/* global React */
// Terminal LatAm — Conversation pane (slide-out copilot, ⌘K)

const TCV_T = window.T_THEME;
const TCV_FM = window.T_FM;
const TCV_FS = window.T_FS;
const TCV_B = window.TerminalBtn;

const SCRIPTED = [
  {
    role: "agent",
    type: "text",
    content: "buenos días Pablo · revisé pacing intra-día de UAR · detecté 2 anomalías P1 · ¿quieres que las traiga al Inbox o las resuelvo dentro de auto-budget?",
    tool: null,
  },
];

const SUGGESTED = [
  "¿qué pasó con CPL UAR ayer?",
  "muéstrame top 3 oportunidades hoy",
  "explícame el lock semanal",
  "compara MMM vs platform último mes",
  "abre Diagnose para SeguroFácil",
  "qué creatives están fatigándose",
];

const TOOL_LIBRARY = {
  "get_pacing": { label: "platform.read · pacing UAR", out: "spend 67% del día · pacing -8% vs target" },
  "query_mmm": { label: "mmm.query · meridian.run", out: "MMM Apr · Meta 0.81 · GAds 1.12 · TT 0.34" },
  "diagnose": { label: "diagnose.tree · SeguroFácil", out: "frag detected · 47 ad sets · ML starvation P1" },
};

// Streaming hook
const useStream = (text, speed = 14) => {
  const [done, setDone] = React.useState("");
  React.useEffect(() => {
    setDone("");
    if (!text) return;
    let i = 0;
    const id = setInterval(() => {
      i += 2;
      setDone(text.slice(0, i));
      if (i >= text.length) clearInterval(id);
    }, speed);
    return () => clearInterval(id);
  }, [text, speed]);
  return done;
};

const StreamingMessage = ({ text }) => {
  const shown = useStream(text);
  const live = shown.length < text.length;
  return (
    <span>
      {shown}
      {live && <span style={{ display: "inline-block", width: 7, height: 12, background: TCV_T.amber, marginLeft: 2, verticalAlign: "middle", animation: "blink 0.6s infinite" }} />}
    </span>
  );
};

const ToolCallLine = ({ tool, out }) => (
  <div style={{ margin: "8px 0", padding: "8px 12px", background: TCV_T.bg, border: `1px solid ${TCV_T.line}`, borderLeft: `2px solid ${TCV_T.cyan}`, fontFamily: TCV_FM, fontSize: 10 }}>
    <div style={{ color: TCV_T.cyan, marginBottom: 3 }}>● tool · {tool}</div>
    <div style={{ color: TCV_T.muteDim }}>↳ {out}</div>
  </div>
);

const InlineActionCard = ({ a, onOpen }) => (
  <div style={{ margin: "10px 0", border: `1px solid ${TCV_T.line}`, borderLeft: `3px solid ${TCV_T.amber}`, background: TCV_T.surface, padding: "10px 12px" }}>
    <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
      <span style={{ fontSize: 9, color: TCV_T.amber, letterSpacing: "0.16em", fontFamily: TCV_FM }}>{a.priority} · INLINE</span>
      <span style={{ fontSize: 9, color: TCV_T.muteDim, fontFamily: TCV_FM }}>conf {a.confidence.toFixed(2)}</span>
    </div>
    <div style={{ fontSize: 12, color: TCV_T.ink, fontFamily: TCV_FS, fontWeight: 500 }}>{a.title}</div>
    <div style={{ fontSize: 10, color: TCV_T.green, fontFamily: TCV_FM, marginTop: 4 }}>{a.impact.primary}</div>
    <div style={{ display: "flex", gap: 4, marginTop: 8 }}>
      <TCV_B kind="green" onClick={() => onOpen(a, "approve")}>APPROVE</TCV_B>
      <TCV_B kind="amber" onClick={() => onOpen(a, "modify")}>MODIFY</TCV_B>
      <TCV_B onClick={() => onOpen(a, "schedule")}>SCHEDULE</TCV_B>
    </div>
  </div>
);

