// ===== Replay · pós-pregão · cronologia + análise =====

const REPLAY_EVENTS = [
  { t:  0, ts: "14:32:00", who: "sistema",  msg: "Pregão aberto · 4 licitantes habilitados", tag: "info" },
  { t:  18, ts: "14:32:18", who: "InfraSys",  msg: "lance inicial R$ 320.000", tag: "lance" },
  { t:  22, ts: "14:32:22", who: "Souza Tech", msg: "lance R$ 318.500", tag: "lance" },
  { t:  25, ts: "14:32:25", who: "Pleita 🤖", msg: "robô cobre · lance R$ 317.000", tag: "pleita" },
  { t:  28, ts: "14:32:28", who: "Bytenet",  msg: "lance R$ 316.500", tag: "lance" },
  { t:  32, ts: "14:32:32", who: "Souza Tech", msg: "lance R$ 315.000", tag: "lance" },
  { t:  35, ts: "14:32:35", who: "Pleita 🤖", msg: "robô cobre · lance R$ 314.000", tag: "pleita" },
  { t:  39, ts: "14:32:39", who: "InfraSys",  msg: "desistiu · margem mínima atingida", tag: "drop" },
  { t:  41, ts: "14:32:41", who: "Bytenet",  msg: "lance R$ 313.500", tag: "lance" },
  { t:  44, ts: "14:32:44", who: "Pleita 🤖", msg: "robô cobre · lance R$ 312.800", tag: "pleita" },
  { t:  48, ts: "14:32:48", who: "Bytenet",  msg: "desistiu · sem margem", tag: "drop" },
  { t:  51, ts: "14:32:51", who: "Souza Tech", msg: "lance R$ 312.500", tag: "lance" },
  { t:  54, ts: "14:32:54", who: "Pleita 🤖", msg: "robô cobre · lance R$ 312.000", tag: "pleita" },
  { t:  58, ts: "14:32:58", who: "Souza Tech", msg: "desistiu · atingiu seu próprio piso", tag: "drop" },
  { t:  62, ts: "14:33:02", who: "sistema",  msg: "Pregão encerrado · arrematante: Souza Engenharia", tag: "win" },
  { t:  90, ts: "14:33:30", who: "sistema",  msg: "Aceitação por R$ 312.000 confirmada pelo pregoeiro", tag: "info" },
  { t: 180, ts: "14:35:00", who: "sistema",  msg: "Fase de habilitação iniciada — você tem 24h", tag: "info" },
  { t: 720, ts: "14:44:00", who: "Marcos",   msg: "Habilitação enviada · 6 documentos do cofre", tag: "user" },
  { t:1440, ts: "14:56:00", who: "sistema",  msg: "Habilitação aprovada · adjudicação publicada", tag: "win" },
];

const TAGS = {
  info:   { dot: "#9B9B9B", bg: "bg-surface-2" },
  lance:  { dot: "#6B6B6B", bg: "bg-surface-2" },
  pleita: { dot: "#9FE870", bg: "bg-pleita-lime/15" },
  drop:   { dot: "#DC2626", bg: "bg-verdict-stop/10" },
  win:    { dot: "#16A34A", bg: "bg-verdict-go/10" },
  user:   { dot: "#3B82F6", bg: "bg-pleita-info/10" },
};

