/* SEL.IA — "Sentinela Regulatória" conceptual monitoring scene.
   Sources (left) → SEL.IA radar core (center) → e-mail alerts inbox (right).
   Conceptual (no real screenshots): shows the platform watching keywords,
   company citations, favorited-process updates across the sector and firing
   automatic e-mail alerts. */

const MON_SOURCES = [
  { id:"dou",    icon:"newspaper", name:"Diário Oficial (DOU)",   sub:"atos e publicações" },
  { id:"reuniao",icon:"mic",       name:"Reuniões da Diretoria",  sub:"transcrições ANEEL" },
  { id:"sei",    icon:"filesearch",name:"Processos SEI",          sub:"acompanhados ★" },
  { id:"sorteio",icon:"shuffle",   name:"Sorteios de relatoria",  sub:"distribuição de processos" },
  { id:"social", icon:"users",     name:"Participação social",    sub:"audiências e consultas públicas" },
  { id:"news",   icon:"mail",      name:"Newsletters do setor",   sub:"boletins e mídia" },
];

// each scenario: which source fires, the match shown, the resulting e-mail
const MON_SCENARIOS = [
  { src:0, chip:0, match:"“GERAÇÃO DISTRIBUÍDA”", icon:"newspaper", notify:true,
    from:"Stokhos IA · notificacao@selia", subj:"Destaque no DOU · Geração Distribuída", tag:"Palavra-chave" },
  { src:1, chip:2, match:"“ENEL SP” citada", icon:"mic",
    from:"Stokhos IA · notificacao@selia", subj:"ENEL SP citada em reunião da Diretoria", tag:"Empresa citada" },
  { src:2, chip:3, match:"Processo 48500…72 atualizado", icon:"star", notify:true,
    from:"Stokhos IA · notificacao@selia", subj:"Um processo que você acompanha foi atualizado", tag:"Favorito ★", fav:true },
  { src:3, chip:-1, match:"Relatoria → Dir. Agnes", icon:"shuffle",
    from:"Stokhos IA · notificacao@selia", subj:"Novo sorteio de relatoria de processo", tag:"Sorteio" },
  { src:4, chip:-1, match:"Nova consulta pública", icon:"users", notify:true,
    from:"Stokhos IA · notificacao@selia", subj:"Consulta pública aberta sobre seu tema", tag:"Part. social" },
  { src:5, chip:2, match:"Menção em newsletter", icon:"mail",
    from:"Stokhos IA · notificacao@selia", subj:"Sua empresa foi citada em uma newsletter", tag:"Menção" },
];

const MON_WATCH = [
  { label:"GERAÇÃO DISTRIBUÍDA", icon:"sparkles" },
  { label:"REN 1.000", icon:"book" },
  { label:"ENEL SP", icon:"briefcase" },
  { label:"★ 48500…72", icon:"star", fav:true },
];

// fixed-scene geometry
const SRC_X = 48, SRC_W = 250, SRC_H = 58, SRC_GAP = 78;
const SRC_RIGHT = SRC_X + SRC_W;              // 298
const CORE_X = 592;
const CORE_LEFT = 510, CORE_RIGHT = 679;
const INBOX_X = 900;
const TITLE_OFF = 84;        // vertical space the internal title block occupies
const sceneHeightFor = (hideTitle) => 640 - (hideTitle ? TITLE_OFF : 0);

