/* Darwin Chat — full-screen focused chat (V2)
   API real: POST /api/ask → bot-server
*/

const { useState, useEffect, useRef } = React;


/* ====================================================
   MOCK DATA — histórico de conversa seed
   ==================================================== */
const DEFAULT_SEED = [
  {
    id: 1, pinned: true, group: "today",
    title: "LinkedIn estourou o CPL — investigar",
    lastAt: "10:24",
    messages: [
      { role: "user", content: "O CPL do LinkedIn subiu pra R$ 312 essa semana. O que tá acontecendo?" },
      {
        role: "bot",
        thinking: "DARWIN CRUZOU 3 FONTES · 1.2s",
        content: "**CPL · LinkedIn** subiu **+41%** vs ciclo anterior. Cruzei com a Matriz e tenho 3 fatores explicando quase tudo:",
        bullet: [
          "Audiência **Diretores TI · 50-200** saturou (freq média 4.8x).",
          "Criativo `LI-CR-117` perdeu **38% de CTR** em 5 dias — fadiga.",
          "Concorrência subiu **CPM em 22%** (benchmark da Matriz).",
        ],
        cta: "Quer que eu abra hipótese pra **lookalike de leads MQL**?",
        sources: ["linkedin", "matrix"],
      },
    ],
  },
  { id: 2, pinned: true, group: "today",   title: "Resumo do ciclo C-46 pro board",                  lastAt: "08:09" },
  { id: 3, pinned: false, group: "today",  title: "Quais hipóteses do Meta merecem virar Acelerador?", lastAt: "07:11" },
  { id: 4, group: "yesterday", title: "Por que o CTR de Google caiu sexta?",       lastAt: "ontem · 16h" },
  { id: 5, group: "yesterday", title: "Tese de saturação no Meta — confirmar?",    lastAt: "ontem · 11h" },
  { id: 6, group: "week",      title: "O que travou o pipeline de hipóteses?",     lastAt: "Seg" },
  { id: 7, group: "week",      title: "Comparar CPL Meta vs Google 30d",           lastAt: "Seg" },
  { id: 8, group: "week",      title: "Leads de dezembro por plataforma",          lastAt: "Dom" },
  { id: 9, group: "older",     title: "Cross-channel — proposta de orçamento Q1",  lastAt: "12/jan" },
  { id: 10, group: "older",    title: "Sugestões para o painel executivo",         lastAt: "08/jan" },
];

const SUGGESTIONS = [
  { icon: "📊", title: "Diagnóstico", q: "Por que o CPL caiu no Google últimos 7 dias?" },
  { icon: "💡", title: "Hipótese",    q: "Sugira 3 hipóteses pra reduzir o CPA do Meta." },
  { icon: "📋", title: "Resumo",      q: "Resuma o ciclo atual em 3 bullets pra board." },
  { icon: "⚖",  title: "Comparação",  q: "Compare ROAS Meta vs Google no mês passado." },
];

const QUICK = [
  "Por onde devo começar hoje?",
  "Resumo do ciclo atual",
  "Quais hipóteses virar Acelerador?",
  "Compare CPL Meta vs Google",
];

const SOURCES = {
  meta:     { label: "Meta Ads",   color: "#1877F2" },
  google:   { label: "Google Ads", color: "#EA4335" },
  linkedin: { label: "LinkedIn",   color: "#0A66C2" },
  rd:       { label: "RD Station", color: "#00A571" },
  ga4:      { label: "GA4",        color: "#F6A803" },
  matrix:   { label: "Matriz",     color: "#9FEF00" },
};

/* ====================================================
   PRIMITIVES
   ==================================================== */

function SourceChip({ id }) {
  const s = SOURCES[id];
  if (!s) return null;
  return (
    <span className="chat-src">
      <span className="dot" style={{ background: s.color, boxShadow: `0 0 4px ${s.color}` }}/>
      {s.label}
    </span>
  );
}