function ReplayChart({ playT }) {
  // Mini step chart of bids; reveal points up to playT
  const W = 800, H = 280, padL = 60, padR = 60, padT = 20, padB = 36;
  const minP = 311000, maxP = 322000;
  const minT = 0,      maxT = 65;
  const xOf = (t) => padL + ((t - minT) / (maxT - minT)) * (W - padL - padR);
  const yOf = (p) => padT + ((maxP - p) / (maxP - minP)) * (H - padT - padB);

  const series = {
    infra:   { c: "#8693B5", pts: [{ t:18, p:320000 }] },
    souza:   { c: "#A6B2D4", pts: [{ t:22, p:318500 }, { t:32, p:315000 }, { t:51, p:312500 }] },
    bytenet: { c: "#6C7AA1", pts: [{ t:28, p:316500 }, { t:41, p:313500 }] },
    pleita:  { c: "#9FE870", pts: [{ t:25, p:317000 }, { t:35, p:314000 }, { t:44, p:312800 }, { t:54, p:312000 }] },
  };

  return (
    <svg viewBox={`0 0 ${W} ${H}`} className="w-full h-auto block">
      {/* y grid */}
      {[312000, 315000, 318000, 321000].map((p) => (
        <g key={p}>
          <line x1={padL} y1={yOf(p)} x2={W - padR} y2={yOf(p)} stroke="rgb(var(--pleita-line))" strokeDasharray="3 6" />
          <text x={padL - 8} y={yOf(p) + 4} textAnchor="end" className="pl-num" fontSize="11" fill="rgb(var(--pleita-stone-2))">R$ {(p / 1000).toFixed(0)}k</text>
        </g>
      ))}
      {/* x ticks */}
      {[10, 20, 30, 40, 50, 60].map((t) => (
        <text key={t} x={xOf(t)} y={H - 8} textAnchor="middle" className="pl-num" fontSize="10" fill="rgb(var(--pleita-stone-2))">{t}s</text>
      ))}
      {/* playhead vertical */}
      <line x1={xOf(playT)} y1={padT} x2={xOf(playT)} y2={H - padB} stroke="rgb(var(--pleita-lime))" strokeWidth="1.5" />
      <circle cx={xOf(playT)} cy={padT} r="4" fill="rgb(var(--pleita-lime))" />

      {/* bidder series */}
      {Object.entries(series).map(([k, s]) => {
        const visible = s.pts.filter((pt) => pt.t <= playT);
        if (visible.length === 0) return null;
        let d = `M ${xOf(visible[0].t)} ${yOf(visible[0].p)}`;
        for (let i = 1; i < visible.length; i++) {
          d += ` L ${xOf(visible[i].t)} ${yOf(visible[i - 1].p)} L ${xOf(visible[i].t)} ${yOf(visible[i].p)}`;
        }
        return (
          <g key={k}>
            <path d={d} stroke={s.c} strokeWidth={k === "pleita" ? "3" : "1.8"} fill="none" strokeLinejoin="round" />
            {visible.map((pt, i) => (
              <circle key={i} cx={xOf(pt.t)} cy={yOf(pt.p)} r={k === "pleita" ? 5 : 3.5} fill={s.c} stroke="rgb(var(--surface-card))" strokeWidth="1.5" />
            ))}
          </g>
        );
      })}
    </svg>
  );
}

