/* SEL.IA — "Converse com os Dados" (BDGD) didactic+dynamic demo. Loops 3 técnica Q&As. */

const bell = (peak, w) => Array.from({length:24},(_,h)=>{ const x=(h-12.5)/w; return Math.max(0, peak*Math.exp(-x*x)); });
const fluxBars = Array.from({length:24},(_,h)=>{
  const gen = bell(1500,3.0)[h];
  const load = 520 + 230*Math.sin((h-7)/24*6.28);
  return Math.round(load - gen); // negative midday = reverse flow
});
const genLine = bell(1500,3.2).map(v=>Math.round(v));

const DD_Q = [
  { id:"flux",
    q:"Faça um gráfico do fluxo horário do transformador com maior fluxo reverso (Enel SP).",
    a:<>Levantei o transformador com maior fluxo reverso na Enel SP: o <b>14483607</b> (alimentador <b>GNA0102</b>). O pior valor ocorreu em <b>abril</b>, com fluxo líquido mínimo de <b>−1.406,7 kW</b> por volta das <b>13h</b> — exportação líquida relevante.</>,
    chart:{ kind:"signed", title:"Fluxo horário — transformador 14483607 (Enel SP · abril)", bars:fluxBars, line:genLine, barLabel:"Fluxo líquido (kW)", lineLabel:"Geração distribuída (kW)", xlabels:Array.from({length:24},(_,h)=>h+1), every:2 },
    read:["Reversão de fluxo concentrada entre 9h e 16h.","Pico de geração distribuída no miolo do dia, superando a carga local.","Fora dessa janela, o transformador volta ao fluxo positivo (atendimento normal)."] },
  { id:"rede",
    q:"Qual o comprimento de rede AT, MT, BT e ramal da empresa? Faça um gráfico.",
    a:<>Para a Enel SP (BDGD 2024): <b>Rede AT 1.892 km</b>, <b>MT 22.244 km</b>, <b>BT 40.330 km</b> e <b>Ramal 60.216 km</b>.</>,
    chart:{ kind:"bars", title:"Comprimento de rede por nível de tensão e ramal — Enel SP (2024)", bars:[1892,22244,40330,60216], xlabels:["Rede AT","Rede MT","Rede BT","Ramal"], unit:"km" },
    table:[["Rede AT","1.892,14 km"],["Rede MT","22.243,92 km"],["Rede BT","40.329,61 km"],["Ramal","60.215,97 km"]],
    read:["Malha fortemente concentrada em baixa tensão e, principalmente, em ramais.","A rede AT representa uma fração mínima da extensão total.","Perfil típico de distribuidora urbana de grande porte."] },
  { id:"dec",
    q:"Top 10 conjuntos com maior DEC vs limite regulatório.",
    a:<>Os <b>10 conjuntos</b> com maior DEC apurado em 2024 ficaram <b>todos acima do limite</b>. O pior foi <b>Juquitiba (23,06 h)</b> frente a um limite de 15 h; o caso mais crítico em distância do limite é o <b>Centro (15,68 h vs 3 h)</b>.</>,
    chart:{ kind:"combo", title:"Top 10 conjuntos — DEC apurado vs limite (Enel SP · 2024)",
      bars:[23.06,17.9,15.5,15.68,15.0,15.0,13.6,13.6,13.6,13.0], line:[15,9,3,12.7,8.6,9,11.2,10,10.2,9.4],
      xlabels:["JUQUITIBA","CAUCAIA","CENTRO","PARELHEIROS","—","VARGEM G.","—","RIO GRANDE","—","PARNAÍBA"], barLabel:"DEC apurado (h)", lineLabel:"Limite DEC (h)", every:1 },
    read:["Os 10 conjuntos do ranking ficaram acima do limite de DEC.","Pior resultado: Juquitiba, 23,06 h (limite 15 h).","Caso mais crítico vs limite: Centro, 15,68 h para um limite de 3 h."] },
];