const MonitorScene = ({
  eyebrow = "Vigilância regulatória contínua",
  title = "A SEL.IA fica de olho por você.",
  hideTitle = false,
}) => {
  const OFF = hideTitle ? TITLE_OFF : 0;
  const SCENE_H = 640 - OFF;
  const SRC_TOP0 = 150 - OFF;
  const CORE_Y = 330 - OFF;
  const CAP_TOP = 112 - OFF;
  const WATCH_TOP = 488 - OFF;
  const INBOX_TOP = 146 - OFF;
  const INBOX_PT = { x: INBOX_X, y: 208 - OFF };
  const srcCenterY = (i) => SRC_TOP0 + i * SRC_GAP + SRC_H / 2;

  const [active, setActive] = React.useState(-1);
  const [litChip, setLitChip] = React.useState(-1);
  const [ping, setPing] = React.useState(false);
  const [packet, setPacket] = React.useState({ x: SRC_RIGHT, y: 330 - OFF, show: false, dur: 0 });
  const [emails, setEmails] = React.useState([]);
  const [unread, setUnread] = React.useState(0);
  const [bump, setBump] = React.useState(false);
  const [sent, setSent] = React.useState(false);
  const timers = React.useRef([]);
  const emailKey = React.useRef(0);

  React.useEffect(() => {
    const T = timers.current;
    const push = (fn, ms) => T.push(setTimeout(fn, ms));
    let idx = 0;

    const run = () => {
      const sc = MON_SCENARIOS[idx];
      const cy = srcCenterY(sc.src);

      // 1. detect on source
      setActive(sc.src);
      setLitChip(sc.chip);
      // 2. packet appears at source, travels to core
      push(() => setPacket({ x: SRC_RIGHT, y: cy, show: true, dur: 0 }), 320);
      push(() => setPacket({ x: CORE_X, y: CORE_Y, show: true, dur: 720 }), 400);
      // 3. core processes (ping), packet travels to inbox
      push(() => { setPing(true); }, 1150);
      push(() => setPing(false), 1750);
      push(() => setPacket({ x: INBOX_PT.x, y: INBOX_PT.y, show: true, dur: 700 }), 1300);
      if (sc.notify) {
        push(() => setSent(true), 1350);
        push(() => setSent(false), 2700);
      }
      // 4. e-mail lands
      push(() => {
        setPacket((p) => ({ ...p, show: false }));
        emailKey.current += 1;
        setEmails((list) => [{ k: emailKey.current, ...sc }, ...list].slice(0, 4));
        setUnread((u) => u + 1);
        setBump(true);
      }, 2050);
      push(() => setBump(false), 2520);
      // 5. clear highlight, advance — reset the inbox once a full cycle completes
      push(() => { setActive(-1); setLitChip(-1); setSent(false); }, 3300);
      push(() => {
        const next = (idx + 1) % MON_SCENARIOS.length;
        if (next === 0) { setEmails([]); setUnread(0); }   // full loop done → restart clean
        idx = next; run();
      }, 3900);
    };

    push(run, 700);
    return () => { T.forEach(clearTimeout); timers.current = []; };
  }, []);

  return (
    <div className="mon-scene" style={{ height: SCENE_H }}>
      {!hideTitle && (
        <>
          <div className="mon-eyebrow"><LandIcon name="eye" size={13}/>{eyebrow}</div>
          <div className="mon-title">{title}</div>
        </>
      )}

      <div className="mon-cap left" style={{ top: CAP_TOP }}>Fontes monitoradas</div>
      <div className="mon-cap right" style={{ top: CAP_TOP }}>Seus alertas por e-mail</div>

      {/* connectors */}
      <svg className="mon-links" viewBox={`0 0 1180 ${SCENE_H}`} preserveAspectRatio="none">
        <defs>
          <linearGradient id="monGrad" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0" stopColor="#ff6f9d"/>
            <stop offset="1" stopColor="#d91965"/>
          </linearGradient>
        </defs>
        {MON_SOURCES.map((s, i) => (
          <path key={i}
            className={"mon-link" + (active === i ? " hot" : "")}
            d={`M${SRC_RIGHT},${srcCenterY(i)} C ${SRC_RIGHT + 90},${srcCenterY(i)} ${CORE_LEFT - 70},${CORE_Y} ${CORE_LEFT},${CORE_Y}`}
          />
        ))}
        <path
          className={"mon-link" + (packet.show && packet.x > CORE_X ? " hot" : "")}
          d={`M${CORE_RIGHT},${CORE_Y - 10} C ${CORE_RIGHT + 80},${CORE_Y - 40} ${INBOX_PT.x - 90},${INBOX_PT.y} ${INBOX_PT.x},${INBOX_PT.y}`}
        />
      </svg>

      {/* sources */}
      {MON_SOURCES.map((s, i) => (
        <div key={s.id} className={"mon-source" + (active === i ? " active" : "")}
             style={{ top: SRC_TOP0 + i * SRC_GAP }}>
          <div className="ms-ico"><LandIcon name={s.icon} size={17}/></div>
          <div className="ms-body">
            <div className="ms-name">{s.name}</div>
            <div className="ms-sub">{s.sub}</div>
          </div>
          {active === i && (
            <div className="mon-match"><span className="dotpulse"/>{MON_SCENARIOS[idx_for(i)].match}</div>
          )}
        </div>
      ))}

      {/* center radar core */}
      <div className="mon-core" style={{ top: CORE_Y }}>
        <div className="mon-ring"/><div className="mon-ring r2"/><div className="mon-ring r3"/>
        <div className="mon-pulse"/><div className="mon-pulse d2"/>
        <div className="mon-sweep"/>
        <div className={"mon-core-disc" + (ping ? " ping" : "")}>
          <div className="mon-core-mark">SEL<span className="ia">.IA</span></div>
          <div className="mon-core-sub">monitorando 24/7</div>
        </div>
      </div>

      {/* watched items */}
      <div className="mon-watch" style={{ top: WATCH_TOP }}>
        <div className="mon-watch-label"><LandIcon name="eye" size={11}/>Acompanhando para você</div>
        <div className="mon-watch-chips">
          {MON_WATCH.map((w, i) => (
            <span key={i} className={"mon-chip" + (w.fav ? " fav" : "") + (litChip === i ? " lit" : "")}>
              <LandIcon name={w.icon} size={11}/>{w.label}
            </span>
          ))}
        </div>
      </div>

      {/* travelling packet */}
      <div className={"mon-packet" + (packet.show ? " show" : "")}
           style={{ left: packet.x, top: packet.y,
                    transition: `left ${packet.dur}ms cubic-bezier(0.5,0,0.2,1), top ${packet.dur}ms cubic-bezier(0.5,0,0.2,1), opacity 200ms ease` }}/>

      {/* e-mail dispatched confirmation */}
      <div className={"mon-sent-toast" + (sent ? " show" : "")}>
        <LandIcon name="send" size={12}/>E-mail enviado
      </div>

      {/* inbox */}
      <div className="mon-inbox" style={{ top: INBOX_TOP }}>
        <div className="mon-inbox-head">
          <div className="ih-ico">
            <LandIcon name="bell" size={16}/>
            {unread > 0 && <span className={"mon-bell-badge" + (bump ? " bump" : "")}>{unread}</span>}
          </div>
          <div>
            <div className="ih-title">Caixa de entrada</div>
            <div className="ih-sub">alertas automáticos da SEL.IA</div>
          </div>
        </div>
        <div className="mon-inbox-body">
          {emails.length === 0 && <div className="mon-inbox-empty">Aguardando eventos do setor…</div>}
          {emails.map((e) => (
            <div key={e.k} className="mon-email unread">
              <div className="me-ico"><LandIcon name={e.icon} size={14}/></div>
              <div className="me-body">
                <div className="me-from">{e.from}</div>
                <div className="me-subj">{e.subj}</div>
                <span className={"me-tag" + (e.fav ? " fav" : "")}><LandIcon name={e.fav ? "star" : "bell"} size={8}/>{e.tag}</span>
              </div>
              <div className="me-unreaddot"/>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// helper: the active source index maps 1:1 to the scenario currently firing;
// find the scenario whose src === i (sources are unique per scenario here)
function idx_for(i) {
  const n = MON_SCENARIOS.findIndex((s) => s.src === i);
  return n < 0 ? 0 : n;
}

window.MonitorScene = MonitorScene;

/* Responsive wrapper for the landing: scales the fixed 1180×640 scene to the
   container width (never upscales past native), centered, no page overflow. */
const MonitorEmbed = (props) => {
  const ref = React.useRef(null);
  const sceneH = sceneHeightFor(props.hideTitle);
  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 / 1180;            // fill the container width (may upscale)
      setBox({ scale, left: Math.max(0, (w - 1180 * scale) / 2) });
    };
    fit();
    const ro = new ResizeObserver(fit);
    ro.observe(el);
    return () => ro.disconnect();
  }, []);
  return (
    <div ref={ref} style={{ width: "100%", height: sceneH * box.scale, position: "relative", overflow: "hidden" }}>
      <div style={{ position: "absolute", top: 0, left: box.left, width: 1180, height: sceneH, transform: `scale(${box.scale})`, transformOrigin: "top left" }}>
        <MonitorScene {...props}/>
      </div>
    </div>
  );
};
window.MonitorEmbed = MonitorEmbed;
