/* SEL.IA Landing — Isometric laptop with 3 rotating screens & dynamic bubbles */

const SCREENS = [
  { id: "chat",      label: "Chat Regulatório",   annotations: [
    { icon:"zap",      label:"Deep Search em segundos",        tag:"IA",        corner:"tl", at:1500,  until:6300 },
    { icon:"sparkles", label:"Respostas com fontes auditáveis",tag:"IA",        corner:"tr", at:6600,  until:11300 },
    { icon:"book",     label:"Citações com link à origem",     tag:"Auditável", corner:"bl", at:11600, until:15300 },
    { icon:"chart",    label:"Cruza 7 fontes oficiais",        tag:"IA",        corner:"br", at:15600, until:19000 },
  ]},
  { id: "sei",       label: "Processo SEI",       annotations: [
    { icon:"chart",     label:"Linha do tempo cronológica",     tag:"Histórico", corner:"bl", at:800,   until:7000 },
    { icon:"sparkles",  label:"Resumo de cada documento por IA", tag:"IA",        corner:"br", at:7300,  until:13500 },
    { icon:"sparkles",  label:"IA analisa centenas de docs e gera o resumo do processo", tag:"IA", corner:"tl", at:13800, until:21500 },
  ]},
  { id: "diretores", label: "Painel da Diretoria", annotations: [
    { icon:"users",   label:"Perfil de cada Diretor",        tag:"Painel",  corner:"tl", at:700,   until:5800 },
    { icon:"grid",    label:"Distribuição por tema",         tag:"Análise", corner:"bl", at:6100,  until:10600 },
    { icon:"message", label:"Pergunte em linguagem natural", tag:"IA",      corner:"tr", at:11000, until:15800 },
    { icon:"sparkles",label:"Resumo de falas com citações",  tag:"IA",      corner:"br", at:16100, until:21300 },
  ]},
  { id: "participacao", label: "Participação Social", annotations: [
    { icon:"users",    label:"Audiências, consultas e subsídios", tag:"Part. social", corner:"tl", at:700,   until:5800 },
    { icon:"sparkles", label:"Chatbot especialista no processo",  tag:"IA",          corner:"bl", at:6100,  until:11000 },
    { icon:"message",  label:"Pergunte qualquer coisa do processo", tag:"IA",        corner:"tr", at:11300, until:16400 },
    { icon:"book",     label:"Respostas fundamentadas nos documentos", tag:"Auditável", corner:"br", at:16700, until:22000 },
    { icon:"filetext", label:"Gera relatórios exportáveis",      tag:"Exportável",  corner:"tl", at:22300, until:32500 },
  ]},
];

/* Per-screen annotation-clock loop length (ms). Only the chat self-restarts,
   so only it loops — keeping callouts in sync with the replayed animation. */
const ANNOT_LOOP = [19200, null, null, null];

const SCREEN_DURATION = 11000; // ms per screen (fallback)
/* Per-screen dwell time — chat is longer to fit the sources-modal sequence */
const SCREEN_DURATIONS = [19200, 22000, 21500, 33000];

/* Sources recreated from the product — this module draws only from
   REN 1.000, PRODIST and PRORET (no SEI / nota técnica here). */
const REFERENCES = [
  { doc: "Resolução Normativa nº 1.000/2021", sec: "Seção I",
    quote: "Art. 433. A qualidade do serviço prestado pela distribuidora é avaliada, quanto à sua continuidade, por indicadores coletivos e individuais…",
    full: {
      art: "Art. 433.",
      caput: "A qualidade do serviço prestado pela distribuidora é avaliada, quanto à sua continuidade, por indicadores coletivos e individuais relacionados à duração e frequência das interrupções do serviço, conforme Módulo 8 do PRODIST.",
      paras: [
        { n: "§ 1º", t: "O consumidor e demais usuários têm o direito de receber compensação financeira em sua fatura de energia no caso da distribuidora violar os limites de continuidade individuais relativos às suas instalações." },
        { n: "§ 2º", t: "A distribuidora pode deduzir da compensação a que se refere o § 1º os débitos vencidos do consumidor e demais usuários que não sejam objeto de contestação administrativa ou judicial." },
      ],
    } },
  { doc: "Resolução Normativa nº 1.000/2021", sec: "Seção V",
    quote: "Art. 447. A qualidade do serviço prestado pela distribuidora é avaliada, quanto ao tratamento das reclamações e das…" },
  { doc: "Resolução Normativa nº 1.000/2021", sec: "Seção III",
    quote: "Art. 439. As metas dos indicadores coletivos de continuidade DEC e FEC são fixadas pela ANEEL para cada conjunto…" },
  { doc: "Resolução Normativa nº 1.000/2021", sec: "Anexo IV — Prazos",
    quote: "Os prazos regulatórios de atendimento e de compensação ao consumidor observam o disposto neste anexo, conforme…" },
  { doc: "PRODIST — Módulo 8 · Qualidade do Fornecimento", sec: "Introdução",
    quote: "Com caráter introdutório, este Módulo 8 está estruturado de forma a abranger a qualidade do produto e do serviço…" },
  { doc: "PRODIST — Módulo 8 · Qualidade do Fornecimento", sec: "Seção 8.1 Qualidade do Produto",
    quote: "108. A distribuidora deve enviar à ANEEL os valores dos indicadores DRP e DRC obtidos das medições amostrais, d…" },
  { doc: "PRODIST — Módulo 8 · Qualidade do Fornecimento", sec: "Seção 8.2 Qualidade do Serviço",
    quote: "173. Os indicadores de continuidade individuais, a seguir discriminados, devem ser apurados para todas as unidade…" },
  { doc: "PRODIST — Módulo 8 · Qualidade do Fornecimento", sec: "Seção 8.2 — Indicadores",
    quote: "DIC, FIC e DMIC expressam a duração e a frequência de interrupção por unidade consumidora no período de apuração…" },
  { doc: "PRORET — Submódulo 2.2 · Estrutura Tarifária", sec: "Procedimentos gerais",
    quote: "Define a metodologia de cálculo dos componentes tarifários, observados os indicadores de continuidade e qualidade…" },
  { doc: "PRORET — Submódulo 7.1 · Revisão Tarifária", sec: "Custos operacionais",
    quote: "Estabelece o tratamento regulatório dos custos associados às metas de continuidade na revisão tarifária periódica…" },
];

const LaptopMockup = ({ initialScreen = 0, autoplay = true }) => {
  const [screenIdx, setScreenIdx] = React.useState(initialScreen);
  const [paused, setPaused] = React.useState(false);

  // Auto-rotation
  React.useEffect(() => {
    if (paused || !autoplay) return;
    const t = setTimeout(() => {
      setScreenIdx((i) => (i + 1) % SCREENS.length);
    }, SCREEN_DURATIONS[screenIdx] || SCREEN_DURATION);
    return () => clearTimeout(t);
  }, [screenIdx, paused, autoplay]);

  const goTo = (i) => {
    setScreenIdx(i);
  };

  // Screen clock — ms elapsed since the current screen mounted; drives the
  // timed annotation callouts. Free-running (NOT paused by hover) so it stays
  // in sync with each screen's own animation, which also doesn't pause. For the
  // chat it loops at CHAT_CYCLE_MS to re-sync with the chat's self-restart.
  const [clock, setClock] = React.useState(0);
  React.useEffect(() => {
    let t0 = Date.now();
    const loop = ANNOT_LOOP[screenIdx];
    setClock(0);
    const id = setInterval(() => {
      let e = Date.now() - t0;
      if (loop && e >= loop) { t0 = Date.now(); e = 0; }
      setClock(e);
    }, 150);
    return () => clearInterval(id);
  }, [screenIdx]);

  // Parallax — track relative position of the stage in viewport
  const stageRef = React.useRef(null);
  const wrapRef  = React.useRef(null);
  React.useEffect(() => {
    let raf;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        raf = null;
        const stage = stageRef.current;
        const wrap  = wrapRef.current;
        if (!stage || !wrap) return;
        const rect = stage.getBoundingClientRect();
        const vh = window.innerHeight;
        const center = rect.top + rect.height / 2;
        const t = Math.max(-1.2, Math.min(1.2, (center - vh / 2) / (vh / 2 + rect.height / 2)));
        const shift = -t * 24;
        void shift; /* parallax transform disabled: a transform on the zoomed wrap rasterizes & blurs the screen */
      });
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
      if (raf) cancelAnimationFrame(raf);
    };
  }, []);

  const current = SCREENS[screenIdx];

  return (
    <div className="laptop-stage" ref={stageRef}>
      {/* Timed AI annotation callouts — each appears near the relevant region
         at the moment that part of the animation happens. */}
      {current.annotations.map((a, i) => {
        const on = clock >= a.at && clock < a.until;
        return (
          <FeatureBubble key={`${current.id}-${i}`} {...a} on={on}/>
        );
      })}

      <div className="laptop-wrap" ref={wrapRef}>
        <div className="laptop">
          <div className="laptop-screen">
            <div className="laptop-camera"></div>
            <div className="laptop-screen-inner">
              <ScreenSwitcher screen={current.id}/>
            </div>
          </div>
        </div>
        <div className="laptop-base"></div>
      </div>
      <div className="laptop-shadow"></div>

      {/* Dots / tabs */}
      <div className="laptop-dots" role="tablist" aria-label="Telas do produto">
        {SCREENS.map((s, i) => (
          <button
            key={s.id}
            role="tab"
            aria-selected={i === screenIdx}
            className={"laptop-dot " + (i === screenIdx ? "is-active" : "")}
            onClick={() => goTo(i)}
          >
            <span className="laptop-dot-pill">
              <span className="laptop-dot-bullet"/>
              {s.label}
            </span>
          </button>
        ))}
      </div>
    </div>
  );
};

const FeatureBubble = ({ corner, icon, label, tag, on }) => (
  <div className={`feat-bubble corner-${corner} ${on ? "is-on" : "is-off"}`}>
    <span className="feat-icon"><LandIcon name={icon} size={12}/></span>
    <span>{label}</span>
    <span className="ai-tag">{tag}</span>
  </div>
);

/* ---------- Screen switcher ---------- */
const ScreenSwitcher = ({ screen }) => {
  // Keyed only on screen id — re-mounts only when screen actually changes,
  // so child state updates (typing) don't restart the fade animation.
  return (
    <div key={screen} className="screen-fade" style={{height:"100%"}}>
      <ScreenChrome screen={screen}/>
    </div>
  );
};