function ScreenReplay({ beginnerMode, setBeginnerMode }) {
  const [playT, setPlayT] = React.useState(62);
  const [playing, setPlaying] = React.useState(false);
  const [navOpen, setNavOpen] = React.useState(false);
  const maxT = 65;

  React.useEffect(() => {
    if (!playing) return;
    const i = setInterval(() => {
      setPlayT((t) => (t >= maxT ? (setPlaying(false), 0) : t + 0.5));
    }, 60);
    return () => clearInterval(i);
  }, [playing]);

  const visibleEvents = REPLAY_EVENTS.filter((e) => e.t <= playT + 1);

  return (
    <div className="h-full flex bg-pleita-paper">
      <Sidebar beginnerMode={beginnerMode} setBeginnerMode={setBeginnerMode} active="pos" mobileOpen={navOpen} onCloseMobile={() => setNavOpen(false)} />
      <div className="flex-1 flex flex-col min-w-0">
        <Topbar crumb={["Resultados", "Pregão 047/2026", "Replay"]} onOpenMobileNav={() => setNavOpen(true)} />
        <main className="flex-1 overflow-y-auto scrollbar-pl">
          <div className="max-w-7xl mx-auto px-4 md:px-8 py-8">
            <header className="mb-8 flex items-start justify-between flex-wrap gap-4">
              <div>
                <div className="pl-num text-xs uppercase tracking-[0.18em] text-pleita-stone-2">Replay · Pregão Eletrônico 047/2026</div>
                <h1 className="font-display text-3xl md:text-4xl text-pleita-ink mt-1 leading-tight">Como você venceu Campinas<span className="text-pleita-lime">.</span></h1>
                <p className="text-sm text-pleita-stone mt-2 max-w-2xl leading-relaxed">23 abr 2026 · 1h28min de pregão · 4 licitantes · arrematada por R$ 312.000 (−74% do referencial).</p>
              </div>
              <div className="rounded-2xl bg-pleita-ink text-pleita-paper p-5 min-w-[260px]">
                <div className="pl-num text-[10px] uppercase tracking-wider text-pleita-paper/60">Resultado</div>
                <div className="font-display text-3xl mt-1">R$ 312.000</div>
                <div className="pl-num text-xs text-pleita-paper/70 mt-1">margem 18,2% · economia 25%</div>
              </div>
            </header>

            <section className="grid lg:grid-cols-3 gap-6">
              <div className="lg:col-span-2 rounded-2xl bg-surface-card border border-pleita-line overflow-hidden">
                <div className="px-6 py-4 border-b border-pleita-line flex items-center justify-between">
                  <div>
                    <div className="pl-num text-[10px] uppercase tracking-wider text-pleita-stone-2">Disputa de lances</div>
                    <div className="font-display text-lg text-pleita-ink">Os primeiros 65 segundos</div>
                  </div>
                  <div className="flex items-center gap-2">
                    <button onClick={() => setPlaying((p) => !p)} className="size-9 rounded-full bg-pleita-ink text-pleita-paper grid place-items-center">
                      {playing ? "❚❚" : "▶"}
                    </button>
                    <span className="pl-num text-xs text-pleita-stone-2">{playT.toFixed(1)}s / {maxT}s</span>
                  </div>
                </div>
                <div className="p-6">
                  <ReplayChart playT={playT} />
                  <input
                    type="range" min={0} max={maxT} step={0.1} value={playT}
                    onChange={(e) => { setPlayT(+e.target.value); setPlaying(false); }}
                    className="w-full mt-3 accent-pleita-ink"
                  />
                </div>
              </div>
              <div className="rounded-2xl bg-surface-card border border-pleita-line overflow-hidden">
                <div className="px-5 py-3 border-b border-pleita-line">
                  <div className="pl-num text-[10px] uppercase tracking-wider text-pleita-stone-2">Cronologia</div>
                  <div className="font-display text-base text-pleita-ink mt-1">{visibleEvents.length} eventos</div>
                </div>
                <div className="max-h-[500px] overflow-y-auto scrollbar-pl">
                  {visibleEvents.slice(-20).map((e, i) => {
                    const m = TAGS[e.tag];
                    return (
                      <div key={i} className="flex items-start gap-3 px-5 py-3 border-b border-pleita-line">
                        <div className="size-2 rounded-full mt-1.5 shrink-0" style={{ background: m.dot }} />
                        <div className="flex-1 min-w-0">
                          <div className="pl-num text-[11px] text-pleita-stone-2 flex items-center gap-2">
                            <span>{e.ts}</span><span>·</span><span className="text-pleita-ink">{e.who}</span>
                          </div>
                          <div className="text-sm text-pleita-ink leading-snug mt-0.5">{e.msg}</div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            </section>

            <section className="mt-8 grid lg:grid-cols-3 gap-6">
              <div className="lg:col-span-2 rounded-2xl bg-surface-card border border-pleita-line p-6">
                <div className="pl-num text-[10px] uppercase tracking-wider text-pleita-stone-2 mb-3">Lições do pregão</div>
                <h3 className="font-display text-xl text-pleita-ink mb-4">O que o Analista aprendeu</h3>
                <ul className="space-y-3 text-sm">
                  {[
                    ["Você cobriu Souza Tech 3 vezes", "padrão observado: ela tem piso por volta de R$ 312.500. Da próxima vez, considere começar 0,5% acima desse piso."],
                    ["InfraSys desistiu rápido", "consistente com o histórico — InfraSys nunca disputou abaixo de R$ 317k em pregões parecidos. Use isso a seu favor."],
                    ["Margem 18,2% × meta 15%", "você fechou acima da margem alvo. Bom sinal — não sangrou."],
                    ["Habilitação em 12 min", "todos os 6 documentos estavam válidos no Cofre. Continue assim."],
                  ].map(([h, d], i) => (
                    <li key={i} className="rounded-md border border-pleita-line p-4">
                      <div className="text-sm text-pleita-ink font-medium">{h}</div>
                      <div className="pl-num text-[11px] text-pleita-stone-2 mt-1 leading-relaxed">{d}</div>
                    </li>
                  ))}
                </ul>
              </div>

              <div className="space-y-4">
                <div className="rounded-2xl bg-pleita-lime/10 border border-pleita-lime/40 p-5">
                  <div className="text-pleita-lime text-2xl">🎓</div>
                  <div className="font-display text-base text-pleita-ink mt-1">Próximos passos</div>
                  <ol className="text-xs text-pleita-stone leading-relaxed mt-3 space-y-2 pl-num">
                    <li>1. Aguardar publicação no DOU (~3 dias úteis)</li>
                    <li>2. Assinar contrato (até 14 dias)</li>
                    <li>3. Entrega prevista pra 18 jul · 60 dias</li>
                    <li>4. 1ª nota fiscal: emite na entrega</li>
                  </ol>
                </div>
                <div className="rounded-2xl bg-surface-card border border-pleita-line p-5">
                  <div className="pl-num text-[10px] uppercase tracking-wider text-pleita-stone-2 mb-2">Exportar</div>
                  <div className="flex flex-col gap-2">
                    {["Replay completo (vídeo)", "Cronologia em CSV", "Ata oficial (PDF)", "Relatório financeiro"].map((n) => (
                      <button key={n} className="flex items-center justify-between p-3 rounded-md border border-pleita-line hover:bg-surface-2 text-sm text-pleita-ink">
                        <span>{n}</span><Icons.Download className="size-4 text-pleita-stone-2" />
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            </section>
          </div>
        </main>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenReplay });
