/* ============================================================
   KeS Metas — Primitivos de UI (compartilhados via window)
   ============================================================ */
const { useState, useEffect, useRef, useMemo } = React;

/* ---------- Ícones (estilo Lucide, traço arredondado) ---------- */
const ICON_PATHS = {
  dashboard: '<rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/>',
  calendar: '<rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/>',
  calendarCheck: '<rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18M9 16l2 2 4-4"/>',
  users: '<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"/>',
  user: '<path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>',
  target: '<circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="5"/><circle cx="12" cy="12" r="1.4" fill="currentColor" stroke="none"/>',
  sliders: '<path d="M4 21v-7M4 10V3M12 21v-9M12 8V3M20 21v-5M20 12V3M1 14h6M9 8h6M17 16h6"/>',
  logout: '<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9"/>',
  menu: '<path d="M3 12h18M3 6h18M3 18h18"/>',
  plus: '<path d="M12 5v14M5 12h14"/>',
  trash: '<path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M10 11v6M14 11v6"/>',
  pencil: '<path d="M12 20h9M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/>',
  check: '<path d="M20 6 9 17l-5-5"/>',
  checkCircle: '<circle cx="12" cy="12" r="9"/><path d="M8.5 12.5l2.5 2.5 4.5-5"/>',
  x: '<path d="M18 6 6 18M6 6l12 12"/>',
  arrowRight: '<path d="M5 12h14M13 6l6 6-6 6"/>',
  chevronLeft: '<path d="M15 18l-6-6 6-6"/>',
  chevronRight: '<path d="M9 18l6-6-6-6"/>',
  chevronDown: '<path d="M6 9l6 6 6-6"/>',
  phone: '<path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92Z"/>',
  link: '<path d="M9 17H7A5 5 0 0 1 7 7h2M15 7h2a5 5 0 0 1 0 10h-2M8 12h8"/>',
  handshake: '<path d="m11 17 2 2a1 1 0 1 0 3-3M11 17l1.5-1.5M16 16l3.5-3.5a1 1 0 0 0 0-1.5L13 4.5a2 2 0 0 0-2.8 0L7 7.7a2 2 0 0 1-2.8 0L3 6.5"/><path d="M7.5 12.5 9 11M6 16l3.5-3.5M3 9l2 2M5 16l3-3"/>',
  trophy: '<path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6M18 9h1.5a2.5 2.5 0 0 0 0-5H18M4 22h16M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22M18 2H6v7a6 6 0 0 0 12 0V2Z"/>',
  banknote: '<rect x="2" y="6" width="20" height="12" rx="2"/><circle cx="12" cy="12" r="2.5"/><path d="M6 12h.01M18 12h.01"/>',
  lock: '<rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>',
  clock: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>',
  trendingUp: '<path d="M23 6l-9.5 9.5-5-5L1 18"/><path d="M17 6h6v6"/>',
  filter: '<path d="M22 3H2l8 9.46V19l4 2v-8.54L22 3z"/>',
  search: '<circle cx="11" cy="11" r="8"/><path d="M21 21l-4.3-4.3"/>',
  alert: '<circle cx="12" cy="12" r="9"/><path d="M12 8v4M12 16h.01"/>',
  mail: '<rect x="2" y="4" width="20" height="16" rx="2"/><path d="m22 7-10 6L2 7"/>',
  mapPin: '<path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z"/><circle cx="12" cy="10" r="3"/>',
  eye: '<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/>',
  eyeOff: '<path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c6.5 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68M6.61 6.61A13.5 13.5 0 0 0 2 11s3.5 7 10 7a9.12 9.12 0 0 0 5.39-1.61M1 1l22 22M14.12 14.12A3 3 0 1 1 9.88 9.88"/>',
  cloudCheck: '<path d="M20 16.2A4.5 4.5 0 0 0 17.5 8h-1.8A7 7 0 1 0 4 14.9"/><path d="m9 14 2 2 4-4"/>',
  refresh: '<path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8M21 3v5h-5M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16M3 21v-5h5"/>',
  sparkles: '<path d="M12 3l1.9 4.9L19 9.8l-4.9 1.9L12 17l-1.9-4.9L5 9.8l4.9-1.9L12 3Z"/>',
  download: '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"/>',
  upload: '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12"/>',
  externalLink: '<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6M15 3h6v6M10 14 21 3"/>',
  grip: '<circle cx="9" cy="6" r="1.3"/><circle cx="9" cy="12" r="1.3"/><circle cx="9" cy="18" r="1.3"/><circle cx="15" cy="6" r="1.3"/><circle cx="15" cy="12" r="1.3"/><circle cx="15" cy="18" r="1.3"/>',
  message: '<path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5Z"/>',
  tag: '<path d="M20.59 13.41 13.42 20.6a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82Z"/><circle cx="7" cy="7" r="1.3" fill="currentColor" stroke="none"/>',
  spreadsheet: '<rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M3 15h18M9 3v18M15 3v18"/>',
  video: '<path d="m22 8-6 4 6 4V8Z"/><rect x="2" y="6" width="14" height="12" rx="2"/>',
  userPlus: '<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M19 8v6M22 11h-6"/>',
  funnel: '<path d="M22 3H2l8 9.46V19l4 2v-8.54L22 3z"/>',
  copy: '<rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>',
};
function Icon({ name, size = 20, strokeWidth = 2, style, className }) {
  return React.createElement("svg", {
    width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor",
    strokeWidth, strokeLinecap: "round", strokeLinejoin: "round", style, className,
    dangerouslySetInnerHTML: { __html: ICON_PATHS[name] || "" },
  });
}
function GoogleG({ size = 18 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24">
      <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.27-4.74 3.27-8.1Z"/>
      <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.65l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84A11 11 0 0 0 12 23Z"/>
      <path fill="#FBBC05" d="M5.84 14.11a6.6 6.6 0 0 1 0-4.22V7.05H2.18a11 11 0 0 0 0 9.9l3.66-2.84Z"/>
      <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1A11 11 0 0 0 2.18 7.05l3.66 2.84C6.71 7.3 9.14 5.38 12 5.38Z"/>
    </svg>
  );
}

