/* ============================================================
   SKYVIDYA AI — AgentSpec panel + chat engine hook
   ============================================================ */

const { useState, useEffect, useRef, useMemo } = React;

/* ---------- chat engine ---------- */
function useAgentChat() {
  const [messages, setMessages] = useState([]);
  const [busy, setBusy] = useState(false);
  const timers = useRef([]);
  const idc = useRef(0);

  function clearTimers() { timers.current.forEach(clearTimeout); timers.current = []; }
  function wait(ms) { return new Promise((res) => { const t = setTimeout(res, ms); timers.current.push(t); }); }

  useEffect(() => () => clearTimers(), []);

  async function run(userText, resp) {
    setBusy(true);
    const uid = ++idc.current;
    setMessages((m) => [...m, { id: "u" + uid, role: "user", text: userText }]);
    await wait(260);

    const aid = "a" + uid;
    const agentList = resp.agents.map((id) => SKY.agents.find((a) => a.id === id)).filter(Boolean);
    setMessages((m) => [...m, {
      id: aid, role: "ai", resp, agentList,
      agentStatus: agentList.map(() => "pending"),
      revealed: 0, typing: "", typingIdx: -1, done: false,
    }]);

    // animate agents sequentially
    for (let i = 0; i < agentList.length; i++) {
      setMessages((m) => m.map((x) => x.id === aid ? { ...x, agentStatus: x.agentStatus.map((s, k) => k === i ? "running" : s) } : x));
      await wait(420 + Math.random() * 280);
      setMessages((m) => m.map((x) => x.id === aid ? { ...x, agentStatus: x.agentStatus.map((s, k) => k === i ? "done" : s) } : x));
      await wait(90);
    }
    await wait(220);

    // reveal blocks; typewriter on text blocks
    const blocks = resp.blocks;
    for (let b = 0; b < blocks.length; b++) {
      const blk = blocks[b];
      if (blk.type === "p") {
        setMessages((m) => m.map((x) => x.id === aid ? { ...x, revealed: b, typingIdx: b, typing: "" } : x));
        const full = blk.text;
        const step = Math.max(1, Math.round(full.length / 60));
        for (let c = 0; c <= full.length; c += step) {
          setMessages((m) => m.map((x) => x.id === aid ? { ...x, typing: full.slice(0, c) } : x));
          await wait(16);
        }
        setMessages((m) => m.map((x) => x.id === aid ? { ...x, typing: full, revealed: b + 1, typingIdx: -1 } : x));
      } else {
        setMessages((m) => m.map((x) => x.id === aid ? { ...x, revealed: b + 1, typingIdx: -1 } : x));
        await wait(360);
      }
      await wait(120);
    }
    setMessages((m) => m.map((x) => x.id === aid ? { ...x, done: true } : x));
    setBusy(false);
  }

  function askPrompt(promptKey, customText) {
    if (busy) return;
    const qp = SKY.quickPrompts.find((q) => q.id === promptKey);
    const resp = SKY.responses[promptKey] || SKY.genericResponse;
    run(customText || (qp ? qp.text : promptKey), resp);
  }
  function askHex(hex) {
    if (busy) return;
    run(`Analisar hexágono ${hex.code} · ${hex.regionName}`, SKY.hexResponse(hex));
  }
  function askGeoHex(cell) {
    if (busy) return;
    run(`Analisar célula H3 ${cell.h3.slice(0,9)}… · ${cell.region}`, SKY.geoHexResponse(cell));
  }
  function askFree(text) {
    if (busy) return;
    const t = text.toLowerCase();
    let key = null;
    if (/deterior|piora|caind|pior/.test(t)) key = "deteriorando";
    else if (/pescaria|nível a|nivel a|melhores produtores/.test(t)) key = "pescarias";
    else if (/exposi|limit|20%|carteira|sinistralidade/.test(t)) key = "exposicao";
    else if (/fraude|anomal|passo fundo|decreto/.test(t)) key = "fraude";
    run(text, key ? SKY.responses[key] : SKY.genericResponse);
  }
  function reset() { clearTimers(); setMessages([]); setBusy(false); }

  return { messages, busy, askPrompt, askHex, askGeoHex, askFree, reset };
}

/* ---------- agent trace row ---------- */
function AgentRow({ agent, status }) {
  return (
    <div className={"agent-row " + status}>
      <span className="agent-led">
        {status === "done" ? <Icon name="check" size={11} />
          : status === "running" ? <span className="led-spin" />
          : <span className="led-idle" />}
      </span>
      <span className="agent-name">{agent.name}</span>
      <span className="agent-state mono">
        {status === "done" ? "concluído" : status === "running" ? "processando" : "pendente"}
      </span>
    </div>
  );
}

