// ============================================================
// Claude · Painel lateral
// ============================================================
function ClaudePanel({ onClose, currentPage, alunos, tarefas }) {
  const [msgs, setMsgs] = useState([
    { role:"assistant", content:"Olá Maria! Sou o cérebro da Iuvenis — conectado a todos os módulos do dashboard. Posso resumir sua semana, sugerir conteúdo, identificar alunos em risco ou rascunhar uma edição da IuNews. Por onde começamos?" },
  ]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const bodyRef = useRef();

  useEffect(()=>{ bodyRef.current?.scrollTo({ top: 1e9, behavior:"smooth" }); }, [msgs, loading]);

  const send = async (text) => {
    const q = (text ?? input).trim();
    if (!q || loading) return;
    setInput("");
    const next = [...msgs, { role:"user", content:q }];
    setMsgs(next);
    setLoading(true);

    // Build context summary
    const ctx = `Você é o assistente interno da Iuvenis, uma mentoria de intercâmbio. Responda em português brasileiro, em tom direto e prático. Use os dados abaixo para responder com números reais quando relevante. Limite-se a 4-6 linhas. Use **negrito** com moderação.

CONTEXTO ATUAL:
- Página: ${currentPage}
- Alunos cadastrados: ${alunos.length} (${alunos.filter(a=>a.status==="Ativo").length} ativos)
- MRR estimado: R$ ${alunos.filter(a=>a.status==="Ativo").reduce((s,a)=>s+a.mensalidade,0).toLocaleString("pt-BR")}
- Receita mês atual: R$ ${DATA.finance.receitaMensal.at(-1).receita.toLocaleString("pt-BR")}
- Assinantes IuNews: ${DATA.iunews.assinantes.toLocaleString("pt-BR")} (open rate ${DATA.iunews.openRate}%)
- Seguidores totais redes: ${DATA.social.kpis.seguidores.value.toLocaleString("pt-BR")} (+${DATA.social.kpis.seguidores.delta}%)
- Tarefas em aberto: ${tarefas.filter(t=>t.col!=="done").length}
- Leads no pipeline: ${DATA.pipeline.estagios.reduce((s,e)=>s+e.count,0)}
- Gasto em Ads (mês): R$ ${DX.ads.kpis.gastoMes.value.toLocaleString("pt-BR")} · ROAS ${DX.ads.kpis.roas.value}x
- Mensagens não lidas: ${DX.inbox.filter(m=>m.naoLida).length}
- Alunos em risco (health < 55): ${alunos.filter(a=>{let s=a.progresso*0.5;s+=a.status==="Ativo"?32:a.status==="Pausado"?0:15;s+=a.plano==="Premium"?18:10;return s<55;}).length}`;

    try {
      const response = await window.claude.complete({
        messages: [
          ...next.map(m => ({ role:m.role, content: m.role==="user" && m===next[next.length-1] ? ctx + "\n\nPERGUNTA: " + m.content : m.content }))
        ]
      });
      setMsgs(prev => [...prev, { role:"assistant", content: response }]);
    } catch (e) {
      setMsgs(prev => [...prev, { role:"assistant", content: "Tive um problema pra responder agora. Tenta de novo em alguns segundos." }]);
    } finally {
      setLoading(false);
    }
  };

  const onKey = e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); } };

  const suggestions = msgs.length <= 1 ? [
    "Resuma minha semana na Iuvenis",
    "Quais alunos precisam de atenção?",
    "Sugira 3 ideias de Reels pra essa semana",
    "Como tá meu pipeline de vendas?",
  ] : [];

  // Format assistant messages: bold
  const renderContent = (c) => {
    const parts = c.split(/(\*\*[^*]+\*\*)/g);
    return parts.map((p,i)=> p.startsWith("**") ? <strong key={i}>{p.slice(2,-2)}</strong> : <span key={i}>{p}</span>);
  };

  return (
    <aside className="claude-panel">
      <div className="cp-head">
        <div className="cp-icon">I</div>
        <div style={{ flex:1, minWidth:0 }}>
          <div className="cp-title">Cérebro Iuvenis</div>
          <div className="cp-sub">Conectado · {currentPage}</div>
        </div>
        <button className="icon-btn" onClick={onClose}><I.x size={16}/></button>
      </div>

      <div className="cp-body" ref={bodyRef}>
        {msgs.map((m,i)=>(
          <div key={i} className={"msg "+m.role}>
            {m.role==="assistant" && <div className="msg-av a">I</div>}
            <div className="bubble">{renderContent(m.content)}</div>
          </div>
        ))}
        {loading && <div className="msg assistant">
          <div className="msg-av a">I</div>
          <div className="bubble">
            <span className="loading-dots">
              <span style={{ display:"inline-block", width:6, height:6, borderRadius:50, background:"var(--text-3)", marginRight:4, animation:"blink 1.4s infinite" }}></span>
              <span style={{ display:"inline-block", width:6, height:6, borderRadius:50, background:"var(--text-3)", marginRight:4, animation:"blink 1.4s 0.2s infinite" }}></span>
              <span style={{ display:"inline-block", width:6, height:6, borderRadius:50, background:"var(--text-3)", animation:"blink 1.4s 0.4s infinite" }}></span>
            </span>
          </div>
        </div>}

        {suggestions.length > 0 && !loading && (
          <div className="cp-suggest mt-2">
            <div className="cp-suggest-h">Sugestões pra começar</div>
            {suggestions.map((s,i)=>(
              <button key={i} className="cp-chip" onClick={()=>send(s)}>{s}</button>
            ))}
          </div>
        )}
      </div>

      <div className="cp-foot">
        <div className="cp-input-wrap">
          <textarea className="cp-input" rows="1" placeholder="Pergunte algo ao cérebro Iuvenis…" value={input} onChange={e=>setInput(e.target.value)} onKeyDown={onKey}/>
          <button className="cp-send" onClick={()=>send()} disabled={!input.trim() || loading}><I.send size={14}/></button>
        </div>
        <div className="text-3" style={{ fontSize:10.5, marginTop:6, textAlign:"center" }}>Claude tem acesso aos dados do dashboard · use ⌘K pra navegar</div>
      </div>

      <style>{`
        @keyframes blink {
          0%, 80%, 100% { opacity: 0.3; transform: translateY(0); }
          40% { opacity: 1; transform: translateY(-2px); }
        }
      `}</style>
    </aside>
  );
}

window.ClaudePanel = ClaudePanel;