const DDChart = ({ spec, grow }) => {
  const W = 600, H = 200, padB = 26, padT = 8, padL = 4;
  const n = spec.bars.length;
  const gap = W / n;
  const bw = gap * (spec.kind === "bars" ? 0.5 : 0.62);
  const signed = spec.kind === "signed";
  const maxAbs = Math.max(...spec.bars.map(Math.abs), ...(spec.line || []).map(Math.abs));
  const base = signed ? (padT + (H - padB - padT) * 0.55) : (H - padB);
  const usable = signed ? Math.min(base - padT, (H - padB) - base) : (H - padB - padT);
  const scale = (v) => (Math.abs(v) / maxAbs) * (signed ? Math.min(base - padT, (H - padB) - base) : usable);
  const lineY = (v) => base - (v / maxAbs) * (base - padT);
  const linePts = (spec.line || []).map((v, i) => `${i * gap + gap / 2},${lineY(v)}`).join(" ");
  return (
    <div className="dd-chart">
      <div className="dd-chart-title">{spec.title}</div>
      <svg viewBox={`0 0 ${W} ${H}`}>
        <line x1="0" y1={base} x2={W} y2={base} stroke="#e6e7e8" strokeWidth="1"/>
        {spec.bars.map((v, i) => {
          const h = grow ? scale(v) : 0;
          const x = i * gap + (gap - bw) / 2;
          const y = v >= 0 ? base - h : base;
          return <rect key={i} className="dd-bar" x={x} y={y} width={bw} height={h} rx="2"
            fill={v < 0 ? "#d91965" : "#e0287f"} style={{ transitionDelay: `${i * 25}ms` }}/>;
        })}
        {spec.line && (
          <polyline className="dd-line" points={linePts} fill="none" stroke="#ef9b3f" strokeWidth="2.5"
            strokeLinejoin="round" strokeDasharray="1400" strokeDashoffset={grow ? 0 : 1400}/>
        )}
        {spec.line && spec.line.map((v, i) => (
          <circle key={i} cx={i * gap + gap / 2} cy={lineY(v)} r="2.6" fill="#fff" stroke="#ef9b3f" strokeWidth="2" opacity={grow ? 1 : 0} style={{ transition: "opacity 300ms ease 700ms" }}/>
        ))}
        {spec.xlabels.map((l, i) => ((spec.every ? i % spec.every === 0 : true) && l !== "—") ? (
          <text key={i} className="dd-axislbl" x={i * gap + gap / 2} y={H - 8} textAnchor="middle">{l}</text>
        ) : null)}
      </svg>
      {(spec.barLabel || spec.lineLabel) && (
        <div className="dd-legend">
          <span><span className="sw" style={{background:"#e0287f"}}/>{spec.barLabel}</span>
          {spec.lineLabel && <span><span className="swl" style={{background:"#ef9b3f"}}/>{spec.lineLabel}</span>}
        </div>
      )}
    </div>
  );
};