/* ---------- response block renderer ---------- */
function RespBlocks({ msg }) {
  const { resp, revealed, typing, typingIdx } = msg;
  return (
    <div className="resp-body">
      {resp.blocks.map((blk, i) => {
        if (i >= revealed && i !== typingIdx) return null;
        const isTyping = i === typingIdx;
        if (blk.type === "p") {
          return <p key={i} className="resp-p fade-up">{isTyping ? typing : blk.text}{isTyping && <span className="caret" />}</p>;
        }
        if (blk.type === "finding") {
          return (
            <div key={i} className={"finding fade-up tone-" + blk.tone}>
              <div className="finding-title"><span className="finding-dot" /> {blk.title}</div>
              <ul>{blk.lines.map((l, k) => <li key={k}>{l}</li>)}</ul>
            </div>
          );
        }
        if (blk.type === "sim") {
          return (
            <div key={i} className="sim-table fade-up">
              {blk.rows.map((r, k) => (
                <div className="sim-row" key={k}>
                  <span className="sim-limit mono">limite {r.limit}</span>
                  <span className="sim-red mono">{r.reducao}</span>
                  <span className="sim-note">{r.note}</span>
                </div>
              ))}
            </div>
          );
        }
        return null;
      })}
    </div>
  );
}

/* ---------- main panel ---------- */
function AIPanel({ chat, onAction, collapsed, onToggle }) {
  const { messages, busy, askPrompt, askFree } = chat;
  const [input, setInput] = useState("");
  const scrollRef = useRef(null);
  const hasChat = messages.length > 0;

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages]);

  function submit(e) {
    e.preventDefault();
    if (!input.trim() || busy) return;
    askFree(input.trim());
    setInput("");
  }

  return (
    <aside className={"ai-panel" + (collapsed ? " collapsed" : "")}>
      <div className="ai-head">
        <div className="ai-title">
          <span className="ai-glyph"><Icon name="sparkles" size={15} color="var(--sv-cyan)" /></span>
          <div className="col" style={{ lineHeight: 1.2 }}>
            <b>Skyvidya AI</b>
            <span className="mono ai-sub">{busy ? "AgentSpec · orquestrando…" : "AgentSpec · 6 agentes"}</span>
          </div>
        </div>
        <button className="ai-collapse" onClick={onToggle} title="Recolher painel">
          <Icon name="chevR" size={16} />
        </button>
      </div>

      <div className="ai-scroll" ref={scrollRef}>
        {!hasChat && (
          <div className="ai-idle">
            <p className="ai-idle-lead">Pergunte sobre o portfólio agrícola do recorte Sul. Cada resposta mostra quais agentes foram orquestrados.</p>
            <div className="quick-list">
              {SKY.quickPrompts.map((q) => (
                <button key={q.id} className="quick-chip" disabled={busy} onClick={() => askPrompt(q.id)}>
                  <Icon name={{ "trend-down":"trendDown", gem:"gem", sliders:"sliders", alert:"alert" }[q.icon]} size={14} color="var(--sv-cyan)" />
                  <span>{q.text}</span>
                  <Icon name="arrowR" size={13} className="qc-arrow" />
                </button>
              ))}
            </div>
            <div className="ai-agents-legend">
              <span className="eyebrow" style={{ marginBottom: 8, display: "block" }}>Agentes disponíveis</span>
              {SKY.agents.map((a) => (
                <div className="legend-agent" key={a.id}>
                  <span className="la-dot" /><b>{a.name}</b><span>{a.desc}</span>
                </div>
              ))}
            </div>
          </div>
        )}

        {messages.map((m) => (
          m.role === "user" ? (
            <div className="msg-user" key={m.id}><span>{m.text}</span></div>
          ) : (
            <div className="msg-ai" key={m.id}>
              <div className="agent-trace">
                <div className="trace-head"><Icon name="cpu" size={12} /> <span className="mono">orquestração agentspec</span></div>
                {m.agentList.map((a, i) => <AgentRow key={a.id} agent={a} status={m.agentStatus[i]} />)}
              </div>
              {m.revealed > 0 || m.typingIdx >= 0 ? <RespBlocks msg={m} /> : null}
              {m.done && m.resp.actions && m.resp.actions.length > 0 && (
                <div className="resp-actions fade-up">
                  {m.resp.actions.map((a, i) => (
                    <button key={i} className="resp-action" onClick={() => onAction && onAction(a.to)}>
                      <Icon name="arrowR" size={12} />{a.label}
                    </button>
                  ))}
                </div>
              )}
            </div>
          )
        ))}
      </div>

      <form className="ai-input" onSubmit={submit}>
        <input value={input} onChange={(e) => setInput(e.target.value)} disabled={busy}
          placeholder={busy ? "Orquestrando agentes…" : "Analise o portfólio para o IRB…"} />
        <button type="submit" className="ai-send" disabled={busy || !input.trim()}>
          <Icon name="send" size={15} />
        </button>
      </form>
    </aside>
  );
}

Object.assign(window, { useAgentChat, AIPanel });