/* ---------- Logo ---------- */
function Logo({ size = 38 }) {
  return <img src="ds/logo-mark-red.png" alt="KeS" style={{ width: size, height: size, objectFit: "contain" }} />;
}

/* ---------- Avatar ---------- */
function initials(nome) {
  const p = nome.trim().split(/\s+/);
  return (p[0][0] + (p[1] ? p[1][0] : "")).toUpperCase();
}
function Avatar({ user, size = 38 }) {
  return (
    <div className="avatar" style={{ width: size, height: size, background: user.cor, fontSize: size * 0.38 }}>
      {initials(user.nome)}
    </div>
  );
}

/* ---------- Botão ---------- */
function Btn({ variant = "primary", size, icon, iconRight, disc, children, ...rest }) {
  const cls = ["btn", `btn-${variant}`, size === "sm" ? "btn-sm" : "", rest.className || ""].join(" ").trim();
  const { className, ...r } = rest;
  return (
    <button className={cls} {...r}>
      {disc && <span className="disc"><Icon name="arrowRight" size={12} /></span>}
      {icon && <Icon name={icon} size={size === "sm" ? 15 : 17} />}
      {children}
      {iconRight && <Icon name={iconRight} size={size === "sm" ? 15 : 17} />}
    </button>
  );
}

/* ---------- Progresso + tom de cor ---------- */
function tonePct(pct) {
  if (pct >= 100) return "ok";
  if (pct >= 70) return "warn";
  return "bad";
}
function Progress({ pct }) {
  const t = tonePct(pct);
  return (
    <div className="progress">
      <i className={"bar-" + t} style={{ width: Math.min(100, Math.max(2, pct)) + "%" }} />
    </div>
  );
}

/* ---------- Badge ---------- */
function Badge({ tone = "muted", icon, children }) {
  return (
    <span className={"badge badge-" + tone}>
      {icon && <Icon name={icon} size={13} />}
      {children}
    </span>
  );
}

/* ---------- Campos ---------- */
function Field({ label, error, children }) {
  return (
    <div className="field-group">
      {label && <label className="lbl">{label}</label>}
      {children}
      {error && <div className="form-err"><Icon name="alert" size={14} />{error}</div>}
    </div>
  );
}