const DadosScene = () => {
  const [qi, setQi] = React.useState(-1);
  const [typed, setTyped] = React.useState("");
  const [phase, setPhase] = React.useState("ask"); // ask → think → answer
  const [grow, setGrow] = React.useState(false);
  const [reads, setReads] = React.useState(0);
  const [cycle, setCycle] = React.useState(0);
  const bodyRef = React.useRef(null);

  React.useEffect(() => {
    const T = []; const push = (fn, ms) => T.push(setTimeout(fn, ms));
    setTyped(""); setPhase("ask"); setGrow(false); setReads(0);
    if (qi < 0) { push(() => setQi(0), 15000); return () => T.forEach(clearTimeout); }
    const Q = DD_Q[qi];
    for (let i = 1; i <= Q.q.length; i++) push(() => setTyped(Q.q.slice(0, i)), 500 + i * 28);
    const qEnd = 500 + Q.q.length * 28;
    push(() => setPhase("think"), qEnd + 200);
    push(() => setPhase("answer"), qEnd + 1500);
    push(() => setGrow(true), qEnd + 2100);
    for (let i = 1; i <= Q.read.length; i++) push(() => setReads(i), qEnd + 3200 + i * 600);
    push(() => setQi((q) => (q + 1) % DD_Q.length), qEnd + 20000);
    return () => T.forEach(clearTimeout);
  }, [qi, cycle]);

  React.useEffect(() => { const b = bodyRef.current; if (b) b.scrollTop = b.scrollHeight; }, [typed, phase, grow, reads]);

  const Q = qi >= 0 ? DD_Q[qi] : null;
  return (
    <div className="dd-scene">
      <div className="dd-head">
        <div className="ico"><LandIcon name="database" size={20}/></div>
        <div><div className="t">Converse com os Dados</div><div className="s">Análise da BDGD por distribuidora</div></div>
        <div className="spacer"/>
        <div className="dd-badge"><LandIcon name="briefcase" size={12}/>Analisando: Enel SP</div>
        <div className="dd-base"><span className="dot"/>BDGDs Brasil · 2024</div>
      </div>

      <div className="dd-caption">
        <span className="dd-stepnum"><LandIcon name="sparkles" size={14}/></span>
        <span className="dd-steptext" key={qi}>Pergunte em linguagem natural — a SEL.IA consulta a BDGD e responde com gráfico</span>
      </div>
      <div className="dd-chips">
        <span className="dd-chip-hint"><LandIcon name="sparkles" size={11}/>Exemplos — pergunte o que quiser:</span>
        {DD_Q.map((q, i) => (
          <span key={i} className={"dd-chip" + (qi === i ? " on" : "")} onClick={() => setQi(i)}>
            {["Fluxo reverso do transformador", "Comprimento de rede", "DEC vs limite regulatório"][i]}
          </span>
        ))}
      </div>

      <div className="dd-body" ref={bodyRef}>
        {!Q ? (
          <div style={{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",textAlign:"center",color:"#9aa0a6",gap:10}}>
            <div style={{width:54,height:54,borderRadius:15,background:"rgba(217,25,101,0.10)",color:"#d91965",display:"flex",alignItems:"center",justifyContent:"center"}}><LandIcon name="database" size={26}/></div>
            <div style={{fontSize:15,fontWeight:700,color:"#102b4e"}}>Pergunte livremente sobre a BDGD</div>
            <div style={{fontSize:12.5}}>Os chips acima são só exemplos — a SEL.IA responde qualquer consulta com gráficos <b>ou tabelas</b>.</div>
          </div>
        ) : (
        <>
        <div className="dd-user">{typed}{phase === "ask" && typed.length < Q.q.length && <span className="caret"/>}</div>
        {phase !== "ask" && (
          <div className="dd-ai">
            <div className="dd-ai-ico"><LandIcon name="sparkles" size={15}/></div>
            <div className="dd-ai-body">
              {phase === "think" ? (
                <div className="dd-think"><i/><i/><i/></div>
              ) : (
                <>
                  <div className="dd-ai-text">{Q.a}</div>
                  {Q.table && (
                    <table className="dd-table"><thead><tr><th>Tipo</th><th>Comprimento</th></tr></thead><tbody>
                      {Q.table.map((r,i)=>(<tr key={i}><td>{r[0]}</td><td>{r[1]}</td></tr>))}
                    </tbody></table>
                  )}
                  <DDChart spec={Q.chart} grow={grow}/>
                  {reads > 0 && (
                    <>
                      <div className="dd-readtitle">Leitura rápida</div>
                      {Q.read.slice(0, reads).map((r, i) => (
                        <div className="dd-li" key={i}><span className="dot"/><span>{r}</span></div>
                      ))}
                      <div className="dd-sql"><LandIcon name="filesearch" size={11}/>Ver SQL utilizado (2 queries, 514ms)</div>
                    </>
                  )}
                </>
              )}
            </div>
          </div>
        )}
        </>
        )}
      </div>

      <div className="dd-input">
        <div className="dd-input-box"><span style={{flex:1}}>Faça sua consulta técnica sobre a BDGD…</span><span className="send"><LandIcon name="send" size={13}/></span></div>
      </div>
    </div>
  );
};
window.DadosScene = DadosScene;

const DadosEmbed = (props) => {
  const ref = React.useRef(null);
  const [box, setBox] = React.useState({ scale: 1, left: 0 });
  React.useEffect(() => {
    const el = ref.current; if (!el) return;
    const fit = () => { const w = el.clientWidth; const scale = w / 1200; setBox({ scale, left: Math.max(0, (w - 1200 * scale) / 2) }); };
    fit(); const ro = new ResizeObserver(fit); ro.observe(el); return () => ro.disconnect();
  }, []);
  return (
    <div ref={ref} style={{ width:"100%", height: 700 * box.scale, position:"relative", overflow:"hidden" }}>
      <div style={{ position:"absolute", top:0, left:box.left, width:1200, height:700, transform:`scale(${box.scale})`, transformOrigin:"top left" }}>
        <DadosScene {...props}/>
      </div>
    </div>
  );
};
window.DadosEmbed = DadosEmbed;