/* Sidebar shared by all screens */
const Sidebar = ({ active = "message" }) => {
  const items = [
    {n:"message"}, {n:"newspaper"}, {n:"filesearch"},
    {n:"database"}, {n:"users"}, {n:"clipboard"}, {n:"search"}
  ];
  return (
    <div style={{
      width: 56, background:"#102b4e",
      display:"flex",flexDirection:"column",alignItems:"center",
      padding:"12px 0", gap: 14, flexShrink: 0
    }}>
      <div style={{
        width:32,height:32,borderRadius:8,
        background:"linear-gradient(135deg,#d91965,#ef405b)",
        display:"flex",alignItems:"center",justifyContent:"center",
        color:"#fff",fontWeight:800,fontSize:11,letterSpacing:"-0.02em"
      }}>S</div>
      <div style={{height:1,background:"rgba(255,255,255,0.10)",width:32}}/>
      {items.map((it, i) => (
        <div key={i} style={{
          width:32,height:32,borderRadius:8,
          display:"flex",alignItems:"center",justifyContent:"center",
          background: it.n === active ? "linear-gradient(135deg,#d91965,#ef405b)" : "transparent",
          color: it.n === active ? "#fff" : "rgba(255,255,255,0.55)"
        }}>
          <LandIcon name={it.n} size={14}/>
        </div>
      ))}
      <div style={{flex:1}}/>
      <div style={{
        width:28,height:28,borderRadius:9999,background:"#d91965",
        color:"#fff",fontSize:9,fontWeight:700,
        display:"flex",alignItems:"center",justifyContent:"center"
      }}>GS</div>
    </div>
  );
};

const ScreenChrome = ({ screen }) => {
  if (screen === "chat") return <ChatScreen/>;
  if (screen === "sei")  return <SeiScreen/>;
  if (screen === "participacao") return <ParticipacaoScreen/>;
  return <DiretoresScreen/>;
};

/* ===================== SCREEN 1 — Chat ===================== */
const ChatScreen = () => {
  const userText = "Quais são os impactos da REN 1.000 na qualidade do serviço?";
  const aiText = "A Resolução Normativa nº 1.000/2021 estabelece parâmetros mais rigorosos para indicadores DEC e FEC, com metas anuais de redução. Identifiquei 12 trechos relevantes em 4 fontes.";
  const [step, setStep] = React.useState(0);
  const [typed, setTyped] = React.useState("");
  const [aiTyped, setAiTyped] = React.useState("");
  const [actions, setActions] = React.useState(false);
  const [bookZoom, setBookZoom] = React.useState(false);
  const [modal, setModal] = React.useState(false);
  const [modalIn, setModalIn] = React.useState(false);
  const [hi, setHi] = React.useState(-1);
  const [expanded, setExpanded] = React.useState(-1);
  const [dive, setDive] = React.useState(false);
  const [cycle, setCycle] = React.useState(0);

  const listRef = React.useRef(null);
  const cardRefs = React.useRef([]);
  const msgsRef = React.useRef(null);
  const modalRef = React.useRef(null);
  const srcTimers = React.useRef([]);
  const restartTimer = React.useRef(null);

  // Auto-restart the whole chat from zero after a delay, so the animation never
  // gets stuck on the sources modal (e.g. if the user opens it and walks away).
  const scheduleRestart = React.useCallback((delay) => {
    if (restartTimer.current) clearTimeout(restartTimer.current);
    restartTimer.current = setTimeout(() => setCycle((c) => c + 1), delay);
  }, []);

  // The sources-modal choreography (walk → settle → expand → focus).
  // Reusable so the timeline AND the "Ver fontes" button can run it.
  const runSourcesSequence = React.useCallback(() => {
    srcTimers.current.forEach(clearTimeout);
    srcTimers.current = [];
    const T = srcTimers.current;
    const modal = modalRef.current;
    if (modal) { modal.style.transition = "none"; modal.style.transform = ""; }
    setExpanded(-1); setDive(false); setHi(-1);
    setModal(true);
    T.push(setTimeout(() => setModalIn(true), 40));
    const hiStart = 480;
    const stepMs = 320;
    for (let i = 0; i < REFERENCES.length; i++) {
      T.push(setTimeout(() => setHi(i), hiStart + i * stepMs));
    }
    const walkEnd = hiStart + REFERENCES.length * stepMs;
    T.push(setTimeout(() => setHi(0), walkEnd + 120));
    T.push(setTimeout(() => setExpanded(0), walkEnd + 620));
  }, []);

  React.useEffect(() => {
    let timers = [];
    setStep(0); setTyped(""); setAiTyped("");
    setActions(false); setBookZoom(false); setModal(false); setModalIn(false); setHi(-1); setExpanded(-1); setDive(false);
    timers.push(setTimeout(() => setStep(1), 600));
    for (let i = 1; i <= userText.length; i++) {
      timers.push(setTimeout(() => setTyped(userText.slice(0, i)), 600 + i * 22));
    }
    const tEnd = 600 + userText.length * 22;
    timers.push(setTimeout(() => setStep(2), tEnd + 200));
    timers.push(setTimeout(() => setStep(3), tEnd + 1400));
    for (let i = 1; i <= aiText.length; i++) {
      timers.push(setTimeout(() => setAiTyped(aiText.slice(0, i)), tEnd + 1400 + i * 10));
    }
    const aEnd = tEnd + 1400 + aiText.length * 10;
    timers.push(setTimeout(() => setStep(4), aEnd + 100));            // citations
    timers.push(setTimeout(() => setActions(true), aEnd + 700));      // action row fades in
    timers.push(setTimeout(() => setBookZoom(true), aEnd + 1500));    // zoom into the book icon
    const modalAt = aEnd + 2700;
    timers.push(setTimeout(() => { setBookZoom(false); runSourcesSequence(); }, modalAt));
    // Dive ends ~5430ms after the modal opens; hold, then restart from zero.
    // The delay is intentionally longer than SCREEN_DURATIONS[0] so on the
    // landing the parent screen-rotation takes over first; this only fires when
    // the screen stays put (autoplay off / hover-paused / modal reopened).
    scheduleRestart(modalAt + 5430 + 6000);
    return () => {
      timers.forEach(clearTimeout);
      srcTimers.current.forEach(clearTimeout);
      if (restartTimer.current) clearTimeout(restartTimer.current);
    };
  }, [cycle]);

  // Scroll the modal list so the highlighted source stays in view (no scrollIntoView)
  React.useEffect(() => {
    if (hi < 0) return;
    const card = cardRefs.current[hi];
    const list = listRef.current;
    if (card && list) {
      const cRect = card.getBoundingClientRect();
      const lRect = list.getBoundingClientRect();
      const delta = (cRect.top - lRect.top) - 14;
      list.scrollTop = Math.max(0, list.scrollTop + delta);
    }
  }, [hi]);

  // When a source expands, bring its top to the list top so the article reads cleanly
  React.useEffect(() => {
    if (expanded < 0) return;
    const card = cardRefs.current[expanded];
    const list = listRef.current;
    if (!card || !list) return;
    const t = setTimeout(() => {
      const cRect = card.getBoundingClientRect();
      const lRect = list.getBoundingClientRect();
      list.scrollTop = Math.max(0, list.scrollTop + (cRect.top - lRect.top) - 10);
    }, 430);
    return () => clearTimeout(t);
  }, [expanded]);

  // Final focus — the chosen excerpt takes over the modal (siblings collapse)
  // and its text grows to a comfortable reading size, keeping the modal chrome.
  React.useEffect(() => {
    if (!dive) return;
    const card = cardRefs.current[0];
    const list = listRef.current;
    if (!card || !list) return;
    const t = setTimeout(() => {
      const cRect = card.getBoundingClientRect();
      const lRect = list.getBoundingClientRect();
      list.scrollTop = Math.max(0, list.scrollTop + (cRect.top - lRect.top) - 6);
    }, 520);
    return () => clearTimeout(t);
  }, [dive]);

  // Keep the chat pinned to the bottom as the answer + action row appear
  React.useEffect(() => {
    const m = msgsRef.current;
    if (m) m.scrollTop = m.scrollHeight;
  }, [step, aiTyped, actions, bookZoom]);

  const closeModal = () => {
    srcTimers.current.forEach(clearTimeout);
    srcTimers.current = [];
    setModalIn(false);
    setTimeout(() => {
      setModal(false);
      setDive(false); setExpanded(-1); setHi(-1);
      const modal = modalRef.current;
      if (modal) { modal.style.transition = "none"; modal.style.transform = ""; }
    }, 300);
  };

  const openSources = () => {
    srcTimers.current.forEach(clearTimeout);
    srcTimers.current = [];
    runSourcesSequence();
    // Keep the self-healing guarantee after a manual reopen.
    scheduleRestart(5430 + 7000);
  };

  return (
    <div style={{display:"flex",height:"100%",background:"#fff",fontSize:13,position:"relative"}}>
      <Sidebar active="message"/>
      <div style={{flex:1,display:"flex",flexDirection:"column",minWidth:0}}>
        <div style={{
          display:"flex",alignItems:"center",
          padding:"10px 18px",
          borderBottom:"1px solid #eef0f2",
          gap:12
        }}>
          <div style={{fontSize:14,fontWeight:700,color:"#102b4e",letterSpacing:"-0.01em"}}>Chat Regulatório</div>
          <div style={{
            display:"inline-flex",alignItems:"center",gap:4,
            padding:"2px 8px",
            background:"linear-gradient(135deg,rgba(217,25,101,0.10),rgba(239,64,91,0.10))",
            border:"1px solid rgba(217,25,101,0.20)",
            borderRadius:9999,
            fontSize:9,fontWeight:600,color:"#d91965",
            letterSpacing:"0.04em",textTransform:"uppercase"
          }}>
            <LandIcon name="sparkles" size={9}/>Deep Search
          </div>
          <div style={{flex:1}}/>
          <div style={{fontSize:11.5,color:"#9aa0a6"}}>7 fontes ativas</div>
        </div>

        <div ref={msgsRef} style={{flex:1,padding:"18px 24px",overflow:"hidden",display:"flex",flexDirection:"column",gap:14}}>
          <Bubble role="ai" name="SEL.IA">
            Olá Gustavo. Posso ajudar com normas, processos SEI, votos da Diretoria ou consultas à BDGD.
          </Bubble>

          {step >= 1 && (
            <Bubble role="user" name="GS">
              {typed}<span className="caret" style={{display: typed.length === userText.length ? "none" : "inline-block", width:1.5, height: 10, background:"#fff", marginLeft:1, verticalAlign:"middle"}}/>
            </Bubble>
          )}

          {step === 2 && (<Bubble role="ai" name="SEL.IA" thinking/>)}

          {step >= 3 && (
            <Bubble role="ai" name="SEL.IA" deep>
              {aiTyped}
              {step >= 4 && (
                <div style={{display:"flex",gap:6,marginTop:8,flexWrap:"wrap"}}>
                  <CitationChip label="REN 1.000/2021" type="aneel"/>
                  <CitationChip label="PRODIST Mód. 8" type="dou"/>
                  <CitationChip label="Processo SEI 48500.00" type="sei"/>
                </div>
              )}
              {step >= 4 && (
                <div className={"msg-actions" + (actions ? " show" : "") + (bookZoom ? " spotlight" : "")}>
                  <button className="msg-action-btn"><LandIcon name="copy" size={13}/></button>
                  <button className="msg-action-btn"><LandIcon name="thumbup" size={13}/></button>
                  <button className="msg-action-btn"><LandIcon name="thumbdown" size={13}/></button>
                  <button className={"msg-action-btn src-btn" + (bookZoom ? " zoom" : "")} onClick={openSources}>
                    <LandIcon name="book" size={13}/>
                  </button>
                  <span className="msg-action-label" onClick={openSources} style={{cursor:"pointer"}}>Ver fontes</span>
                  <span className="msg-action-sep"/>
                  <button className="msg-action-btn"><LandIcon name="dots" size={13}/></button>
                </div>
              )}
            </Bubble>
          )}
        </div>

        <div style={{padding:"10px 24px 14px",borderTop:"1px solid #eef0f2",background:"#fafbfc"}}>
          <div style={{
            display:"flex",alignItems:"center",
            background:"#fff",border:"1px solid #e6e7e8",borderRadius:8,
            padding:"6px 8px 6px 12px",
            fontSize:11.5,color:"#9aa0a6"
          }}>
            <span style={{flex:1}}>Pergunte sobre normas, processos, votos…</span>
            <div style={{
              width:22,height:22,borderRadius:6,
              background:"linear-gradient(135deg,#d91965,#ef405b)",
              color:"#fff",
              display:"flex",alignItems:"center",justifyContent:"center"
            }}>
              <LandIcon name="send" size={10}/>
            </div>
          </div>
        </div>
      </div>

      {/* Fontes e Referências — modal overlay confined to the laptop screen */}
      {modal && (
        <div className={"src-modal-overlay" + (modalIn ? " in" : "")} onClick={closeModal}>
          <div className="src-modal" ref={modalRef} onClick={(e) => e.stopPropagation()}>
            <div className="src-modal-header">
              <div className="smh-title"><LandIcon name="filetext" size={15}/>Fontes e Referências</div>
              <div className="smh-sub">Documentos e normas utilizados para fundamentar esta resposta</div>
              <div className="smh-close" onClick={closeModal}><LandIcon name="x" size={13}/></div>
            </div>
            <div className="src-modal-meta">
              <span className="smm-count"><LandIcon name="layers" size={12}/>{REFERENCES.length} referências encontradas</span>
              <span className="smm-expand">Expandir todos</span>
            </div>
            <div className={"src-modal-body" + (dive ? " dive" : "")} ref={listRef}>
              {REFERENCES.map((r, i) => (
                <div
                  key={i}
                  ref={(el) => { cardRefs.current[i] = el; }}
                  className={"src-ref-card" + (hi === i ? " hi" : "") + (expanded === i ? " expanded" : "")}
                >
                  <div className="src-ref-ico"><LandIcon name="book" size={13}/></div>
                  <div className="src-ref-main">
                    <div className="src-ref-head">
                      <div style={{minWidth:0}}>
                        <div className="src-ref-title">{r.doc}</div>
                        <div className="src-ref-sec">{r.sec}</div>
                      </div>
                      <span className="src-ref-chev">
                        <LandIcon name="chevright" size={12} style={{transform: expanded === i ? "rotate(270deg)" : "rotate(90deg)", transition:"transform 300ms ease"}}/>
                      </span>
                    </div>
                    {expanded === i && r.full ? (
                      <div className="src-ref-full src-zoom-in">
                        <div className="srf-art">{r.full.art}</div>
                        <p className="srf-caput">{r.full.caput}</p>
                        {r.full.paras.map((p, k) => (
                          <p key={k} className="srf-par"><b>{p.n}</b>&nbsp;&nbsp;{p.t}</p>
                        ))}
                      </div>
                    ) : (
                      <div className="src-ref-quote">{r.quote}</div>
                    )}
                    <div className="src-ref-more">
                      {expanded === i ? "Ver menos ↑" : "Ver conteúdo completo →"}
                    </div>
                  </div>
                </div>
              ))}
            </div>
            <div className="src-modal-footer"><span className="smf-btn" onClick={closeModal}>Fechar</span></div>
          </div>
        </div>
      )}
    </div>
  );
};

