// Agent Builder — Hero with a live agent-execution console
// (useState/useRef/useEffect provided globally by primitives.jsx)

const RUN_STEPS = [
  { ic: "doc",   label: "Consultando contrato #4471", sys: "ERP" },
  { ic: "scan",  label: "Analisando cláusulas de rescisão", sys: "Documentos" },
  { ic: "db",    label: "Atualizando status no CRM", sys: "Salesforce" },
  { ic: "mail",  label: "Gerando comunicação ao cliente", sys: "E-mail" },
  { ic: "shield",label: "Registrando ação na auditoria", sys: "Logs" },
];

function RunIcon({ name }) {
  const p = {
    doc:   <path d="M6 2.5h6l4 4v11a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V3.5a1 1 0 0 1 1-1Z M12 2.5V7h4 M7.5 11h7 M7.5 14h7" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" fill="none"/>,
    scan:  <g stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinecap="round"><circle cx="9" cy="9" r="5"/><path d="m13 13 4 4"/></g>,
    db:    <g stroke="currentColor" strokeWidth="1.4" fill="none"><ellipse cx="10" cy="5" rx="6" ry="2.4"/><path d="M4 5v10c0 1.3 2.7 2.4 6 2.4s6-1.1 6-2.4V5"/><path d="M4 10c0 1.3 2.7 2.4 6 2.4s6-1.1 6-2.4"/></g>,
    mail:  <g stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinejoin="round"><rect x="3" y="5" width="14" height="10" rx="1.6"/><path d="m3.5 6 6.5 5 6.5-5"/></g>,
    shield:<path d="M10 2.5 4 5v4.5c0 4 2.6 6.7 6 8 3.4-1.3 6-4 6-8V5l-6-2.5Z M7.6 9.8l1.7 1.7 3.3-3.4" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round"/>,
  }[name];
  return <svg width="18" height="18" viewBox="0 0 20 20">{p}</svg>;
}

function AgentConsole() {
  const [cur, setCur] = useState(-1); // index currently running; < cur are done
  const [elapsed, setElapsed] = useState(0);

  useEffect(() => {
    let alive = true;
    let timers = [];
    const run = () => {
      setCur(-1);
      setElapsed(0);
      RUN_STEPS.forEach((_, i) => {
        timers.push(setTimeout(() => { if (alive) setCur(i); }, 700 + i * 900));
      });
      // finish
      timers.push(setTimeout(() => { if (alive) setCur(RUN_STEPS.length); }, 700 + RUN_STEPS.length * 900));
      // loop
      timers.push(setTimeout(() => { if (alive) run(); }, 700 + RUN_STEPS.length * 900 + 3200));
    };
    run();
    const tick = setInterval(() => { if (alive) setElapsed((e) => e + 0.1); }, 100);
    return () => { alive = false; timers.forEach(clearTimeout); clearInterval(tick); };
  }, []);

  const done = cur >= RUN_STEPS.length;

  return (
    <div className="agentcon">
      <div className="ac-head">
        <span className="ac-dot">
          <img src="assets/logo-mark-white.svg" alt="" style={{ width: 18, height: 18 }} />
        </span>
        <div>
          <div className="ac-title">Agente · Pós-venda</div>
          <div className="ac-meta">{done ? "execução concluída" : "executando"}</div>
        </div>
        <span className="ac-task">run #2f9c · {elapsed.toFixed(1)}s</span>
      </div>

      <div className="ac-prompt">
        <span className="who">Gatilho</span>
        <span className="txt">Cliente solicitou cancelamento do contrato #4471 — analise e processe conforme a política.</span>
      </div>

      <div className="ac-steps">
        {RUN_STEPS.map((s, i) => {
          const state = i < cur || done ? "done" : i === cur ? "run" : "pending";
          return (
            <div key={i} className={"ac-step " + state}>
              <span className="ac-ic"><RunIcon name={s.ic} /></span>
              <span className="ac-label">{s.label}</span>
              <span className="ac-sys">{s.sys}</span>
              <span className="ac-state">
                {state === "run" && <span className="ac-spin"></span>}
                {state === "done" && (
                  <svg width="16" height="16" viewBox="0 0 16 16"><path d="M3.5 8.5 6.5 11.5 12.5 4.5" stroke="#296aed" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
                )}
              </span>
            </div>
          );
        })}
      </div>

      <div className="ac-foot">
        {done
          ? <span className="ok"><svg width="15" height="15" viewBox="0 0 16 16"><circle cx="8" cy="8" r="7.2" fill="rgba(41,106,237,.16)"/><path d="M4.6 8.2 6.9 10.5 11.4 5.6" stroke="#296aed" strokeWidth="1.7" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg> Processo concluído — 5 ações executadas</span>
          : <span>Orquestrando ações entre sistemas corporativos…</span>}
        <span className="spacer">100% auditável</span>
      </div>
    </div>
  );
}

function Hero() {
  return (
    <section className="hero" id="top">
      <div className="hero-bg" style={{ backgroundImage: "url(assets/bg/hero_bg02.jpg)" }}></div>
      <div className="container hero-grid">
        <div className="hero-copy">
          <h1 className="title t-hero" style={{ opacity: 1 }}>Construa sua força de trabalho digital com <span style={{ color: "var(--ab-primary)" }}>agilidade, segurança e observabilidade.</span></h1>
          <Reveal delay={220}>
            <p className="hero-sub">Crie, publique e gerencie agentes de IA conectados aos sistemas, documentos e processos da sua empresa. <strong>Sem infraestrutura complexa, sem lock-in e com governança enterprise desde o primeiro dia.</strong></p>
          </Reveal>
          <Reveal delay={300}>
            <div className="hero-cta">
              <CTAButton onClick={() => { const el = document.getElementById("agendar"); if (el) window.scrollTo({ top: el.offsetTop - 76, behavior: "smooth" }); }}>solicitar demonstração</CTAButton>
              <button className="ghost-cta" onClick={() => { const el = document.getElementById("producao"); if (el) window.scrollTo({ top: el.offsetTop - 76, behavior: "smooth" }); }}>
                quero conhecer o Agent Builder
                <span className="gc-arrow"><svg width="13" height="13" viewBox="0 0 16 16"><path d="M3 8h9M8 4l4 4-4 4" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg></span>
              </button>
            </div>
          </Reveal>
          <Reveal delay={380}>
            <div className="hero-tags">
              <span className="htag">Governança enterprise</span>
              <span className="htag">Zero lock-in</span>
              <span className="htag">Open source</span>
            </div>
          </Reveal>
        </div>
        <Reveal delay={200}><AgentConsole /></Reveal>
      </div>
    </section>
  );
}

Object.assign(window, { Hero, AgentConsole });