/* ---------- Modal ---------- */
function Modal({ title, onClose, children, footer, wide }) {
  useEffect(() => {
    const h = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [onClose]);
  return (
    <div className="overlay" onMouseDown={onClose}>
      <div className="modal" style={wide ? { maxWidth: 620 } : null} onMouseDown={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <h3>{title}</h3>
          <button className="iconbtn" onClick={onClose} aria-label="Fechar"><Icon name="x" /></button>
        </div>
        <div className="modal-body">{children}</div>
        {footer && <div className="modal-foot">{footer}</div>}
      </div>
    </div>
  );
}

/* ---------- Toast ---------- */
function Toast({ toast }) {
  if (!toast) return null;
  return (
    <div style={{
      position: "fixed", bottom: 24, left: "50%", transform: "translateX(-50%)", zIndex: 200,
      background: "var(--bg2)", border: "1px solid var(--border-dark)", borderRadius: "var(--radius-pill)",
      boxShadow: "var(--shadow-lg)", padding: "12px 20px", display: "flex", alignItems: "center", gap: 10,
      fontSize: 13.5, fontWeight: 600, animation: "rise var(--dur-base) var(--ease-out)",
    }}>
      <span style={{ color: "var(--ok)", display: "grid", placeItems: "center" }}><Icon name="cloudCheck" size={18} /></span>
      {toast}
    </div>
  );
}

/* ============================================================
   FILTRO DE PERÍODO
   ============================================================ */
const K = window.KES;
function startOfWeek(d) { const x = new Date(d); const day = (x.getDay() + 6) % 7; x.setDate(x.getDate() - day); return x; }
function buildPreset(name) {
  const today = new Date(K.SIM_TODAY);
  if (name === "hoje") return { preset: "hoje", start: K.iso(today), end: K.iso(today), label: "Hoje" };
  if (name === "semana") { const s = startOfWeek(today); return { preset: "semana", start: K.iso(s), end: K.iso(today), label: "Esta semana" }; }
  if (name === "mes") { const s = new Date(today.getFullYear(), today.getMonth(), 1); return { preset: "mes", start: K.iso(s), end: K.iso(today), label: "Este mês" }; }
  if (name === "mesPassado") {
    const s = new Date(today.getFullYear(), today.getMonth() - 1, 1);
    const e = new Date(today.getFullYear(), today.getMonth(), 0);
    return { preset: "mesPassado", start: K.iso(s), end: K.iso(e), label: "Mês passado" };
  }
  return buildPreset("mes");
}
function PeriodFilter({ value, onChange }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, []);
  const shortcuts = [
    ["hoje", "Hoje"], ["semana", "Esta semana"], ["mes", "Este mês"], ["mesPassado", "Mês passado"],
  ];
  const labelText = value.preset === "custom"
    ? `${K.fmtBR(value.start)} – ${K.fmtBR(value.end)}`
    : value.label;
  return (
    <div className="period" ref={ref}>
      <button className="period-trigger" onClick={() => setOpen((o) => !o)}>
        <Icon name="calendar" size={16} />
        {labelText}
        <Icon name="chevronDown" size={15} />
      </button>
      {open && (
        <div className="period-pop">
          <div className="period-shortcuts">
            {shortcuts.map(([k, lbl]) => (
              <button key={k} className={"chip" + (value.preset === k ? " active" : "")}
                onClick={() => { onChange(buildPreset(k)); setOpen(false); }}>{lbl}</button>
            ))}
          </div>
          <div className="period-custom">
            <Field label="De">
              <input type="date" className="field" value={value.start} max={value.end}
                onChange={(e) => onChange({ ...value, preset: "custom", start: e.target.value, label: "Personalizado" })} />
            </Field>
            <Field label="Até">
              <input type="date" className="field" value={value.end} min={value.start} max={K.iso(K.SIM_TODAY)}
                onChange={(e) => onChange({ ...value, preset: "custom", end: e.target.value, label: "Personalizado" })} />
            </Field>
          </div>
        </div>
      )}
    </div>
  );
}

/* ============================================================
   GRÁFICO DE BARRAS (evolução no período)
   ============================================================ */
function BarChart({ series, target, color = "var(--kes-red)", height = 150 }) {
  // series: [{ label, value }]
  const max = Math.max(target || 0, ...series.map((s) => s.value), 1);
  const W = Math.max(series.length * 26, 300), H = height, pad = 8;
  const bw = (W - pad * 2) / series.length;
  const y = (v) => H - pad - (v / max) * (H - pad * 2);
  const ty = target ? y(target) : null;
  const step = Math.max(1, Math.ceil(series.length / 12));
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={height} preserveAspectRatio="none"
      style={{ display: "block", overflow: "visible" }}>
      {target ? (
        <g>
          <line x1={pad} x2={W - pad} y1={ty} y2={ty} stroke="rgba(255,255,255,.28)" strokeWidth="1" strokeDasharray="4 4" />
          <text x={W - pad} y={ty - 5} textAnchor="end" fontSize="10" fill="var(--fg3)" fontWeight="700">meta {target}</text>
        </g>
      ) : null}
      {series.map((s, i) => {
        const x = pad + i * bw;
        const h = H - pad - y(s.value);
        const reached = target ? s.value >= target : true;
        return (
          <g key={i}>
            <rect x={x + bw * 0.16} y={y(s.value)} width={bw * 0.68} height={Math.max(1, h)} rx="2"
              fill={reached ? color : "var(--kes-navy-700)"} opacity={reached ? 1 : 0.85} />
            {i % step === 0 && (
              <text x={x + bw / 2} y={H + 3} textAnchor="middle" fontSize="9" fill="var(--fg3)">{s.label}</text>
            )}
          </g>
        );
      })}
    </svg>
  );
}

/* ---------- Export global ---------- */
Object.assign(window, {
  Icon, GoogleG, Logo, Avatar, initials, Btn, tonePct, Progress, Badge, Field, Modal, Toast,
  PeriodFilter, buildPreset, BarChart,
});