function mdInline(s) {
  return (s || "")
    .replace(/&/g, "&amp;").replace(/</g, "&lt;")
    .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
    .replace(/`([^`]+)`/g, '<code>$1</code>');
}

function BotMessage({ m }) {
  return (
    <div className="chat-bot">
      {m.thinking && (
        <div className="chat-thinking">
          <span className="pip"/>
          {m.thinking}
        </div>
      )}
      <div className="chat-bot-bubble">
        {m.content && <p className="chat-content" dangerouslySetInnerHTML={{ __html: mdInline(m.content) }}/>}
        {m.bullet && (
          <ul className="chat-bullet">
            {m.bullet.map((b, i) => <li key={i} dangerouslySetInnerHTML={{ __html: mdInline(b) }}/>)}
          </ul>
        )}
        {m.cta && <p className="chat-cta" dangerouslySetInnerHTML={{ __html: mdInline(m.cta) }}/>}
        {m.sources && m.sources.length > 0 && (
          <div className="chat-sources">
            <span className="chat-sources-label">FONTES</span>
            {m.sources.map(s => <SourceChip key={s} id={s}/>)}
          </div>
        )}
        <div className="chat-actions">
          <button title="Copiar" onClick={() => navigator.clipboard?.writeText(m.content || "")}>⎘ Copiar</button>
        </div>
      </div>
    </div>
  );
}

function UserMessage({ m }) {
  return <div className="chat-user-bubble">{m.content}</div>;
}

/* ====================================================
   DARWIN COMPANION RAIL (right side)
   ==================================================== */

function DarwinCompanion({ state, pose }) {
  const caption = state === "thinking"
    ? "Cruzando suas fontes…"
    : state === "welcome"
    ? "Aguardando você"
    : "Pronto pra próxima";

  const DarwinPose = pose === "writing"  ? DarwinWriting
    : pose === "welcome" ? DarwinWelcome
    : DarwinSitting;

  return (
    <aside className="chat-companion">
      <div className="companion-frame">
        <div className="companion-tag">
          <span className="pip"/> DARWIN
        </div>
        <div className="companion-darwin">
          <DarwinPose size={220}/>
        </div>
        <div className="companion-glow"/>
      </div>

      <div className="companion-card">
        <div className="companion-status">
          <span className={`pip ${state}`}/>
          <span className="state-label">
            {state === "thinking" ? "PENSANDO" : state === "welcome" ? "PRESENTE" : "ATIVO"}
          </span>
        </div>
        <p className="companion-caption">{caption}</p>
        <div className="companion-stats">
          <div><span className="l">MODELO</span><span className="v">Claude</span></div>
          <div><span className="l">SUITE</span><span className="v">v2</span></div>
          <div><span className="l">ACESSO</span><span className="v">Matriz</span></div>
        </div>
      </div>
    </aside>
  );
}

/* ====================================================
   HISTORY (left rail)
   ==================================================== */

function History({ active, onSelect, collapsed, onNew }) {
  const [q, setQ] = useState("");
  const filtered = DEFAULT_SEED.filter(c => !q || c.title.toLowerCase().includes(q.toLowerCase()));
  const groups = {
    pinned:    filtered.filter(c => c.pinned),
    today:     filtered.filter(c => !c.pinned && c.group === "today"),
    yesterday: filtered.filter(c => !c.pinned && c.group === "yesterday"),
    week:      filtered.filter(c => !c.pinned && c.group === "week"),
    older:     filtered.filter(c => !c.pinned && c.group === "older"),
  };
  const labels = { pinned: "📌 Fixadas", today: "Hoje", yesterday: "Ontem", week: "Esta semana", older: "Antes" };

  if (collapsed) {
    return (
      <aside className="chat-hist collapsed">
        <button className="hist-new collapsed" title="Nova conversa" onClick={onNew}>+</button>
      </aside>
    );
  }

  return (
    <aside className="chat-hist">
      <div className="hist-top">
        <button className="hist-new" onClick={onNew}>+ Nova conversa</button>
      </div>
      <div className="hist-search">
        <input value={q} onChange={e => setQ(e.target.value)} placeholder="Buscar…"/>
      </div>
      <div className="hist-list">
        {Object.entries(groups).map(([k, list]) => list.length > 0 && (
          <div key={k} className="hist-group">
            <div className="hist-group-head">{labels[k]}</div>
            {list.map(c => (
              <button key={c.id}
                      className={`hist-conv ${c.id === active ? "active" : ""}`}
                      onClick={() => onSelect(c.id)}>
                <div className="hist-conv-title">{c.title}</div>
                <div className="hist-conv-time">{c.lastAt}</div>
              </button>
            ))}
          </div>
        ))}
      </div>
    </aside>
  );
}

/* ====================================================
   EMPTY STATE
   ==================================================== */

function EmptyState({ onPick }) {
  return (
    <div className="chat-empty">
      <div className="chat-empty-darwin">
        <DarwinWelcome size={200}/>
      </div>

      <div className="chat-empty-copy">
        <div className="chat-empty-eyebrow">
          <span className="pip"/> Darwin · pronto
        </div>
        <h1 className="chat-empty-title">Pode perguntar.</h1>
        <p className="chat-empty-lede">
          Tenho acesso à <strong>Matriz de Inteligência</strong> com dados de Meta, Google, LinkedIn, RD Station e GA4.
          Por onde quer começar?
        </p>
      </div>

      <div className="chat-empty-suggestions">
        {SUGGESTIONS.map((s, i) => (
          <button key={i} className="chat-sug" onClick={() => onPick(s.q)}>
            <div className="chat-sug-icon">{s.icon}</div>
            <div className="chat-sug-meta">
              <div className="chat-sug-title">{s.title}</div>
              <div className="chat-sug-q">{s.q}</div>
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

/* ====================================================
   ROOT
   ==================================================== */

function DarwinChat() {
  const [active, setActive] = useState(null);
  const [conversations, setConversations] = useState(() =>
    Object.fromEntries(DEFAULT_SEED.map(c => [c.id, c.messages ? [...c.messages] : []]))
  );
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const [histCollapsed, setHistCollapsed] = useState(false);
  const bodyRef = useRef(null);
  const textareaRef = useRef(null);

  const messages = active ? (conversations[active] || []) : [];
  const isEmpty  = !active || messages.length === 0;
  const companionState = loading ? "thinking" : isEmpty ? "welcome" : "idle";
  const companionPose  = loading ? "writing" : isEmpty ? "welcome" : "sitting";

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

  // Auto-resize textarea
  useEffect(() => {
    if (!textareaRef.current) return;
    textareaRef.current.style.height = "auto";
    textareaRef.current.style.height = Math.min(textareaRef.current.scrollHeight, 140) + "px";
  }, [input]);

  const newConversation = () => {
    setActive(null);
    setInput("");
    if (textareaRef.current) textareaRef.current.focus();
  };

  const send = (text) => {
    const t = (text ?? input).trim();
    if (!t || loading) return;
    setInput("");

    let convId = active;
    if (!convId) {
      convId = Date.now();
      const title = t.length > 52 ? t.slice(0, 49) + "…" : t;
      DEFAULT_SEED.unshift({ id: convId, group: "today", title, lastAt: "agora" });
      setConversations(c => ({ ...c, [convId]: [] }));
      setActive(convId);
    }

    setConversations(c => ({ ...c, [convId]: [...(c[convId] || []), { role: "user", content: t }] }));
    setLoading(true);

    fetch('/api/ask', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ question: t, user: 'darwin-central', session_id: String(convId) }),
    })
    .then(r => r.json())
    .then(data => {
      const answer = data.answer || data.reply || data.message || "Não consegui uma resposta agora.";
      const lc = t.toLowerCase();
      const sources = [];
      if (/meta|cpl|frequ|criat/i.test(lc)) sources.push("meta");
      if (/google|adwords|search/i.test(lc)) sources.push("google");
      if (/linkedin/i.test(lc)) sources.push("linkedin");
      if (/ga4|sess|tráf/i.test(lc)) sources.push("ga4");
      if (/rd|crm|lead/i.test(lc)) sources.push("rd");
      if (sources.length === 0) sources.push("matrix");

      setConversations(c => ({
        ...c,
        [convId]: [...(c[convId] || []), {
          role: "bot",
          thinking: "DARWIN · MATRIZ DE INTELIGÊNCIA",
          content: answer,
          sources,
        }],
      }));
      setLoading(false);
    })
    .catch(() => {
      setConversations(c => ({
        ...c,
        [convId]: [...(c[convId] || []), {
          role: "bot",
          content: "Não consegui acessar o motor de inferência agora. Verifique se o bot-server está rodando.",
        }],
      }));
      setLoading(false);
    });
  };

  return (
    <div className={`chat-shell ${histCollapsed ? "hist-collapsed" : ""}`}>
      <History active={active} onSelect={setActive} collapsed={histCollapsed} onNew={newConversation}/>

      <main className="chat-main">
        <header className="chat-topbar">
          <button className="topbar-toggle" onClick={() => setHistCollapsed(c => !c)} title={histCollapsed ? "Expandir" : "Recolher"}>
            {histCollapsed ? "›" : "‹"}
          </button>
          <div className="topbar-title">
            <div className="topbar-darwin-mini">
              <div style={{width:28,height:28,borderRadius:'50%',background:'var(--brand)',color:'#000',display:'flex',alignItems:'center',justifyContent:'center',fontWeight:700,fontSize:12}}>D</div>
            </div>
            <div>
              <div className="topbar-name">Darwin AI <span className="ver">v2</span></div>
              <div className="topbar-role">
                <span className="pip"/> MATRIZ DE INTELIGÊNCIA · Meta · Google · LinkedIn · RD · GA4
              </div>
            </div>
          </div>
          <div className="topbar-actions">
            <button title="Nova conversa" onClick={newConversation}>✦</button>
            <div className="topbar-user">WS</div>
          </div>
        </header>

        <div className="chat-body" ref={bodyRef}>
          {isEmpty ? (
            <EmptyState onPick={send}/>
          ) : (
            <div className="chat-flow">
              {messages.map((m, i) => (
                <div key={i} className={`chat-row ${m.role}`}>
                  {m.role === "user" ? <UserMessage m={m}/> : <BotMessage m={m}/>}
                </div>
              ))}
              {loading && (
                <div className="chat-row bot">
                  <div className="chat-bot">
                    <div className="chat-thinking">
                      <span className="pip"/> DARWIN ROTEANDO PELA MATRIZ…
                    </div>
                    <div className="chat-bot-bubble loading">
                      <span className="typing"><span/><span/><span/></span>
                      <span className="typing-label">Cruzando padrões em suas fontes…</span>
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>

        <div className="chat-composer-wrap">
          <div className="chat-composer">
            {!isEmpty && (
              <div className="composer-quick">
                {QUICK.map(q => (
                  <button key={q} onClick={() => send(q)}>{q}</button>
                ))}
              </div>
            )}
            <div className="composer-field">
              <textarea
                ref={textareaRef}
                value={input}
                onChange={e => setInput(e.target.value)}
                onKeyDown={e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); } }}
                placeholder={isEmpty ? "Pergunta qualquer coisa pro Darwin…" : "Continua a conversa…"}
                rows={1}
              />
              <button className="composer-send" disabled={!input.trim() || loading} onClick={() => send()}>↑</button>
            </div>
            <div className="composer-hint">
              <span className="pip"/> Darwin tem acesso a Meta · Google · LinkedIn · RD · GA4 · Matriz
            </div>
          </div>
        </div>
      </main>

      <DarwinCompanion state={companionState} pose={companionPose}/>
    </div>
  );
}

window.DarwinChat = DarwinChat;

ReactDOM.createRoot(document.getElementById('root')).render(React.createElement(DarwinChat));