const ConversationPane = ({ open, onClose, scope }) => {
  const D = window.MA_DATA;
  const [messages, setMessages] = React.useState(SCRIPTED);
  const [input, setInput] = React.useState("");
  const [thinking, setThinking] = React.useState(false);
  const hitl = window.useHITL();
  const scrollRef = React.useRef();

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

  React.useEffect(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key === "k") {
        e.preventDefault();
        if (open) onClose(); else window.dispatchEvent(new CustomEvent("ma:open-cmd"));
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  const onSend = (text) => {
    if (!text.trim()) return;
    const newMsgs = [...messages, { role: "user", type: "text", content: text }];
    setMessages(newMsgs);
    setInput("");
    setThinking(true);

    setTimeout(() => {
      const lower = text.toLowerCase();
      let reply = { role: "agent", type: "text", content: "Procesando · busco evidencia y traigo data..." };
      let extras = [];

      if (lower.includes("cpl") || lower.includes("uar") || lower.includes("ayer")) {
        extras.push({ role: "agent", type: "tool", tool: "get_pacing" });
        reply = { role: "agent", type: "text", content: "CPL UAR ayer cerró S/ 41.20 · -29.9% vs prev semana · driver principal: ad set #7 (Hero · LAL 1%) ganó share por mejor hook rate. Te traigo la acción de consolidar más spend ahí?", offerAction: "act-001" };
      } else if (lower.includes("oportunidades") || lower.includes("opp") || lower.includes("top")) {
        reply = { role: "agent", type: "text", content: "3 acciones top hoy · todas con conf > 0.85:", offerActions: D.actions.pending.slice(0,3).map(a => a.id) };
      } else if (lower.includes("lock") || lower.includes("semanal")) {
        reply = { role: "agent", type: "text", content: "Lock semanal previene tinkering · congela budget allocations 6 días · solo emergencias se aprueban (CPL +25% sostenido 12h o anomaly P0). Próximo unlock: jueves 11:00. Tinkering reduce eficiencia ~7% según tu propio histórico." };
      } else if (lower.includes("mmm") || lower.includes("vs platform")) {
        extras.push({ role: "agent", type: "tool", tool: "query_mmm" });
        reply = { role: "agent", type: "text", content: "Divergencia MMM vs Platform Apr · Meta over-attributes 23% (CAPI dedup falló 3 días) · GAds under 11% (view-through cortado en CMv2). Recomiendo correr Geo-lift Meta-LATAM próx ventana." };
      } else if (lower.includes("diagnose") || lower.includes("seguro")) {
        extras.push({ role: "agent", type: "tool", tool: "diagnose" });
        reply = { role: "agent", type: "text", content: "SeguroFácil · 47 ad sets activos · clásico anti-pattern de fragmentación. Cada ad set captura <50 events/sem → ML starvation. Plan: consolidar a 11 ad sets agrupados por audience seed × creative theme. Impacto modelado: -S/ 8.4k/mes desperdicio.", offerAction: "act-003" };
      } else if (lower.includes("creative") || lower.includes("fatig")) {
        reply = { role: "agent", type: "text", content: "12 creatives en zona fatigada (frequency >3.2 con CTR cayendo 7d). Top 3 a pausar: Hero-V2 (UAR), Form-Direct-A (SF), Tour-Surco-B (VL). Te abro la matriz creativa? F6 ó dilo aquí." };
      } else {
        reply = { role: "agent", type: "text", content: "Entendido · busco contexto. Mientras tanto, ¿quieres que arranque alguna de estas? top oportunidades · diagnose · MMM vs platform" };
      }

      setMessages(m => [...m, ...extras, reply]);
      setThinking(false);
    }, 700 + Math.random() * 600);
  };

  const openHITL = (a, kind) => hitl.open(kind, { action: a });
  const onResolved = () => hitl.close();

  if (!open) return null;

  return (
    <>
      <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "transparent", zIndex: 8000 }} />
      <div style={{
        position: "fixed", top: 0, right: 0, bottom: 0, width: 460, zIndex: 8500,
        background: TCV_T.bg, borderLeft: `1px solid ${TCV_T.line}`, boxShadow: "-20px 0 60px rgba(0,0,0,0.5)",
        display: "flex", flexDirection: "column", fontFamily: TCV_FS,
      }}>
        {/* HEADER */}
        <div style={{ padding: "14px 18px", borderBottom: `1px solid ${TCV_T.line}`, display: "flex", alignItems: "center", gap: 10 }}>
          <span style={{ width: 8, height: 8, background: TCV_T.green, borderRadius: 99, boxShadow: `0 0 8px ${TCV_T.green}`, animation: "blink 2s infinite" }} />
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: TCV_FM, fontSize: 11, color: TCV_T.amber, letterSpacing: "0.18em" }}>// AGENT · CONVERSATION</div>
            <div style={{ fontSize: 11, color: TCV_T.mute, marginTop: 2 }}>scope · <span style={{ color: TCV_T.cyan }}>{scope || "portfolio"}</span> · model · haiku-4.5</div>
          </div>
          <button onClick={onClose} style={{ background: "none", border: `1px solid ${TCV_T.line}`, color: TCV_T.mute, fontFamily: TCV_FM, fontSize: 10, padding: "4px 8px", cursor: "pointer" }}>⌘K · CLOSE</button>
        </div>

        {/* MESSAGES */}
        <div ref={scrollRef} style={{ flex: 1, overflowY: "auto", padding: "16px 18px" }}>
          {messages.map((m, i) => {
            if (m.type === "tool") {
              const t = TOOL_LIBRARY[m.tool] || { label: m.tool, out: "ok" };
              return <ToolCallLine key={i} tool={t.label} out={t.out} />;
            }
            const isAgent = m.role === "agent";
            const isLast = i === messages.length - 1;
            return (
              <div key={i} style={{ marginBottom: 14 }}>
                <div style={{ fontFamily: TCV_FM, fontSize: 10, color: isAgent ? TCV_T.amber : TCV_T.cyan, marginBottom: 4 }}>
                  {isAgent ? "agent>" : "pablo>"}
                </div>
                <div style={{ fontSize: 12, color: TCV_T.ink, lineHeight: 1.6, fontFamily: TCV_FS }}>
                  {isAgent && isLast ? <StreamingMessage text={m.content} /> : m.content}
                </div>
                {m.offerAction && (() => {
                  const a = D.actions.pending.find(x => x.id === m.offerAction);
                  return a ? <InlineActionCard a={a} onOpen={openHITL} /> : null;
                })()}
                {m.offerActions && m.offerActions.map(id => {
                  const a = D.actions.pending.find(x => x.id === id);
                  return a ? <InlineActionCard key={id} a={a} onOpen={openHITL} /> : null;
                })}
              </div>
            );
          })}
          {thinking && (
            <div style={{ display: "flex", gap: 4, padding: "8px 0", color: TCV_T.amber, fontSize: 11, fontFamily: TCV_FM }}>
              <span style={{ animation: "blink 0.8s infinite" }}>●</span>
              <span style={{ animation: "blink 0.8s infinite 0.2s" }}>●</span>
              <span style={{ animation: "blink 0.8s infinite 0.4s" }}>●</span>
              <span style={{ marginLeft: 6, color: TCV_T.muteDim }}>agent procesando...</span>
            </div>
          )}
        </div>

        {/* QUICK COMMANDS */}
        {messages.length < 3 && (
          <div style={{ padding: "10px 18px", borderTop: `1px solid ${TCV_T.line}`, background: TCV_T.surface }}>
            <div style={{ fontSize: 9, color: TCV_T.muteDim, letterSpacing: "0.14em", marginBottom: 6 }}>SUGGESTED</div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 5 }}>
              {SUGGESTED.map(s => (
                <button key={s} onClick={() => onSend(s)} style={{
                  padding: "5px 10px", background: TCV_T.bg, border: `1px solid ${TCV_T.line}`,
                  color: TCV_T.cyan, fontSize: 10, fontFamily: TCV_FM, cursor: "pointer", whiteSpace: "nowrap",
                }}>{s}</button>
              ))}
            </div>
          </div>
        )}

        {/* INPUT */}
        <div style={{ padding: "12px 18px 16px", borderTop: `1px solid ${TCV_T.line}`, background: TCV_T.surface }}>
          <div style={{ display: "flex", gap: 6, alignItems: "flex-end" }}>
            <span style={{ fontFamily: TCV_FM, fontSize: 11, color: TCV_T.cyan, paddingBottom: 8 }}>pablo&gt;</span>
            <textarea
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); onSend(input); } }}
              placeholder="pregunta · ordena · explora..."
              style={{
                flex: 1, minHeight: 36, maxHeight: 120, padding: "8px 10px", background: TCV_T.bg,
                border: `1px solid ${TCV_T.line}`, color: TCV_T.ink, fontFamily: TCV_FM, fontSize: 12,
                resize: "none", outline: "none",
              }}
            />
            <button onClick={() => onSend(input)} disabled={!input.trim()} style={{
              padding: "8px 14px", background: TCV_T.bg, border: `1px solid ${input.trim() ? TCV_T.amber : TCV_T.line}`,
              color: input.trim() ? TCV_T.amber : TCV_T.muteDim, fontFamily: TCV_FM, fontSize: 11, letterSpacing: "0.14em",
              cursor: input.trim() ? "pointer" : "default",
            }}>↵ SEND</button>
          </div>
          <div style={{ marginTop: 6, fontSize: 9, color: TCV_T.muteDim, fontFamily: TCV_FM, letterSpacing: "0.06em" }}>
            ⌘K toggle · ↵ enviar · ⇧↵ nueva línea · cualquier acción que proponga el agente abre el flujo HITL
          </div>
        </div>

        <window.HITLPortal modal={hitl.modal} onClose={hitl.close} onResolved={onResolved} />
      </div>
    </>
  );
};

window.ConversationPane = ConversationPane;
