/* ============================================================
   SYMPHO · EB — Copiloto como ícono flotante en el top bar
   Click abre un pop-up con el motor de IA en modo chat.
   ============================================================ */

function EbCopilotButton() {
  const nav = useNav();
  const [open, setOpen] = useState(false);
  const ref = useRef();
  useOutside([ref], () => setOpen(false));
  if (!nav || nav.loc.view !== "app" || nav.loc.appId !== "eb") return null;
  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button className="ic-btn" data-on={open} title="Copiloto IA" onClick={() => setOpen(v => !v)}>
        <Icon name="sparkle" size={17} stroke={1.6} />
      </button>
      {open && <EbCopilotPanel onClose={() => setOpen(false)} />}
    </div>
  );
}

function EbCopilotPanel({ onClose }) {
  const [q, setQ] = useState("");
  const [log, setLog] = useState([{ role: "bot", text: "Pregúntame sobre ventas por plaza, stock de refacciones, tiempos de entrega o ranking de dealers." }]);
  function ask(e) {
    e.preventDefault();
    if (!q.trim()) return;
    const ql = q.toLowerCase();
    const hit = window.EB_COPILOT_QA.find(x => x.kw.some(k => ql.includes(k)));
    const a = hit ? hit.a : "No tengo un dato exacto para eso aún — intenta preguntar por ventas de una plaza, stock de refacciones, tiempos de entrega o el ranking de dealers.";
    setLog(l => [...l, { role: "user", text: q }, { role: "bot", text: a }]);
    setQ("");
  }
  return (
    <div className="pop eb-copilot-pop" style={{ right: 0, top: "calc(100% + 8px)" }} onMouseDown={e => e.stopPropagation()}>
      <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "2px 4px 12px" }}>
        <span className="feed-ic" style={{ "--c": "var(--eb)", width: 28, height: 28 }}><Icon name="sparkle" size={14} /></span>
        <b style={{ fontSize: 13.5 }}>Copiloto</b>
        <span className="muted" style={{ fontSize: 11 }}>· IA de Eb</span>
        <button className="ic-btn" style={{ marginLeft: "auto", width: 26, height: 26 }} onClick={onClose}><Icon name="ext" size={13} /></button>
      </div>
      <div className="eb-copilot-log" style={{ maxHeight: 300 }}>
        {log.map((m, i) => <div key={i} className="eb-copilot-msg" data-role={m.role}>{m.text}</div>)}
      </div>
      <form onSubmit={ask} style={{ display: "flex", gap: 8, marginTop: 12 }}>
        <input className="field" value={q} onChange={e => setQ(e.target.value)} placeholder="¿Cuánto vendió Guanajuato?" style={{ flex: 1, height: 34 }} autoFocus />
        <button className="btn btn-sm btn-primary" style={{ background: "var(--eb)" }}><Icon name="arrowr" size={13} /></button>
      </form>
    </div>
  );
}

Object.assign(window, { EbCopilotButton, EbCopilotPanel });
