/* common.jsx — shared components & icons (VER Clipping) */

const Icon = ({ name, className = "ico" }) => {
  const paths = {
    dashboard: <><path d="M3 3h7v9H3z"/><path d="M14 3h7v5h-7z"/><path d="M14 12h7v9h-7z"/><path d="M3 16h7v5H3z"/></>,
    review:    <><path d="M4 4h16v14H4z"/><path d="M8 9h8M8 13h5"/><path d="M16.5 19.5l2 2 3.5-3.5"/></>,
    clients:   <><circle cx="9" cy="8" r="3.5"/><path d="M2.5 19.5c.6-3.4 3.2-5.5 6.5-5.5s5.9 2.1 6.5 5.5"/><circle cx="17" cy="7" r="2.5"/><path d="M15 13.5c2.5-.2 5 1.2 5.7 4"/></>,
    portals:   <><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 9h18"/><path d="M7 4v5"/></>,
    history:   <><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></>,
    metrics:   <><path d="M4 20V10M10 20V4M16 20v-7M22 20H2"/></>,
    plus:      <><path d="M12 5v14M5 12h14"/></>,
    search:    <><circle cx="11" cy="11" r="6.5"/><path d="M20 20l-3.5-3.5"/></>,
    check:     <><path d="M5 12.5l4 4 10-10"/></>,
    checkCircle: <><circle cx="12" cy="12" r="9"/><path d="M8 12.5l2.5 2.5L16 9.5"/></>,
    clock:     <><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></>,
    send:      <><path d="M22 2L11 13"/><path d="M22 2l-7 20-4-9-9-4z"/></>,
    edit:      <><path d="M14 4l6 6L8 22H2v-6L14 4z"/></>,
    trash:     <><path d="M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13"/></>,
    pause:     <><rect x="6" y="5" width="4" height="14"/><rect x="14" y="5" width="4" height="14"/></>,
    play:      <><path d="M7 5v14l12-7z"/></>,
    close:     <><path d="M6 6l12 12M18 6L6 18"/></>,
    eye:       <><path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z"/><circle cx="12" cy="12" r="3"/></>,
    download:  <><path d="M12 3v12"/><path d="M7 11l5 5 5-5"/><path d="M4 21h16"/></>,
    refresh:   <><path d="M21 12a9 9 0 1 1-3-6.7L21 8"/><path d="M21 3v5h-5"/></>,
    chevron:   <><path d="M9 6l6 6-6 6"/></>,
    alert:     <><path d="M12 9v4M12 17v.01"/><path d="M10.3 3.9L2.5 18a2 2 0 0 0 1.7 3h15.6a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z"/></>,
    link:      <><path d="M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1 1"/><path d="M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1-1"/></>,
    pdf:       <><path d="M7 3h7l5 5v13H7z" fill="none"/><path d="M14 3v5h5"/><path d="M9.5 17v-3h1a1 1 0 0 1 0 2h-1"/></>,
    drive:     <><path d="M8 3h8l5 9-4 7H7l-4-7z"/><path d="M8 3l-5 9M16 3l5 9M7 19l4-7M3 12h18"/></>,
    mail:      <><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 7l9 6 9-6"/></>,
    x:         <><path d="M6 6l12 12M18 6L6 18"/></>,
    bot:       <><rect x="4" y="8" width="16" height="11" rx="2"/><path d="M12 8V4M9 4h6"/><circle cx="9" cy="13" r="1" fill="currentColor"/><circle cx="15" cy="13" r="1" fill="currentColor"/></>,
    lock:      <><rect x="4" y="11" width="16" height="9" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></>,
    flame:     <><path d="M12 3c1 3 4 4 4 8a4 4 0 0 1-8 0c0-2 1-3 1-3 0 1.5 1 2 1 2 .5-2-1.5-4 2-7z"/></>,
    flag:      <><path d="M5 21V4M5 4h11l-2 4 2 4H5"/></>,
    save:      <><path d="M5 3h12l4 4v14H5z"/><path d="M8 3v6h8V3M8 21v-7h8v7"/></>,
  };
  return (
    <svg className={className} viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      {paths[name]}
    </svg>
  );
};

const Toggle = ({ on, onChange }) => (
  <span className={"toggle" + (on ? " is-on" : "")} onClick={() => onChange && onChange(!on)} role="switch" aria-checked={on} />
);

const Status = ({ kind, children }) => (
  <span className={"status status--" + kind}><span className="dot" />{children}</span>
);