const Bubble = ({ role, name, children, thinking, deep }) => {
  if (role === "user") {
    return (
      <div style={{display:"flex",justifyContent:"flex-end",gap:8}}>
        <div style={{
          maxWidth:"68%",
          background:"#102b4e",color:"#fff",
          padding:"8px 12px",borderRadius:"12px 12px 2px 12px",
          fontSize:13,lineHeight:1.5
        }}>{children}</div>
        <div style={{
          width:22,height:22,borderRadius:9999,
          background:"#d91965",color:"#fff",
          fontSize:8,fontWeight:700,
          display:"flex",alignItems:"center",justifyContent:"center",
          flexShrink:0
        }}>{name}</div>
      </div>
    );
  }
  return (
    <div style={{display:"flex",gap:8}}>
      <div style={{
        width:22,height:22,borderRadius:9999,
        background:"linear-gradient(135deg,#d91965,#ef405b)",
        color:"#fff",fontSize:7,fontWeight:700,
        display:"flex",alignItems:"center",justifyContent:"center",
        flexShrink:0
      }}>AI</div>
      <div style={{maxWidth:"82%",minWidth:0}}>
        <div style={{display:"flex",alignItems:"center",gap:6,marginBottom:3}}>
          <span style={{fontSize:11.5,fontWeight:700,color:"#102b4e"}}>{name}</span>
          {deep && (
            <span style={{
              padding:"1px 5px",borderRadius:9999,
              background:"linear-gradient(135deg,rgba(217,25,101,0.10),rgba(239,64,91,0.10))",
              color:"#d91965",fontSize:7,fontWeight:700,letterSpacing:"0.04em",textTransform:"uppercase"
            }}>Deep</span>
          )}
        </div>
        <div style={{
          background:"#f6f8fa",
          padding:"8px 12px",
          borderRadius:"2px 12px 12px 12px",
          fontSize:13,lineHeight:1.5,color:"#0a0a0a"
        }}>
          {thinking ? (<span className="typing"><span/><span/><span/></span>) : children}
        </div>
      </div>
    </div>
  );
};

const CitationChip = ({ label, type }) => {
  const colors = {
    aneel: { bg:"rgba(16,43,78,0.08)", c:"#102b4e" },
    dou:   { bg:"rgba(217,25,101,0.10)", c:"#d91965" },
    sei:   { bg:"rgba(0,66,122,0.10)", c:"#00427a" }
  };
  const t = colors[type] || colors.aneel;
  return (
    <span style={{
      display:"inline-flex",alignItems:"center",gap:3,
      padding:"2px 7px",borderRadius:9999,
      background:t.bg,color:t.c,
      fontSize:9,fontWeight:600
    }}>
      <LandIcon name="book" size={8}/>{label}
    </span>
  );
};

/* ===================== SCREEN 2 — SEI Process ===================== */
const TIMELINE_DOCS = [
  { d:"03/03", type:"Memória",   color:"#9b6cd9" },
  { d:"03/03", type:"Voto",      color:"#d91965" },
  { d:"03/03", type:"Memorando", color:"#00427a" },
  { d:"04/03", type:"Memória",   color:"#9b6cd9", featured:true },
  { d:"05/03", type:"Fiscaliz.", color:"#00427a" },
  { d:"11/03", type:"Decisório", color:"#d91965" },
  { d:"12/03", type:"Fiscaliz.", color:"#00427a" },
];

const SEI_SUMMARY = "Documento trata da manifestação da Enel SP sobre o evento climático extremo de dez/2025, classificado como ciclone extratropical inédito na Região Metropolitana. Impacto: ~4,2 milhões de clientes afetados (+37% vs 2024). Resposta operacional: mobilização ~32% acima do Plano de Contingência, 1.566 veículos no Dia D (+57% vs 2024). DEC reduzido de 3,25 para 2,16h.";

/* Synthesized, deliberately brief — conveys "consolidated report" without a wall of text */
const SEI_ORBIT = ["#9b6cd9","#d91965","#00427a","#9b6cd9","#1f9a66","#00427a","#d91965","#9b6cd9"];
const SEI_OVERVIEW_TL = [
  { d:"01/06", c:"#d91965", t:"Despacho da SFT — instauração de PAS" },
  { d:"29/04", c:"#16a34a", t:"Publicação no DOU (Despacho nº 1.468)" },
  { d:"07/04", c:"#7c3aed", t:"Voto do relator encaminhado à Diretoria" },
  { d:"05/03", c:"#00427a", t:"Relatório de fiscalização concluído" },
];
const SEI_OVERVIEW_POINTS = [
  { k: "Objeto", t: "falhas estruturais na distribuição diante do evento climático extremo de dez/2025." },
  { k: "Instrução SFT", t: "Plano de Recuperação considerado insuficiente → hipótese de caducidade da concessão." },
  { k: "Impacto", t: "~4,2 mi de clientes afetados (+37% vs 2024); DEC reduzido de 3,25 para 2,16h." },
  { k: "Resposta", t: "mobilização ~32% acima do Plano de Contingência; 1.566 veículos no Dia D (+57%)." },
  { k: "Status", t: "em andamento · pendente de deliberação da Diretoria Colegiada." },
];

/* Compile stage — document chips converge into a central synthesis core */
const COMPILE_CHIPS = [
  { label: "Memória",   tx: -120, ty: -42 },
  { label: "Voto",      tx:  118, ty: -50 },
  { label: "Memorando", tx:  -76, ty:  44 },
  { label: "Fiscaliz.", tx:   96, ty:  40 },
  { label: "Decisório", tx:  -10, ty: -66 },
  { label: "Parecer",   tx:  150, ty:  -6 },
  { label: "Despacho",  tx: -150, ty:   4 },
  { label: "Nota Téc.", tx:   18, ty:  62 },
];

const CompileStage = () => {
  const [state, setState] = React.useState("idle"); // idle → in → merge
  React.useEffect(() => {
    const t1 = setTimeout(() => setState("in"), 60);
    const t2 = setTimeout(() => setState("merge"), 1080);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, []);
  return (
    <div className="sei-compile">
      <div className="sei-core"><LandIcon name="sparkles" size={20}/></div>
      {COMPILE_CHIPS.map((c, i) => (
        <div
          key={i}
          className={"sei-chip" + (state === "in" ? " in" : "") + (state === "merge" ? " merge" : "")}
          style={{ "--tx": c.tx + "px", "--ty": c.ty + "px", transitionDelay: (state === "merge" ? i * 36 : i * 48) + "ms" }}
        >
          <LandIcon name="newspaper" size={9} style={{color:"#9b6cd9"}}/>{c.label}
        </div>
      ))}
      <div className="sei-compile-caption">
        Sintetizando 310 documentos
        <span className="dots"><i/><i/><i/></span>
      </div>
    </div>
  );
};

const SEI_SYNTH_DOCS = [
  { c:"#9b6cd9", l:"Memória" }, { c:"#d91965", l:"Voto" }, { c:"#00427a", l:"Memorando" },
  { c:"#9b6cd9", l:"Memória" }, { c:"#1f9a66", l:"Fiscaliz." }, { c:"#d91965", l:"Decisório" },
  { c:"#00427a", l:"Fiscaliz." }, { c:"#9b6cd9", l:"Parecer" },
];
const SeiSynth = () => {
  const [stage, setStage] = React.useState("row"); // row → orbit
  React.useEffect(() => {
    const t = setTimeout(() => setStage("orbit"), 650);
    return () => clearTimeout(t);
  }, []);
  const N = SEI_SYNTH_DOCS.length;
  return (
    <div className={"sei-synth" + (stage === "orbit" ? " spinning" : "")}>
      <div className={"sei-core sei-core2" + (stage === "orbit" ? " on" : "")}><LandIcon name="sparkles" size={24}/></div>
      <div className="sei-flyring">
      {SEI_SYNTH_DOCS.map((d, i) => (
        <span
          key={i}
          className={"sei-fly" + (stage === "orbit" ? " orbit" : "")}
          style={{
            color: d.c,
            "--rowx": ((i + 0.5) / N * 100) + "%",
            "--a": (i / N) + "turn",
            transitionDelay: (stage === "orbit" ? i * 55 : 0) + "ms",
          }}
        >
          <LandIcon name="newspaper" size={12}/>
        </span>
      ))}
      </div>
      <div className="sei-compile-caption" style={{opacity: stage === "orbit" ? 1 : 0}}>
        Sintetizando 310 documentos
        <span className="dots"><i/><i/><i/></span>
      </div>
    </div>
  );
};

const SeiScreen = () => {
  const [activeIdx, setActiveIdx] = React.useState(0);
  const [summaryTyped, setSummaryTyped] = React.useState("");
  const [phase, setPhase] = React.useState("walk"); // walk → focus → summary → converge → compiling → consolidated

  // Walk through timeline → focus featured → type doc summary → dots fly to the
  // IA wheel → timeline disappears → consolidated overview (full space). Slower.
  React.useEffect(() => {
    let timers = [];
    setActiveIdx(0); setSummaryTyped(""); setPhase("walk");
    const featuredIdx = TIMELINE_DOCS.findIndex(d => d.featured);
    for (let i = 1; i <= featuredIdx; i++) {
      timers.push(setTimeout(() => setActiveIdx(i), i * 850));
    }
    const walkEnd = featuredIdx * 850 + 500;
    timers.push(setTimeout(() => setPhase("focus"), walkEnd));
    timers.push(setTimeout(() => setPhase("summary"), walkEnd + 600));
    for (let i = 1; i <= SEI_SUMMARY.length; i++) {
      timers.push(setTimeout(() => setSummaryTyped(SEI_SUMMARY.slice(0, i)), walkEnd + 600 + i * 9));
    }
    const sumEnd = walkEnd + 600 + SEI_SUMMARY.length * 9;
    // After the summary: complete the purple timeline (all processed), hold,
    // THEN lift the docs off into the IA wheel — one continuous motion, same screen.
    timers.push(setTimeout(() => { setActiveIdx(TIMELINE_DOCS.length - 1); setPhase("processed"); }, sumEnd + 1500));
    timers.push(setTimeout(() => setPhase("synth"), sumEnd + 1500 + 1300));
    timers.push(setTimeout(() => setPhase("consolidated"), sumEnd + 1500 + 1300 + 3600));
    return () => timers.forEach(clearTimeout);
  }, []);

  const synth = phase === "synth" || phase === "consolidated";
  const timelineGone = phase === "synth" || phase === "consolidated";
  const lineFull = phase === "processed" || synth;
  const allPast = phase === "processed" || synth;
  const centerIdx = (TIMELINE_DOCS.length - 1) / 2;

  return (
    <div className="sei-fit" style={{display:"flex",height:"100%",background:"#fff",fontSize:10}}>
      <Sidebar active="filesearch"/>
      <div style={{flex:1,display:"flex",flexDirection:"column",minWidth:0,background:"#f6f7f9"}}>
        {/* Top header */}
        <div style={{padding:"10px 18px",background:"#fff",borderBottom:"1px solid #eef0f2",display:"flex",alignItems:"center",gap:8}}>
          <span style={{fontSize:9,color:"#9aa0a6"}}>← Voltar para busca</span>
          <div style={{flex:1}}/>
        </div>

        {/* Process card */}
        <div className="sei-collapsible" style={{padding:"10px 14px 0", overflow:"hidden",
          maxHeight: synth ? 0 : 120, opacity: synth ? 0 : 1, marginTop: synth ? -6 : 0,
          transition:"max-height 600ms cubic-bezier(0.65,0,0.35,1), opacity 420ms ease, margin 500ms ease"}}>
          <div style={{
            background:"#fff",border:"1px solid #eef0f2",borderRadius:8,padding:"10px 14px",
            display:"flex",alignItems:"flex-start",gap:10
          }}>
            <div style={{flex:1,minWidth:0}}>
              <div style={{display:"flex",alignItems:"center",gap:6,marginBottom:3}}>
                <span style={{fontSize:13,fontWeight:800,color:"#102b4e",letterSpacing:"-0.01em"}}>48500.903331/2024-72</span>
                <span style={{
                  fontSize:8,padding:"1px 6px",borderRadius:9999,
                  background:"rgba(34,180,120,0.12)",color:"#1f9a66",fontWeight:700
                }}>Em andamento</span>
              </div>
              <div style={{fontSize:9,color:"#5a6068",marginBottom:5}}>
                Fiscalização da Distribuição: Processo Administrativo Sancionador
              </div>
              <div style={{display:"flex",gap:14,fontSize:8,color:"#5a6068"}}>
                <span><b style={{color:"#102b4e"}}>SFT</b> · Unidade</span>
                <span>Início <b style={{color:"#102b4e"}}>14/10/24</b></span>
                <span>Atualizado <b style={{color:"#102b4e"}}>16/03/26</b></span>
              </div>
            </div>
            <div style={{
              padding:"4px 8px",fontSize:9,fontWeight:600,
              background:"#d91965",color:"#fff",borderRadius:6,
              display:"flex",alignItems:"center",gap:4
            }}>
              <LandIcon name="arrow" size={9}/> Ver no SEI
            </div>
          </div>
        </div>

        {/* Timeline */}
        <div className="sei-collapsible" style={{padding:"10px 14px 0", overflow:"hidden",
          maxHeight: timelineGone ? 0 : 120, opacity: timelineGone ? 0 : 1,
          marginTop: timelineGone ? -6 : 0,
          transition:"max-height 600ms cubic-bezier(0.65,0,0.35,1), opacity 420ms ease, margin 500ms ease"}}>
          <div style={{
            background:"#fff",border:"1px solid #eef0f2",borderRadius:8,padding:"8px 10px"
          }}>
            <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:6}}>
              <span style={{fontSize:10,fontWeight:700,color:"#102b4e"}}>Linha do Tempo do Processo</span>
              <span style={{fontSize:8,color:"#9b6cd9",fontWeight:600}}>{synth ? "310 documentos · síntese" : "91 de 310 (com resumo)"}</span>
            </div>
            <div style={{position:"relative",padding:"4px 0 0"}}>
              {/* Connecting line */}
              <div style={{
                position:"absolute",left:8,right:8,top:14,height:2,
                background:"#eef0f2"
              }}/>
              <div style={{
                position:"absolute",left:8,top:14,height:2,
                width: lineFull ? "calc(100% - 16px)" : `calc(${(activeIdx / (TIMELINE_DOCS.length - 1)) * 100}% )`,
                maxWidth: "calc(100% - 16px)",
                background:"linear-gradient(90deg,#9b6cd9,#d91965)",
                transition:"width 600ms cubic-bezier(0.65, 0, 0.35, 1)"
              }}/>
              <div style={{
                display:"flex",justifyContent:"space-between",position:"relative"
              }}>
                {TIMELINE_DOCS.map((doc, i) => {
                  const isActive = !synth && i === activeIdx;
                  const isPast = allPast || i < activeIdx;
                  return (
                    <div key={i} style={{
                      display:"flex",flexDirection:"column",alignItems:"center",gap:3,
                      flex:1
                    }}>
                      <div style={{height:22,display:"flex",alignItems:"center",justifyContent:"center"}}>
                      <div className={synth ? "sei-node-on" : ""} style={{
                        width:isActive?22:16,height:isActive?22:16,
                        borderRadius:9999,
                        background: isActive ? "#9b6cd9" : "#fff",
                        border: (isActive || isPast) ? "2px solid #9b6cd9" : "2px solid #d6dadf",
                        display:"flex",alignItems:"center",justifyContent:"center",
                        color: isActive ? "#fff" : (isPast ? "#9b6cd9" : "#aab0b6"),
                        boxShadow: isActive ? "0 0 0 4px rgba(155,108,217,0.18)" : "none",
                        animation: synth ? `sei-node-glow 1100ms ease-in-out ${i * 90}ms infinite` : "none",
                        transition:"all 280ms ease"
                      }}>
                        <LandIcon name="newspaper" size={isActive?10:8}/>
                      </div>
                      </div>
                      <span style={{fontSize:7,color:"#5a6068",fontWeight:isActive?700:500}}>{doc.d}</span>
                      <span style={{fontSize:7,color: (isActive||isPast) ? "#9b6cd9" : "#9aa0a6",fontWeight:isActive?700:500}}>{doc.type}</span>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        </div>

        {/* Document detail card → compile stage → consolidated overview */}
        <div style={{padding:"10px 14px 14px",flex:1,minHeight:0}}>
          {phase === "synth" && (
            <div style={{
              background:"#fff",border:"1px solid #eef0f2",borderRadius:8,
              height:"100%"
            }}>
              <SeiSynth/>
            </div>
          )}

          {phase === "consolidated" && (
            <div className="sei-overview">
              <div className="sei-ov-head">
                <div className="sei-ov-icon"><LandIcon name="sparkles" size={15}/></div>
                <div style={{minWidth:0}}>
                  <div className="t1">Visão Geral do Processo</div>
                  <div className="t2">Resumo do processo gerado por IA · 310 documentos</div>
                </div>
              </div>
              <div className="sei-ov-title">RELATÓRIO TÉCNICO CONSOLIDADO</div>
              <div className="sei-ov-meta">Processo SEI nº 48500.903331/2024-72 · Última atualização 01/06/2026</div>
              <div className="sei-ov-meta">Tema: <b>Fiscalização da Distribuição — Processo Administrativo Sancionador</b></div>
              <div style={{display:"flex",gap:6,flexWrap:"wrap",margin:"8px 0 2px"}}>
                <span className="sei-ov-tag" style={{background:"rgba(217,25,101,0.12)",color:"#d91965"}}>ENEL SP</span>
                <span className="sei-ov-tag" style={{background:"rgba(155,108,217,0.14)",color:"#7c3aed"}}>Caducidade</span>
                <span className="sei-ov-tag" style={{background:"rgba(245,158,11,0.14)",color:"#b45309"}}>Evento climático</span>
                <span className="sei-ov-tag" style={{background:"rgba(31,154,102,0.12)",color:"#1f9a66"}}>Em andamento</span>
              </div>
              <div className="sei-ov-divider"/>
              <div className="sei-ov-points">
                {SEI_OVERVIEW_POINTS.map((p, i) => (
                  <div className="sei-ov-point" key={i} style={{animationDelay:`${200 + i * 160}ms`}}>
                    <span className="dot"/>
                    <span><span className="k">{p.k}:</span> {p.t}</span>
                  </div>
                ))}
              </div>
              <div className="sei-ov-divider"/>
              <div className="sei-ov-subhead">Andamento recente</div>
              <div className="sei-ov-tl">
                {SEI_OVERVIEW_TL.map((t, i) => (
                  <div className="sei-ov-tlrow" key={i} style={{animationDelay:`${900 + i * 140}ms`}}>
                    <span className="d">{t.d}</span>
                    <span className="dotc" style={{background:t.c}}/>
                    <span className="tt">{t.t}</span>
                  </div>
                ))}
              </div>
              <div className="sei-ov-foot">Ver relatório completo <LandIcon name="chevright" size={11} style={{transform:"rotate(90deg)"}}/></div>
            </div>
          )}

          {!synth && (
            <div style={{
              background:"#fff",border:"1px solid #eef0f2",borderRadius:8,padding:"10px 14px",
              height:"100%",display:"flex",flexDirection:"column",
              transform: phase === "walk" ? "translateY(4px)" : "translateY(0)",
              opacity: phase === "walk" ? 0.85 : 1,
              transition: "all 400ms ease"
            }}>
            <div style={{display:"flex",alignItems:"center",gap:6,marginBottom:4}}>
              <span style={{
                fontSize:8,padding:"2px 7px",borderRadius:9999,
                background:"rgba(155,108,217,0.14)",color:"#9b6cd9",fontWeight:700
              }}>Memória</span>
              <span style={{fontSize:8,color:"#5a6068"}}>4 de março de 2026</span>
            </div>
            <div style={{fontSize:10,fontWeight:700,color:"#102b4e",marginBottom:5,lineHeight:1.3,letterSpacing:"-0.01em"}}>
              Manifestação da Enel SP sobre o evento climático extremo dez/2025
            </div>
            <div style={{
              display:"inline-flex",alignItems:"center",gap:4,marginBottom:5,
              fontSize:8,fontWeight:700,color:"#d91965",letterSpacing:"0.05em",textTransform:"uppercase"
            }}>
              <LandIcon name="sparkles" size={8}/>Resumo do documento por IA
            </div>
            <div style={{
              fontSize:9,lineHeight:1.5,color:"#1a1d22",
              flex:1,minHeight:0,overflow:"hidden"
            }}>
              {summaryTyped}
              {phase === "summary" && summaryTyped.length < SEI_SUMMARY.length && (
                <span className="caret-dark"/>
              )}
            </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

/* ===================== SCREEN 3 — Diretores Dashboard ===================== */
const DIRECTORS = [
  { ini:"AM", name:"Agnes Maria de Aragão da Costa", role:"Diretora", mandate:"Mandato: 2022-2028", proc:"2.152", month:"6", grad:"linear-gradient(135deg,#ef9b3f,#d91965)" },
  { ini:"FL", name:"Fernando Luiz Mosna Ferreira da Silva", role:"Diretor", mandate:"Mandato: 2022-2026", proc:"2.171", month:"4", color:"#102b4e" },
  { ini:"GN", name:"Gentil Nogueira de Sá Júnior", role:"Diretor", mandate:"Mandato: N/A", proc:"186", month:"11", color:"#5a8e3a" },
];

const DONUT_ALL = [
  { label:"Geração",        value:44.9, color:"#d91965" },
  { label:"Transmissão",    value:23.4, color:"#1f6cd9" },
  { label:"Distribuição",   value:16.9, color:"#102b4e" },
  { label:"Comercialização",value: 6.3, color:"#5bb3e6" },
  { label:"Tarifa",         value: 5.8, color:"#ef9b3f" },
  { label:"Outros",         value: 2.7, color:"#aab0b6" },
];
const DONUT_AGNES = [
  { label:"Geração",        value:52.8, color:"#d91965" },
  { label:"Transmissão",    value:20.7, color:"#1f6cd9" },
  { label:"Distribuição",   value:15.0, color:"#102b4e" },
  { label:"Comercialização",value: 4.9, color:"#5bb3e6" },
  { label:"Tarifa",         value: 4.2, color:"#ef9b3f" },
  { label:"Outros",         value: 2.3, color:"#aab0b6" },
];
const ATOS_ALL = [
  { label:"Resolução Autorizativa", value:45.1, color:"#d91965" },
  { label:"Despacho",               value:31.6, color:"#102b4e" },
  { label:"Não informado",          value:14.4, color:"#c3c8cf" },
  { label:"Resolução Homologatória",value: 4.0, color:"#1f6cd9" },
  { label:"Outros",                 value: 4.9, color:"#aab0b6" },
];
const ATOS_AGNES = [
  { label:"Resolução Autorizativa", value:44.3, color:"#d91965" },
  { label:"Despacho",               value:40.8, color:"#102b4e" },
  { label:"Não informado",          value: 9.8, color:"#c3c8cf" },
  { label:"Resolução Homologatória",value: 2.5, color:"#1f6cd9" },
  { label:"Outros",                 value: 2.6, color:"#aab0b6" },
];

const DATASETS = {
  all:   { title:"Todos os Diretores", total:14608, month:26, approved:14364, apprPct:"99,3%", rejected:108, rejPct:"0,8%", donut:DONUT_ALL,   atos:ATOS_ALL },
  agnes: { title:"Agnes Maria de Aragão da Costa", total:2152, month:6, approved:2075, apprPct:"99,1%", rejected:18, rejPct:"0,9%", donut:DONUT_AGNES, atos:ATOS_AGNES },
};

const AGNES_QUESTION = "Qual foi o padrão de votação desta diretora em relação ao tema de Geração Distribuída nas últimas reuniões da diretoria ANEEL?";
const AGNES_POINTS = [
  "Cautela com subsídios cruzados da GD entre consumidores.",
  "Defesa de uma transição gradual nas regras de compensação (REN 1.000).",
  "Ênfase em sinal locacional e justiça tarifária.",
  "Apoio à modernização regulatória, com previsibilidade ao investidor.",
  "Voto majoritariamente alinhado à área técnica nos processos de GD.",
];
const AGNES_QUOTE = "…é preciso calibrar o incentivo à geração distribuída sem transferir custos indevidos aos demais consumidores; a transição prevista na REN 1.000 e o sinal locacional ajudam a equilibrar essa conta.";

const DiretoresScreen = () => {
  // Sequence: all → agnes (select) → chat → typing → answer
  const [phase, setPhase] = React.useState("all");
  const [donutPhase, setDonutPhase] = React.useState(0);
  const [typedQ, setTypedQ] = React.useState("");
  const [ans, setAns] = React.useState(false);
  const [reveal, setReveal] = React.useState(0);
  const [justSelected, setJustSelected] = React.useState(false);
  const msgRef = React.useRef(null);

  const isChat = phase === "chat" || phase === "typing" || phase === "answer";
  const selected = phase === "all" ? "all" : "agnes";
  const data = DATASETS[selected];

  // Master timeline
  React.useEffect(() => {
    let timers = [];
    setPhase("all"); setTypedQ(""); setAns(false); setReveal(0); setJustSelected(false);
    timers.push(setTimeout(() => { setPhase("agnes"); setJustSelected(true); }, 2800));
    timers.push(setTimeout(() => setJustSelected(false), 3950));
    timers.push(setTimeout(() => setPhase("chat"),  5600));
    timers.push(setTimeout(() => setPhase("typing"), 6900));
    for (let i = 1; i <= AGNES_QUESTION.length; i++) {
      timers.push(setTimeout(() => setTypedQ(AGNES_QUESTION.slice(0, i)), 6900 + i * 26));
    }
    const qEnd = 6900 + AGNES_QUESTION.length * 26;
    timers.push(setTimeout(() => setPhase("answer"), qEnd + 350));   // user bubble sends
    timers.push(setTimeout(() => setAns(true), qEnd + 2900));        // ~2.5s "thinking" before the answer
    // reveal the summary points one by one, THEN the literal citation (top-down)
    for (let i = 1; i <= AGNES_POINTS.length + 1; i++) {
      timers.push(setTimeout(() => setReveal(i), qEnd + 3100 + i * 700));
    }
    return () => timers.forEach(clearTimeout);
  }, []);

  // Animate donut whenever the active dataset changes (all → agnes)
  React.useEffect(() => {
    let raf, start; const dur = 1100;
    setDonutPhase(0);
    const step = (t) => {
      if (!start) start = t;
      const p = Math.min(1, (t - start) / dur);
      setDonutPhase(1 - Math.pow(1 - p, 3));
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [selected]);

  // Answer reveals top-down (pin to top so the points appear from the top first)
  React.useEffect(() => {
    const m = msgRef.current; if (m) m.scrollTop = 0;
  }, [ans, phase]);

  const fmt = (n) => n.toLocaleString("pt-BR");
  const tabs = ["Visão Geral","Processos","Chat de Análise","Transcrições"];
  const activeTab = isChat ? "Chat de Análise" : "Visão Geral";

  return (
    <div className="dir-fit" style={{display:"flex",height:"100%",background:"#fff",fontSize:10}}>
      <Sidebar active="users"/>

      {/* Directors sidebar */}
      <div style={{
        width: 156, background:"#fafbfc", borderRight:"1px solid #eef0f2",
        padding:"9px 8px", display:"flex", flexDirection:"column", gap:7, flexShrink:0, overflow:"hidden"
      }}>
        {/* Todos os Diretores block */}
        <div style={{
          display:"flex",alignItems:"flex-start",gap:7,padding:"7px 8px",borderRadius:7,
          background: selected==="all" ? "rgba(31,154,102,0.10)" : "#fff",
          border: selected==="all" ? "1px solid rgba(31,154,102,0.45)" : "1px solid #eef0f2",
          transition:"all 300ms ease"
        }}>
          <div style={{width:26,height:26,borderRadius:9999,background:"#1f9a66",color:"#fff",fontSize:8.5,fontWeight:700,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0}}>TD</div>
          <div style={{minWidth:0,flex:1}}>
            <div style={{fontSize:8.5,fontWeight:700,color:"#102b4e"}}>Todos os Diretores</div>
            <div style={{fontSize:7,color:"#9aa0a6",lineHeight:1.3}}>Visão consolidada</div>
            <div style={{display:"flex",gap:8,marginTop:3,fontSize:7,color:"#5a6068"}}>
              <span><b style={{color:"#102b4e"}}>5</b> Ativos</span>
              <span><b style={{color:"#102b4e"}}>17</b> Ex-diretores</span>
            </div>
          </div>
        </div>

        <div style={{fontSize:7,fontWeight:700,color:"#9aa0a6",letterSpacing:"0.07em",textTransform:"uppercase",padding:"0 2px"}}>Diretores Ativos</div>

        {DIRECTORS.map((d, i) => {
          const isSel = selected==="agnes" && i===0;
          const clicking = justSelected && i===0;
          return (
            <div key={i} className={clicking ? "dir-card-click" : ""} style={{
              display:"flex",alignItems:"flex-start",gap:7,padding:"7px 8px",borderRadius:7,
              background: isSel ? "rgba(217,25,101,0.07)" : "#fff",
              border: isSel ? "1px solid rgba(217,25,101,0.45)" : "1px solid #eef0f2",
              transition:"all 300ms ease", position:"relative"
            }}>
              {clicking && <span className="dir-tap-ring"/>}
              <div style={{width:26,height:26,borderRadius:9999,background:d.grad||d.color,color:"#fff",fontSize:8,fontWeight:700,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0}}>{d.ini}</div>
              <div style={{minWidth:0,flex:1}}>
                <div style={{fontSize:8,fontWeight:700,color:"#102b4e",lineHeight:1.2}}>{d.name}</div>
                <div style={{fontSize:7,color:"#9aa0a6"}}>{d.role}</div>
                <div style={{fontSize:6.5,color:"#9aa0a6"}}>{d.mandate}</div>
                <div style={{display:"flex",gap:8,marginTop:2,fontSize:7,color:"#5a6068"}}>
                  <span><b style={{color:"#102b4e"}}>{d.proc}</b> Proc.</span>
                  <span><b style={{color:"#102b4e"}}>{d.month}</b> Este mês</span>
                </div>
              </div>
            </div>
          );
        })}

        <div style={{flex:1}}/>
        <div style={{borderTop:"1px solid #eef0f2",paddingTop:7,display:"flex",flexDirection:"column",gap:4}}>
          <div style={{fontSize:7,fontWeight:700,color:"#102b4e"}}>Estatísticas Gerais</div>
          {[["Total de Processos","14.608"],["Reuniões c/ Transcrição","25"],["Horas de Transcrição","86h"]].map((r,i)=>(
            <div key={i} style={{display:"flex",justifyContent:"space-between",fontSize:7,color:"#5a6068"}}>
              <span>{r[0]}</span><b style={{color:"#102b4e"}}>{r[1]}</b>
            </div>
          ))}
        </div>
      </div>

      {/* Main */}
      <div style={{flex:1,display:"flex",flexDirection:"column",minWidth:0}}>
        {/* Tabs */}
        <div style={{display:"flex",borderBottom:"1px solid #eef0f2",padding:"0 14px",gap:16,flexShrink:0}}>
          {tabs.map((t, i) => {
            const on = t===activeTab;
            return (
              <div key={i} style={{
                padding:"10px 0",fontSize:9,fontWeight:on?700:500,
                color: on ? "#d91965" : "#5a6068",
                borderBottom: on ? "2px solid #d91965" : "2px solid transparent",
                display:"flex",alignItems:"center",gap:4,transition:"color 240ms ease"
              }}>
                <LandIcon name={["grid","filetext","message","newspaper"][i]} size={9}/>{t}
              </div>
            );
          })}
        </div>

        {!isChat && (
          <div style={{flex:1,padding:"11px 14px",display:"flex",flexDirection:"column",gap:9,minHeight:0,overflow:"hidden"}}>
            <div style={{fontSize:11,fontWeight:700,color:"#102b4e",letterSpacing:"-0.01em"}}>
              {data.title} — Visão Geral
            </div>
            <div style={{display:"grid",gridTemplateColumns:"1.05fr 1fr",gap:10,flex:1,minHeight:0}}>
              {/* Donut */}
              <div style={{background:"#fff",border:"1px solid #eef0f2",borderRadius:8,padding:"10px 12px",display:"flex",flexDirection:"column",gap:6}}>
                <div style={{fontSize:9,fontWeight:700,color:"#102b4e"}}>Distribuição de Processos por Tema</div>
                <div style={{flex:1,display:"flex",alignItems:"center",gap:10,minHeight:0}}>
                  <DonutChart segments={data.donut} phase={donutPhase} total={fmt(data.total)}/>
                  <div style={{display:"grid",gridTemplateColumns:"1fr",gap:3,flex:1,minWidth:0}}>
                    {data.donut.map((s, i) => (
                      <div key={i} style={{display:"flex",alignItems:"center",gap:5,fontSize:7.5}}>
                        <span style={{width:7,height:7,borderRadius:2,background:s.color,flexShrink:0}}/>
                        <span style={{color:"#5a6068",flex:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}}>{s.label}</span>
                        <span style={{color:"#102b4e",fontWeight:700}}>{s.value.toFixed(1)}%</span>
                      </div>
                    ))}
                  </div>
                </div>
              </div>

              {/* Stats + atos */}
              <div style={{display:"flex",flexDirection:"column",gap:8,minHeight:0}}>
                <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:7}}>
                  <StatBlock value={fmt(data.total)} label="Processos Relatados (Total)" color="#d91965"/>
                  <StatBlock value={fmt(data.month)} label="Processos este Mês" color="#102b4e"/>
                  <StatBlock value={fmt(data.approved)} label="Processos Aprovados" color="#1f9a66" sub={`(${data.apprPct} de aprovação)`}/>
                  <StatBlock value={fmt(data.rejected)} label="Processos Rejeitados" color="#d91965" sub={`(${data.rejPct} de rejeição)`}/>
                </div>
                <div style={{background:"#fff",border:"1px solid #eef0f2",borderRadius:8,padding:"9px 11px",flex:1,minHeight:0,display:"flex",flexDirection:"column",gap:5}}>
                  <div style={{fontSize:8.5,fontWeight:700,color:"#102b4e"}}>Tipos de Atos Administrativos</div>
                  {data.atos.map((a, i) => (
                    <div key={i} style={{display:"flex",alignItems:"center",gap:6,fontSize:7}}>
                      <span style={{width:74,color:"#5a6068",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flexShrink:0}}>{a.label}</span>
                      <span style={{flex:1,height:7,borderRadius:9999,background:"#f0f1f3",overflow:"hidden"}}>
                        <span style={{display:"block",height:"100%",borderRadius:9999,background:a.color,width:`${a.value * donutPhase}%`,transition:"width 500ms ease"}}/>
                      </span>
                      <span style={{width:26,textAlign:"right",color:"#102b4e",fontWeight:700,flexShrink:0}}>{a.value.toFixed(1)}%</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        )}

        {isChat && (
          <div style={{flex:1,display:"flex",flexDirection:"column",minWidth:0,minHeight:0}}>
            {/* Filters */}
            <div style={{display:"flex",gap:7,padding:"9px 14px",borderBottom:"1px solid #eef0f2",flexShrink:0}}>
              {["Temas","Processos","Reuniões"].map((f,i)=>(
                <div key={i} style={{display:"inline-flex",alignItems:"center",gap:6,padding:"5px 10px",borderRadius:7,border:"1px solid #e6e7e8",background:"#fff",fontSize:8,color:"#5a6068",fontWeight:600}}>
                  <LandIcon name="filesearch" size={8}/>{f}<LandIcon name="chevright" size={8} style={{transform:"rotate(90deg)",opacity:0.6}}/>
                </div>
              ))}
            </div>

            <div ref={msgRef} style={{flex:1,padding:"12px 14px",overflow:"hidden",display:"flex",flexDirection:"column",gap:10,minHeight:0}}>
              {phase !== "answer" ? (
                /* Welcome card */
                <div style={{background:"linear-gradient(180deg,#fdeef4,#fef6f9)",border:"1px solid rgba(217,25,101,0.18)",borderLeft:"3px solid #d91965",borderRadius:10,padding:"14px 16px"}}>
                  <div style={{fontSize:13,fontWeight:800,color:"#102b4e",marginBottom:6}}>👋 Olá! Sou o assistente de análise de diretores da SEL.IA</div>
                  <div style={{fontSize:12,color:"#5a6068",lineHeight:1.5,marginBottom:10}}>Posso ajudá-lo a entender o comportamento e decisões dos diretores da ANEEL. Selecione um diretor na barra lateral e faça sua pergunta!</div>
                  <div style={{fontSize:10.5,color:"#9aa0a6",marginBottom:7,fontWeight:600}}>Sugestões de perguntas:</div>
                  <div style={{display:"flex",flexWrap:"wrap",gap:6}}>
                    {["Posicionamentos sobre GD","Revisão tarifária","Divergências","Transmissão"].map((c,i)=>(
                      <span key={i} style={{display:"inline-flex",alignItems:"center",gap:5,padding:"6px 11px",borderRadius:9999,background:"#fff",border:"1px solid rgba(217,25,101,0.25)",fontSize:10.5,fontWeight:600,color:"#d91965"}}>
                        <LandIcon name={["sparkles","target","book","zap"][i] || "sparkles"} size={10}/>{c}
                      </span>
                    ))}
                  </div>
                </div>
              ) : (
                <>
                  {/* User question */}
                  <div style={{alignSelf:"flex-end",maxWidth:"82%",background:"#102b4e",color:"#fff",padding:"8px 12px",borderRadius:"12px 12px 2px 12px",fontSize:13,lineHeight:1.5}}>
                    {AGNES_QUESTION}
                  </div>
                  {/* AI answer */}
                  <div style={{display:"flex",gap:8,maxWidth:"94%"}}>
                    <div style={{width:24,height:24,borderRadius:9999,background:"linear-gradient(135deg,#d91965,#ef405b)",color:"#fff",fontSize:9,fontWeight:800,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0}}>S</div>
                    <div style={{flex:1,minWidth:0}}>
                      {!ans ? (
                        <div style={{display:"inline-flex",gap:3,padding:"6px 2px"}}>
                          <span className="think-dot"/><span className="think-dot"/><span className="think-dot"/>
                        </div>
                      ) : (
                        <div className="src-zoom-in" style={{fontSize:13,lineHeight:1.5,color:"#1a1d22"}}>
                          <div style={{fontSize:13.5,fontWeight:800,color:"#102b4e",marginBottom:7}}>Resumo das Falas de Agnes — Geração Distribuída</div>
                          <div style={{display:"flex",flexDirection:"column",gap:6,marginBottom:11}}>
                            {AGNES_POINTS.slice(0, reveal).map((p,i)=>(
                              <div key={i} className="sei-ov-point" style={{fontSize:12,color:"#1a1d22"}}>
                                <span className="dot"/><span>{p}</span>
                              </div>
                            ))}
                          </div>
                          {reveal > AGNES_POINTS.length && (
                            <div className="sei-ov-point" style={{display:"block"}}>
                              <div style={{fontSize:12.5,fontWeight:700,color:"#102b4e",marginBottom:6}}>Exemplo de Citação Literal</div>
                              <div style={{borderLeft:"3px solid #d91965",padding:"4px 0 4px 11px",fontSize:12,fontStyle:"italic",color:"#5a6068",lineHeight:1.55}}>
                                “{AGNES_QUOTE}” <span style={{fontStyle:"normal",fontWeight:700,color:"#102b4e"}}>— Agnes Maria de Aragão da Costa</span>, 9º RPO, 5/5/2026
                              </div>
                              <div style={{fontSize:9,color:"#9aa0a6",marginTop:9}}>Exemplo ilustrativo · SEL.IA pode cometer erros. Verifique informações importantes.</div>
                            </div>
                          )}
                        </div>
                      )}
                    </div>
                  </div>
                </>
              )}
            </div>

            {/* Input */}
            <div style={{padding:"9px 14px 12px",borderTop:"1px solid #eef0f2",background:"#fafbfc",flexShrink:0}}>
              <div style={{display:"flex",alignItems:"center",background:"#fff",border:"1px solid #e6e7e8",borderRadius:8,padding:"7px 8px 7px 12px",fontSize:12}}>
                <span style={{flex:1,color: typedQ && phase==="typing" ? "#1a1d22" : "#9aa0a6",whiteSpace:"normal",lineHeight:1.35}}>
                  {phase==="typing" && typedQ ? <>{typedQ}<span className="caret-dark"/></> : "Pergunte sobre as falas dos diretores…"}
                </span>
                <div style={{padding:"6px 13px",borderRadius:6,background:"linear-gradient(135deg,#d91965,#ef405b)",color:"#fff",fontSize:10,fontWeight:700,flexShrink:0,marginLeft:8}}>Enviar</div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

const StatBlock = ({ value, label, color, sub }) => (
  <div style={{
    background:"#fff",border:"1px solid #eef0f2",borderRadius:6,
    padding:"8px 10px",display:"flex",flexDirection:"column",gap:2,
    justifyContent:"center"
  }}>
    <div style={{fontSize:14,fontWeight:800,color,letterSpacing:"-0.02em",lineHeight:1}}>{value}</div>
    <div style={{fontSize:7.5,color:"#5a6068",lineHeight:1.2}}>{label}</div>
    {sub && <div style={{fontSize:7,color:"#9aa0a6"}}>{sub}</div>}
  </div>
);

const DonutChart = ({ segments, phase, total }) => {
  const size = 96;
  const r = 36;
  const cx = size / 2, cy = size / 2;
  const C = 2 * Math.PI * r;
  let acc = 0;
  return (
    <div style={{position:"relative",width:size,height:size,flexShrink:0}}>
      <svg width={size} height={size} style={{transform:"rotate(-90deg)"}}>
        <circle cx={cx} cy={cy} r={r} fill="none" stroke="#f0f1f3" strokeWidth={14}/>
        {segments.map((s, i) => {
          const len = (s.value / 100) * C * phase;
          const offset = -acc * phase;
          acc += (s.value / 100) * C;
          return (
            <circle key={i} cx={cx} cy={cy} r={r} fill="none"
              stroke={s.color} strokeWidth={14}
              strokeDasharray={`${len} ${C}`}
              strokeDashoffset={offset}
            />
          );
        })}
      </svg>
      <div style={{
        position:"absolute",inset:0,display:"flex",flexDirection:"column",
        alignItems:"center",justifyContent:"center"
      }}>
        <div style={{fontSize:13,fontWeight:800,color:"#102b4e",letterSpacing:"-0.02em",lineHeight:1}}>{total}</div>
        <div style={{fontSize:7,color:"#5a6068"}}>processos</div>
      </div>
    </div>
  );
};

/* ===================== SCREEN 4 — Participação Social ===================== */
const CP_DOCS = [
  { name:"Aviso de Abertura da CP 008/2026", type:"PDF" },
  { name:"Modelo para envio de contribuições", type:"DOC" },
  { name:"Minuta de Resolução Normativa", type:"PDF" },
  { name:"Nota Técnica nº 57/2026-STD/ANEEL", type:"PDF" },
];
const CP_CONTRIB = [
  { org:"COCEN Paulista", ini:"CP", stance:"Apoio",    color:"#1f9a66", text:"apoiou a minuta — limite de 31/03 e exigência de garantias." },
  { org:"CONCEN/MS",      ini:"CM", stance:"Apoio",    color:"#1f9a66", text:"favorável à manutenção da data contratada." },
  { org:"ENGIE",          ini:"EN", stance:"Ressalva", color:"#ef9b3f", text:"vê restrições não previstas em lei ao ajuste do CUST." },
  { org:"ABEEólica",      ini:"AB", stance:"Ressalva", color:"#ef9b3f", text:"efeitos do ajuste independentes do ciclo tarifário." },
  { org:"Voltalia",       ini:"VO", stance:"Proposta", color:"#1f6cd9", text:"tratamento específico para EUST já pagos, com compensação." },
  { org:"PEC Energia",    ini:"PE", stance:"Proposta", color:"#1f6cd9", text:"postergação do início do CUST de até 84 meses." },
];

const ParticipacaoScreen = () => {
  const userText = "Resuma as contribuições da fase de Contribuições";
  const q2 = "faça um relatório com o resumo das contribuições para apresentação à minha diretoria";
  const [phase, setPhase] = React.useState("process"); // process → panel → ask → answer → report
  const [cycle, setCycle] = React.useState(0);
  const [typed, setTyped] = React.useState("");
  const [clicked, setClicked] = React.useState(false);
  const [panelIn, setPanelIn] = React.useState(false);
  const [answer, setAnswer] = React.useState(false);
  const [shown, setShown] = React.useState(0);
  const [typed2, setTyped2] = React.useState("");
  const [writing, setWriting] = React.useState(false);
  const [reportReady, setReportReady] = React.useState(false);
  const [reportModal, setReportModal] = React.useState(false);
  const [reportIn, setReportIn] = React.useState(false);
  const [bars, setBars] = React.useState(false);
  const bodyRef = React.useRef(null);
  const repBodyRef = React.useRef(null);

  React.useEffect(() => {
    const T = [];
    const push = (fn, ms) => T.push(setTimeout(fn, ms));
    setPhase("process"); setTyped(""); setClicked(false); setPanelIn(false); setAnswer(false); setShown(0);
    setTyped2(""); setWriting(false); setReportReady(false); setReportModal(false); setReportIn(false); setBars(false);
    push(() => setClicked(true), 2300);
    push(() => { setPhase("panel"); setPanelIn(true); }, 2950);
    push(() => setPhase("ask"), 3550);
    for (let i = 1; i <= userText.length; i++) push(() => setTyped(userText.slice(0, i)), 3550 + i * 26);
    const qEnd = 3550 + userText.length * 26;
    push(() => setPhase("answer"), qEnd + 400);
    push(() => setAnswer(true), qEnd + 2600);
    const aStart = qEnd + 3100;
    for (let i = 1; i <= CP_CONTRIB.length; i++) push(() => setShown(i), aStart + (i - 1) * 1300);
    // — second exchange: generate an HTML report → modal
    const contribEnd = aStart + (CP_CONTRIB.length - 1) * 1300 + 1400;
    const t1 = contribEnd + 1300;
    push(() => { setPhase("report"); setTyped2(""); }, t1);
    for (let i = 1; i <= q2.length; i++) push(() => setTyped2(q2.slice(0, i)), t1 + i * 22);
    const q2End = t1 + q2.length * 22;
    push(() => setWriting(true), q2End + 350);
    push(() => { setWriting(false); setReportReady(true); }, q2End + 2400);
    push(() => setReportModal(true), q2End + 3500);
    push(() => setReportIn(true), q2End + 3560);
    push(() => setBars(true), q2End + 4000);
    push(() => setCycle((c) => c + 1), q2End + 13500); // loop the whole sequence
    return () => T.forEach(clearTimeout);
  }, [cycle]);

  React.useEffect(() => { const b = bodyRef.current; if (b) b.scrollTop = b.scrollHeight; }, [shown, answer, typed, typed2, writing, reportReady]);

  // slow auto-scroll through the report modal to reveal chart + table + conclusion
  React.useEffect(() => {
    if (!reportIn) return;
    const el = repBodyRef.current; if (!el) return;
    let raf, start;
    const begin = setTimeout(() => {
      const dur = 6500;
      const step = (t) => {
        if (!start) start = t;
        const p = Math.min(1, (t - start) / dur);
        const max = el.scrollHeight - el.clientHeight;
        el.scrollTop = max * (p < 0.5 ? 2 * p * p : 1 - Math.pow(-2 * p + 2, 2) / 2);
        if (p < 1) raf = requestAnimationFrame(step);
      };
      raf = requestAnimationFrame(step);
    }, 1200);
    return () => { clearTimeout(begin); if (raf) cancelAnimationFrame(raf); };
  }, [reportIn]);

  const tagStyle = (bg, fg) => ({ fontSize:8, fontWeight:700, padding:"2px 7px", borderRadius:9999, background:bg, color:fg });

  return (
    <div style={{display:"flex",height:"100%",background:"#fff",fontSize:10,position:"relative"}}>
      <Sidebar active="clipboard"/>
      <div style={{flex:1,display:"flex",flexDirection:"column",minWidth:0,background:"#f6f7f9"}}>
        <div style={{padding:"9px 16px",background:"#fff",borderBottom:"1px solid #eef0f2",fontSize:9,color:"#9aa0a6",display:"flex",gap:6,alignItems:"center"}}>
          Participação Social <LandIcon name="chevright" size={8}/> <b style={{color:"#102b4e"}}>Consulta Pública 008/2026</b>
        </div>

        {/* process card */}
        <div style={{padding:"12px 16px 0"}}>
          <div style={{background:"#fff",border:"1px solid #eef0f2",borderRadius:10,padding:"12px 14px"}}>
            <div style={{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:10}}>
              <div style={{minWidth:0}}>
                <div style={{fontSize:14,fontWeight:800,color:"#102b4e",letterSpacing:"-0.01em"}}>Consulta Pública 008/2026</div>
                <div style={{display:"flex",gap:6,margin:"6px 0"}}>
                  <span style={tagStyle("rgba(31,108,217,0.12)","#1f6cd9")}>Consulta Pública</span>
                  <span style={tagStyle("rgba(16,43,78,0.08)","#5a6068")}>Encerrada</span>
                </div>
                <div style={{fontSize:9,color:"#5a6068",lineHeight:1.45,maxWidth:340}}>
                  Obter subsídios sobre a regulamentação do art. 26, §1º-W da Lei nº 9.427/1996.
                </div>
              </div>
              <div className={"cp-analisar" + (clicked ? " click" : "")}>
                <LandIcon name="sparkles" size={11}/>Analisar com a SELIA
              </div>
            </div>
            <div style={{display:"flex",gap:16,marginTop:10,paddingTop:9,borderTop:"1px solid #eef0f2",fontSize:8,color:"#5a6068"}}>
              <span>Modalidade <b style={{color:"#102b4e"}}>Intercâmbio Documental</b></span>
              <span>Período <b style={{color:"#102b4e"}}>23/04 a 12/05/2026</b></span>
            </div>
          </div>
        </div>

        {/* docs */}
        <div style={{padding:"10px 16px 14px",display:"flex",flexDirection:"column",gap:6,flex:1,minHeight:0,overflow:"hidden"}}>
          {CP_DOCS.map((d, i) => (
            <div key={i} style={{display:"flex",alignItems:"center",gap:9,background:"#fff",border:"1px solid #eef0f2",borderRadius:8,padding:"8px 11px"}}>
              <div style={{width:24,height:24,borderRadius:7,background:"rgba(217,25,101,0.10)",color:"#d91965",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0}}>
                <LandIcon name="filetext" size={13}/>
              </div>
              <div style={{flex:1,minWidth:0}}>
                <div style={{fontSize:9.5,fontWeight:600,color:"#102b4e",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}}>{d.name}</div>
                <div style={{fontSize:7.5,color:"#9aa0a6"}}>{d.type}</div>
              </div>
              <LandIcon name="chevright" size={11} style={{color:"#c3c8cf",transform:"rotate(90deg)"}}/>
            </div>
          ))}
        </div>
      </div>

      {/* SELIA chat panel */}
      <div className={"cp-panel" + (panelIn ? " in" : "")}>
        <div style={{display:"flex",alignItems:"center",gap:9,padding:"10px 13px",borderBottom:"1px solid #eef0f2",flexShrink:0}}>
          <div style={{width:28,height:28,borderRadius:8,background:"linear-gradient(135deg,#d91965,#ef405b)",color:"#fff",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0}}>
            <LandIcon name="sparkles" size={14}/>
          </div>
          <div style={{flex:1,minWidth:0}}>
            <div style={{fontSize:12,fontWeight:800,color:"#102b4e"}}>SEL.IA</div>
            <div style={{fontSize:8.5,color:"#9aa0a6"}}>Consulta Pública 008/2026</div>
          </div>
          <LandIcon name="x" size={13} style={{color:"#aab0b6"}}/>
        </div>

        <div ref={bodyRef} style={{flex:1,minHeight:0,overflow:"hidden",padding:"12px 13px",display:"flex",flexDirection:"column",gap:10}}>
          {typed && (
            <div style={{alignSelf:"flex-end",maxWidth:"86%",background:"#102b4e",color:"#fff",padding:"8px 12px",borderRadius:"12px 12px 2px 12px",fontSize:12,lineHeight:1.4}}>
              {typed}{phase === "ask" && typed.length < userText.length && <span className="caret"/>}
            </div>
          )}

          {(answer || phase === "answer") && (
            <div style={{display:"flex",gap:8}}>
              <div style={{width:22,height:22,borderRadius:9999,background:"linear-gradient(135deg,#d91965,#ef405b)",color:"#fff",fontSize:8,fontWeight:800,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0}}>S</div>
              <div style={{flex:1,minWidth:0}}>
                {!answer ? (
                  <div style={{display:"inline-flex",gap:3,padding:"6px 2px"}}>
                    <span className="think-dot"/><span className="think-dot"/><span className="think-dot"/>
                  </div>
                ) : (
                  <div className="src-zoom-in">
                    <div style={{fontSize:12,lineHeight:1.5,color:"#1a1d22",marginBottom:9}}>
                      Na fase de <b>Contribuições</b> houve <b style={{color:"#d91965"}}>12 manifestações</b> — predominância de apoio, com ressalvas sobre <b>prazo, ônus e salvaguardas</b>.
                    </div>
                    <div style={{display:"flex",alignItems:"center",gap:7,marginBottom:8,fontSize:9,fontWeight:700,color:"#9aa0a6",letterSpacing:"0.04em",textTransform:"uppercase"}}>
                      <LandIcon name="briefcase" size={11} style={{color:"#d91965"}}/>{shown} de 12 manifestações analisadas
                    </div>
                    <div style={{display:"flex",flexDirection:"column",gap:7}}>
                      {CP_CONTRIB.slice(0, shown).map((c, i) => (
                        <div key={i} className="cp-contrib" style={{display:"flex",gap:9,alignItems:"flex-start",background:"#fafbfc",border:"1px solid #eef0f2",borderRadius:9,padding:"8px 10px"}}>
                          <div className={"cp-orgico" + (i === shown - 1 ? " new" : "")} style={{width:26,height:26,borderRadius:9999,background:c.color,color:"#fff",fontSize:8.5,fontWeight:700,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0}}>{c.ini}</div>
                          <div style={{flex:1,minWidth:0}}>
                            <div style={{display:"flex",alignItems:"center",gap:6,marginBottom:2}}>
                              <span style={{fontSize:11,fontWeight:700,color:"#102b4e"}}>{c.org}</span>
                              <span style={tagStyle(c.color + "22", c.color)}>{c.stance}</span>
                            </div>
                            <div style={{fontSize:10,lineHeight:1.4,color:"#5a6068"}}>{c.text}</div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            </div>
          )}

          {typed2 && (
            <div style={{alignSelf:"flex-end",maxWidth:"86%",background:"#102b4e",color:"#fff",padding:"8px 12px",borderRadius:"12px 12px 2px 12px",fontSize:12,lineHeight:1.4}}>
              {typed2}{typed2.length < q2.length && <span className="caret"/>}
            </div>
          )}
          {(writing || reportReady) && (
            <div style={{display:"flex",gap:8}}>
              <div style={{width:22,height:22,borderRadius:9999,background:"linear-gradient(135deg,#d91965,#ef405b)",color:"#fff",fontSize:8,fontWeight:800,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0}}>S</div>
              <div style={{flex:1,minWidth:0}}>
                {writing && <div className="cp-writing"><span className="spin"/>Gerando relatório…</div>}
                {reportReady && (
                  <div className="src-zoom-in">
                    <div style={{fontSize:12,lineHeight:1.5,color:"#1a1d22",marginBottom:8}}>Preparei o relatório para apresentação executiva da diretoria:</div>
                    <div className="cp-repcard">
                      <div className="rc-ico"><LandIcon name="filetext" size={15}/></div>
                      <div style={{flex:1,minWidth:0}}>
                        <div className="rc-name">Relatório gerencial — resumo das contribuições</div>
                        <div className="rc-meta">Pronto para apresentação · Abrir relatório</div>
                      </div>
                      <LandIcon name="arrow" size={14} className="rc-arrow"/>
                    </div>
                  </div>
                )}
              </div>
            </div>
          )}
        </div>

        <div style={{padding:"9px 13px 11px",borderTop:"1px solid #eef0f2",background:"#fafbfc",flexShrink:0}}>
          <div style={{display:"flex",alignItems:"center",background:"#fff",border:"1px solid #e6e7e8",borderRadius:8,padding:"7px 8px 7px 12px",fontSize:10.5,color:"#9aa0a6"}}>
            <span style={{flex:1}}>Pergunte sobre este processo de participação social…</span>
            <div style={{width:24,height:24,borderRadius:6,background:"linear-gradient(135deg,#d91965,#ef405b)",color:"#fff",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0}}>
              <LandIcon name="send" size={11}/>
            </div>
          </div>
        </div>
      </div>

      {/* generated report modal */}
      {reportModal && (
        <div className={"cp-rep-overlay" + (reportIn ? " in" : "")}>
          <div className="cp-rep-modal">
            <div className="cp-rep-head">
              <div className="t">Relatório gerencial – resumo das contribuições</div>
              <div className="acts"><span><LandIcon name="arrowdown" size={10}/>Baixar HTML</span><span>Fechar</span></div>
            </div>
            <div className="cp-rep-body" ref={repBodyRef}>
              <div className="cp-rep-inner">
                <div className="cp-rep-hero">
                  <div className="h">Relatório gerencial – resumo das contribuições</div>
                  <div className="s">Consulta Pública 008/2026 · Fase de Contribuições · 12 manifestações analisadas</div>
                </div>
                <div className="cp-rep-msg"><b>Mensagem principal:</b> houve apoio majoritário ao objetivo regulatório, mas com divergência relevante sobre o alcance do direito de ajuste do CUST — especialmente prazo, efeitos por ciclo tarifário e ausência de ônus.</div>
                <div className="cp-rep-stats">
                  <div className="cp-rep-stat" style={{borderTopColor:"#d91965"}}><div className="lab">Contribuições</div><div className="num">12</div><div className="sub">manifestações na fase</div></div>
                  <div className="cp-rep-stat" style={{borderTopColor:"#102b4e"}}><div className="lab">Apoio predominante</div><div className="num">9</div><div className="sub">favoráveis ou com ressalvas</div></div>
                  <div className="cp-rep-stat" style={{borderTopColor:"#ef9b3f"}}><div className="lab">Tema crítico</div><div className="num">3</div><div className="sub">eixos: prazo, ônus e garantias</div></div>
                </div>
                <div className="cp-rep-h">Distribuição qualitativa das posições</div>
                <div className="cp-rep-bars">
                  {[{l:"Favoráveis",v:6,c:"#1f9a66"},{l:"Parc. favoráveis",v:3,c:"#ef9b3f"},{l:"Ênfase flexibilização",v:3,c:"#d91965"}].map((b,i)=>(
                    <div key={i} className="cp-rep-bar"><div className="bar" style={{height: bars ? (b.v/6*100)+"%" : "0%", background:b.c}}/><span className="blab">{b.l}</span></div>
                  ))}
                </div>
                <div className="cp-rep-h">Leitura executiva por grupo de posição</div>
                <table className="cp-rep-table">
                  <thead><tr><th>Grupo</th><th>Entidades</th><th>Síntese</th></tr></thead>
                  <tbody>
                    <tr><td className="g">Apoio com foco em neutralidade tarifária</td><td className="e">COCEN Paulista, CONCEN/MS, ONS, PEC Energia</td><td>Disciplina procedimental para evitar efeitos redistributivos nos ciclos tarifários, com manutenção de garantias e prazos.</td></tr>
                    <tr><td className="g">Apoio com ressalvas</td><td className="e">INEL, CONCCEL, CONERGE</td><td>Concordam com a regulamentação, mas alertam que salvaguardas não devem gerar ônus incompatíveis com a lei.</td></tr>
                    <tr><td className="g">Maior flexibilização para geradores</td><td className="e">ABEEólica, ENGIE, Voltalia</td><td>Leitura mais ampla do ajuste livre e não oneroso, com menor rigidez quanto ao ciclo tarifário.</td></tr>
                  </tbody>
                </table>
                <div className="cp-rep-concl"><b>Conclusão para diretoria:</b> o processo não revela oposição concentrada ao objeto regulatório, mas disputa sobre o desenho da implementação. O ponto decisivo para deliberação é o equilíbrio entre neutralidade tarifária e a efetividade do direito legal de ajuste sem ônus.</div>
              </div>
            </div>
            <div className="cp-rep-foot"><span><LandIcon name="filetext" size={10}/>Exportar PDF</span></div>
          </div>
        </div>
      )}
    </div>
  );
};

window.LaptopMockup = LaptopMockup;