const Modal = ({ title, subtitle, wide, onClose, children, footer }) => {
  React.useEffect(() => {
    const onKey = (e) => e.key === "Escape" && onClose && onClose();
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);
  return (
    <div className="modal-bg" onClick={onClose}>
      <div className={"modal" + (wide ? " modal--wide" : "")} onClick={(e) => e.stopPropagation()}>
        <div className="modal__head">
          <div>
            <h2>{title}</h2>
            {subtitle ? <p>{subtitle}</p> : null}
          </div>
          <button className="modal__close" onClick={onClose} aria-label="Fechar"><Icon name="close" /></button>
        </div>
        <div className="modal__body">{children}</div>
        {footer ? <div className="modal__foot">{footer}</div> : null}
      </div>
    </div>
  );
};

const KeywordEditor = ({ keywords, onChange, variant, placeholder = "Adicionar + Enter" }) => {
  const [draft, setDraft] = React.useState("");
  const add = () => {
    const v = draft.trim().replace(/,$/, "");
    if (!v) return;
    if (keywords.includes(v)) { setDraft(""); return; }
    onChange([...keywords, v]); setDraft("");
  };
  return (
    <div className="kw-list">
      {keywords.map(kw => (
        <span key={kw} className={"chip chip--removable" + (variant === "b" ? " is-b" : "")}>
          {kw}
          <button onClick={() => onChange(keywords.filter(k => k !== kw))} aria-label={"Remover " + kw}>
            <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
          </button>
        </span>
      ))}
      <input className="kw-input" value={draft} onChange={(e) => setDraft(e.target.value)}
        onKeyDown={(e) => {
          if (e.key === "Enter" || e.key === ",") { e.preventDefault(); add(); }
          if (e.key === "Backspace" && !draft && keywords.length) onChange(keywords.slice(0, -1));
        }}
        onBlur={add} placeholder={placeholder} />
    </div>
  );
};

const Search = ({ value, onChange, placeholder = "Buscar..." }) => (
  <div className="search">
    <Icon name="search" />
    <input value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} />
  </div>
);

const Toast = ({ message, onDone }) => {
  React.useEffect(() => {
    const t = setTimeout(() => onDone && onDone(), 2600);
    return () => clearTimeout(t);
  }, [onDone]);
  return (<div className="toast"><Icon name="check" className="ok" /><span>{message}</span></div>);
};

/* tiny inline SVG charts ---------------------------------------- */
const StackedBars = ({ data, max }) => {
  const m = max || Math.max(...data.map(d => d.saiu + d.clipping), 1);
  return (
    <div style={{ display: "flex", alignItems: "flex-end", gap: 14, height: 150, padding: "4px 0" }}>
      {data.map((d, i) => {
        const total = d.saiu + d.clipping;
        const h = (total / m) * 130;
        const saiuH = total ? (d.saiu / total) * h : 0;
        const clipH = h - saiuH;
        return (
          <div key={i} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 6 }}>
            <div style={{ fontSize: 11, color: "var(--ink-500)", fontVariantNumeric: "tabular-nums" }}>{total}</div>
            <div style={{ width: "100%", maxWidth: 46, display: "flex", flexDirection: "column", justifyContent: "flex-end", height: 130 }}>
              <div style={{ height: clipH, background: "var(--ink-300)", borderRadius: "4px 4px 0 0" }} />
              <div style={{ height: saiuH, background: "var(--brand)", borderRadius: saiuH && !clipH ? "4px 4px 0 0" : 0 }} />
            </div>
            <div style={{ fontSize: 11, color: "var(--ink-500)" }}>{d.label}</div>
          </div>
        );
      })}
    </div>
  );
};

const LineChart = ({ series, color = "var(--brand)", height = 90, suffix = "" }) => {
  const w = 320, h = height, pad = 6;
  const max = Math.max(...series) * 1.1, min = Math.min(...series) * 0.85;
  const range = max - min || 1;
  const pts = series.map((v, i) => {
    const x = pad + (i / (series.length - 1)) * (w - pad * 2);
    const y = pad + (1 - (v - min) / range) * (h - pad * 2);
    return [x, y];
  });
  const d = pts.map((p, i) => (i ? "L" : "M") + p[0].toFixed(1) + " " + p[1].toFixed(1)).join(" ");
  const area = d + ` L${pts[pts.length-1][0].toFixed(1)} ${h-pad} L${pts[0][0].toFixed(1)} ${h-pad} Z`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" height={h} preserveAspectRatio="none" style={{ display: "block" }}>
      <path d={area} fill={color} opacity="0.08" />
      <path d={d} fill="none" stroke={color} strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />
      {pts.map((p, i) => <circle key={i} cx={p[0]} cy={p[1]} r={i === pts.length - 1 ? 3.5 : 2.2} fill={color} />)}
    </svg>
  );
};

Object.assign(window, { Icon, Toggle, Status, Modal, KeywordEditor, Search, Toast, StackedBars, LineChart });
