// ===== CENA 5 (28–37s) — PREGÃO AO VIVO · CENA 6 (37–42s) — VITÓRIA =====

// ---------- CENA 5 ----------

const BIDDERS = {
  infra:   { id: "infra",   name: "InfraSys",       cnpj: "32.184.991/0001-04", color: "#8693B5",  start: 320000 },
  souza:   { id: "souza",   name: "Souza Tech",     cnpj: "11.482.770/0001-29", color: "#A6B2D4",  start: 318500 },
  bytenet: { id: "bytenet", name: "Bytenet",        cnpj: "08.290.341/0001-73", color: "#6C7AA1",  start: 316500 },
  pleita:  { id: "pleita",  name: "Souza Engenharia (Pleita)", cnpj: "32.948.117/0001-50", color: C.lime, start: 317000, isUs: true },
};

const PREGAO_EVENTS = [
  { t: 0.4, who: "infra",   price: 320000 },
  { t: 0.9, who: "souza",   price: 318500 },
  { t: 1.4, who: "pleita",  price: 317000 },
  { t: 1.9, who: "bytenet", price: 316500 },
  { t: 2.4, who: "souza",   price: 315000 },
  { t: 2.9, who: "pleita",  price: 314000 },
  { t: 3.4, who: "infra",   action: "drop" },
  { t: 3.9, who: "bytenet", price: 313500 },
  { t: 4.4, who: "pleita",  price: 312800 },
  { t: 4.9, who: "bytenet", action: "drop" },
  { t: 5.4, who: "souza",   price: 312500 },
  { t: 5.9, who: "pleita",  price: 312000 },
  { t: 6.4, who: "souza",   action: "drop" },
  { t: 7.0, who: "pleita",  action: "win" },
];

const fmtPrice = (n) => "R$ " + n.toLocaleString("pt-BR");

function SceneAuction() {
  const { localTime, duration } = useSprite();
  const exitT = Math.max(0, duration - 0.5);
  const exitOpacity = localTime > exitT ? 1 - (localTime - exitT) / 0.5 : 1;

  // Compute bidder state at localTime
  const fired = PREGAO_EVENTS.filter((e) => e.t <= localTime);
  const lastFireT = fired.length ? fired[fired.length - 1].t : 0;

  const state = {};
  Object.keys(BIDDERS).forEach((k) => state[k] = { id: k, price: BIDDERS[k].start, history: [], status: "active", lastUpdate: -10 });
  fired.forEach((e) => {
    if (e.action === "drop") {
      state[e.who].status = "dropped";
      state[e.who].lastUpdate = e.t;
    } else if (e.action === "win") {
      state[e.who].status = "winner";
      state[e.who].lastUpdate = e.t;
    } else if (e.price != null) {
      state[e.who].price = e.price;
      state[e.who].history.push({ t: e.t, p: e.price });
      state[e.who].lastUpdate = e.t;
    }
  });

  // Sorted ranking: active first by lowest price, then dropped
  const ranked = Object.values(state).sort((a, b) => {
    const aActive = a.status !== "dropped";
    const bActive = b.status !== "dropped";
    if (aActive !== bActive) return bActive - aActive;
    return a.price - b.price;
  });

  // Tick clock: starts at 14:32:18 + localTime*4
  const realSec = 14 * 3600 + 32 * 60 + 18 + Math.floor(localTime * 4.2);
  const hh = String(Math.floor(realSec / 3600)).padStart(2, "0");
  const mm = String(Math.floor((realSec % 3600) / 60)).padStart(2, "0");
  const ss = String(realSec % 60).padStart(2, "0");

  // Chart math
  const CHART_X = 96;
  const CHART_Y = 280;
  const CHART_W = 940;
  const CHART_H = 520;
  const T_MIN = 0;
  const T_MAX = 7.5;
  const P_MIN = 311000;
  const P_MAX = 322000;
  const xOf = (t) => CHART_X + 60 + ((Math.min(t, localTime) - T_MIN) / (T_MAX - T_MIN)) * (CHART_W - 60);
  const yOf = (p) => CHART_Y + 60 + ((P_MAX - p) / (P_MAX - P_MIN)) * (CHART_H - 100);

  // Build SVG path for each bidder
  const buildPath = (history, start) => {
    if (!history.length) return "";
    const pts = [{ t: 0, p: start }, ...history];
    // Step path (price holds until next bid)
    let d = `M ${xOf(pts[0].t)} ${yOf(pts[0].p)}`;
    for (let i = 1; i < pts.length; i++) {
      d += ` L ${xOf(pts[i].t)} ${yOf(pts[i - 1].p)}`;
      d += ` L ${xOf(pts[i].t)} ${yOf(pts[i].p)}`;
    }
    // Extend to current time
    const last = pts[pts.length - 1];
    const endT = state[history[0] ? Object.keys(state).find((k) => state[k].history === history) : null]?.status === "dropped"
      ? state[Object.keys(state).find((k) => state[k].history === history)].lastUpdate
      : Math.min(localTime, T_MAX);
    d += ` L ${xOf(endT)} ${yOf(last.p)}`;
    return d;
  };

  return (
    <div style={{
      position: "absolute", inset: 0,
      background: `linear-gradient(180deg, #061029 0%, ${C.ink} 100%)`,
      color: C.paper, opacity: exitOpacity, overflow: "hidden",
    }}>
      {/* Grid lines decorative */}
      <div style={{
        position: "absolute", inset: 0,
        backgroundImage: `linear-gradient(0deg, ${C.lineDk}1a 1px, transparent 1px)`,
        backgroundSize: "100% 40px", pointerEvents: "none",
      }} />

      {/* Header */}
      <div style={{ position: "absolute", left: 96, top: 100, right: 96, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 14, padding: "8px 16px", borderRadius: 999, background: `${C.stop}22`, border: `1px solid ${C.stop}55` }}>
            <span style={{ width: 10, height: 10, borderRadius: 999, background: C.stop, animation: "blinkLive 900ms infinite ease-in-out", boxShadow: `0 0 12px ${C.stop}` }} />
            <span style={{ fontFamily: F.mono, fontSize: 13, letterSpacing: "0.22em", textTransform: "uppercase", color: C.stop }}>Pregão ao vivo</span>
          </div>
          <div style={{ fontFamily: F.display, fontSize: 56, lineHeight: 1, marginTop: 18, letterSpacing: "-0.02em" }}>
            Pregão Eletrônico nº 047/2026<span style={{ color: C.lime }}>.</span>
          </div>
          <div style={{ fontFamily: F.sans, fontSize: 20, color: "#A8B2CC", marginTop: 8 }}>
            Pref. Campinas · Equipamentos de TI · valor de referência R$ 1,2M
          </div>
        </div>
        <div style={{ textAlign: "right" }}>
          <div style={{ fontFamily: F.mono, fontSize: 11, letterSpacing: "0.20em", textTransform: "uppercase", color: C.stone3 }}>relógio do sistema</div>
          <div style={{ fontFamily: F.mono, fontSize: 80, lineHeight: 0.95, color: C.paper, fontVariantNumeric: "tabular-nums", letterSpacing: "-0.02em", marginTop: 4 }}>
            {hh}:{mm}<span style={{ color: C.lime }}>:</span>{ss}
          </div>
          <div style={{ fontFamily: F.mono, fontSize: 12, color: C.stone3, marginTop: 4 }}>
            fase: lances aleatórios · prorrogação automática
          </div>
        </div>
      </div>

      {/* SVG CHART */}
      <svg
        viewBox={`0 0 ${CHART_X + CHART_W + 40} ${CHART_Y + CHART_H + 40}`}
        style={{ position: "absolute", inset: 0, width: "100%", height: "100%", pointerEvents: "none" }}
      >
        {/* Y-axis labels */}
        {[312000, 315000, 318000, 321000].map((p) => (
          <g key={p}>
            <line x1={CHART_X + 60} y1={yOf(p)} x2={CHART_X + CHART_W} y2={yOf(p)} stroke={C.lineDk} strokeWidth="1" strokeDasharray="3 6" opacity="0.5" />
            <text x={CHART_X + 52} y={yOf(p) + 4} textAnchor="end" fontFamily={F.mono} fontSize="13" fill={C.stone3} style={{ letterSpacing: "0.02em" }}>
              R$ {(p / 1000).toFixed(0)}k
            </text>
          </g>
        ))}

        {/* Time axis */}
        <line x1={CHART_X + 60} y1={CHART_Y + CHART_H - 30} x2={CHART_X + CHART_W} y2={CHART_Y + CHART_H - 30} stroke={C.lineDk} strokeWidth="1" opacity="0.4" />
        {[1, 3, 5, 7].map((t) => (
          <text key={t} x={xOf(t)} y={CHART_Y + CHART_H - 10} textAnchor="middle" fontFamily={F.mono} fontSize="11" fill={C.stone3}>
            +{t}s
          </text>
        ))}

        {/* Bidder lines + endpoint dots */}
        {Object.keys(BIDDERS).map((k) => {
          const b = BIDDERS[k];
          const s = state[k];
          if (!s.history.length) return null;

          // Build step path
          const pts = [...s.history];
          let d = `M ${xOf(pts[0].t)} ${yOf(pts[0].p)}`;
          for (let i = 1; i < pts.length; i++) {
            d += ` L ${xOf(pts[i].t)} ${yOf(pts[i - 1].p)}`;
            d += ` L ${xOf(pts[i].t)} ${yOf(pts[i].p)}`;
          }
          // Extend to current playhead OR drop time
          const endT = s.status === "dropped" ? s.lastUpdate : Math.min(localTime, T_MAX);
          d += ` L ${xOf(endT)} ${yOf(s.price)}`;

          const isUs = b.isUs;
          const lastPt = pts[pts.length - 1];

          return (
            <g key={k} style={{ opacity: s.status === "dropped" ? 0.25 : 1, transition: "opacity 500ms" }}>
              <path
                d={d}
                stroke={b.color}
                strokeWidth={isUs ? 3 : 1.8}
                fill="none"
                strokeLinejoin="round"
                strokeLinecap="round"
                style={{ filter: isUs ? `drop-shadow(0 0 6px ${C.lime}66)` : "none" }}
              />
              {/* Bid points */}
              {pts.map((p, i) => (
                <circle key={i} cx={xOf(p.t)} cy={yOf(p.p)} r={isUs ? 5 : 3.5} fill={b.color} stroke={C.ink} strokeWidth="2" />
              ))}
              {/* Current endpoint pulse for active */}
              {s.status === "active" && (
                <circle cx={xOf(endT)} cy={yOf(s.price)} r="8" fill="none" stroke={b.color} strokeWidth="2">
                  <animate attributeName="r" values="8;14;8" dur="1.4s" repeatCount="indefinite" />
                  <animate attributeName="opacity" values="1;0;1" dur="1.4s" repeatCount="indefinite" />
                </circle>
              )}
              {/* Inline label at endpoint */}
              {s.status !== "dropped" && (
                <text x={xOf(endT) + 14} y={yOf(s.price) + 4} fontFamily={F.mono} fontSize={isUs ? "16" : "12"} fill={b.color} fontWeight={isUs ? "600" : "400"}>
                  {isUs ? "Pleita" : b.name.split(" ")[0]}
                </text>
              )}
            </g>
          );
        })}
      </svg>

      {/* Right ranking panel */}
      <div style={{
        position: "absolute", right: 96, top: 320, width: 720,
      }}>
        <div style={{ fontFamily: F.mono, fontSize: 12, letterSpacing: "0.22em", textTransform: "uppercase", color: C.stone3, marginBottom: 14 }}>
          Ranking · atualiza a cada lance
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {ranked.map((s, rank) => {
            const b = BIDDERS[s.id];
            const isLeader = rank === 0 && s.status !== "dropped";
            const justUpdated = localTime - s.lastUpdate < 0.4 && s.lastUpdate > 0;
            const droppedTime = s.status === "dropped" ? localTime - s.lastUpdate : 0;

            return (
              <div key={s.id} style={{
                display: "grid", gridTemplateColumns: "60px 1fr auto",
                gap: 18, alignItems: "center",
                padding: "20px 24px", borderRadius: 14,
                border: `1px solid ${isLeader ? C.lime + "aa" : C.lineDk}`,
                background: isLeader
                  ? `linear-gradient(90deg, ${C.lime}22, ${C.lime}08)`
                  : s.status === "dropped" ? `${C.ink2}66` : `${C.ink2}cc`,
                opacity: s.status === "dropped" ? Math.max(0.45, 1 - droppedTime * 0.4) : 1,
                transition: "border-color 250ms, background 250ms",
                transform: justUpdated ? "translateX(-4px)" : "translateX(0)",
                position: "relative", overflow: "hidden",
              }}>
                <div style={{
                  fontFamily: F.display, fontSize: 44, lineHeight: 1, color: isLeader ? C.lime : C.stone3,
                  textAlign: "center", letterSpacing: "-0.02em",
                }}>
                  {s.status === "dropped" ? "—" : (rank + 1) + "º"}
                </div>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontFamily: F.sans, fontSize: 20, color: C.paper, fontWeight: 500, letterSpacing: "-0.01em", display: "flex", alignItems: "center", gap: 8 }}>
                    {b.name}
                    {b.isUs && <span style={{ fontFamily: F.mono, fontSize: 10, padding: "3px 7px", borderRadius: 4, background: C.lime, color: C.ink, letterSpacing: "0.12em", textTransform: "uppercase" }}>você</span>}
                  </div>
                  <div style={{ fontFamily: F.mono, fontSize: 12, color: C.stone3, marginTop: 4 }}>
                    {b.cnpj}{s.status === "dropped" && " · desistiu"}
                  </div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div style={{
                    fontFamily: F.mono, fontSize: 28, color: isLeader ? C.lime : C.paper,
                    fontVariantNumeric: "tabular-nums",
                    textDecoration: s.status === "dropped" ? "line-through" : "none",
                  }}>
                    {fmtPrice(s.price)}
                  </div>
                  {justUpdated && s.status === "active" && (
                    <div style={{ fontFamily: F.mono, fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase", color: b.color, marginTop: 2 }}>
                      novo lance ↓
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>

        {/* Strategy note */}
        <div style={{
          marginTop: 22, padding: "16px 22px",
          borderRadius: 12, background: `${C.ink2}88`, border: `1px solid ${C.lime}33`,
          display: "flex", alignItems: "center", gap: 16,
          opacity: Math.min(1, localTime / 0.8),
        }}>
          <span style={{ fontSize: 26 }}>⚡</span>
          <div>
            <div style={{ fontFamily: F.display, fontSize: 17, color: C.paper, letterSpacing: "-0.01em" }}>
              Robô de lances · estratégia <span style={{ color: C.lime }}>Equilibrada</span>
            </div>
            <div style={{ fontFamily: F.mono, fontSize: 12, color: C.stone3, marginTop: 4 }}>
              cobre lances até 5% acima do segundo · piso R$ 312.000
            </div>
          </div>
        </div>
      </div>

      {/* Bottom event log strip */}
      <div style={{
        position: "absolute", left: 96, bottom: 160, right: 96,
        display: "flex", alignItems: "center", gap: 12,
        opacity: Math.min(1, localTime / 0.4),
      }}>
        <div style={{ fontFamily: F.mono, fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: C.stone3, marginRight: 8, whiteSpace: "nowrap" }}>
          últimos lances ›
        </div>
        <div style={{ flex: 1, display: "flex", gap: 8, overflow: "hidden" }}>
          {fired.slice(-5).map((e, i, arr) => {
            const b = BIDDERS[e.who];
            const isWin = e.action === "win";
            const isDrop = e.action === "drop";
            const age = localTime - e.t;
            return (
              <div key={`${e.t}-${e.who}-${e.action || ""}`} style={{
                padding: "8px 14px", borderRadius: 999,
                border: `1px solid ${isWin ? C.lime : isDrop ? `${C.stone3}66` : `${b.color}66`}`,
                background: isWin ? `${C.lime}22` : `${C.ink2}aa`,
                whiteSpace: "nowrap",
                opacity: Math.min(1, Math.max(0.35, 1 - age * 0.1)),
                transform: i === arr.length - 1 && age < 0.3 ? `scale(${1 + (0.3 - age) / 0.6})` : "scale(1)",
              }}>
                <span style={{ fontFamily: F.mono, fontSize: 11, color: b.color, marginRight: 8 }}>{b.name.split(" ")[0]}</span>
                <span style={{ fontFamily: F.mono, fontSize: 13, color: isWin ? C.lime : C.paper }}>
                  {isWin ? "VENCEDORA" : isDrop ? "desistiu" : fmtPrice(e.price)}
                </span>
              </div>
            );
          })}
        </div>
      </div>

      <style>{`
        @keyframes blinkLive { 0%, 100% { opacity: 1; } 50% { opacity: 0.35; } }
      `}</style>
    </div>
  );
}

// ---------- CENA 6 — VITÓRIA ----------

// Pre-generate confetti pieces (stable across renders)
const CONFETTI = Array.from({ length: 80 }).map((_, i) => {
  const r = (n) => (Math.sin(i * 9301 + n * 49297) * 233280) % 1;
  const x = Math.abs(r(1)) * 1920;
  const delay = Math.abs(r(2)) * 2.0;
  const dur = 2.2 + Math.abs(r(3)) * 1.5;
  const drift = (r(4) - 0.5) * 200;
  const rotSpd = (r(5) - 0.5) * 720;
  const size = 6 + Math.abs(r(6)) * 10;
  const palette = [C.lime, C.lime2, C.paper, "#F5F0DE", C.lime, "#7DC95B"];
  const color = palette[Math.floor(Math.abs(r(7)) * palette.length)];
  const square = Math.abs(r(8)) > 0.5;
  return { x, delay, dur, drift, rotSpd, size, color, square };
});

function Confetti({ localTime }) {
  return (
    <div style={{ position: "absolute", inset: 0, pointerEvents: "none", overflow: "hidden" }}>
      {CONFETTI.map((c, i) => {
        const t = localTime - c.delay;
        if (t < 0 || t > c.dur + 2) return null;
        const p = t / c.dur;
        const y = -40 + Easing.easeInQuad(Math.min(1, p)) * (1080 + 80);
        const x = c.x + c.drift * Math.sin(t * 2);
        const rot = t * c.rotSpd;
        const opacity = p < 0.1 ? p * 10 : p > 0.9 ? Math.max(0, 1 - (p - 0.9) * 10) : 1;
        return (
          <div key={i} style={{
            position: "absolute", left: x, top: y,
            width: c.size, height: c.square ? c.size * 0.5 : c.size,
            background: c.color, borderRadius: c.square ? 1 : c.size,
            transform: `rotate(${rot}deg)`,
            opacity,
          }} />
        );
      })}
    </div>
  );
}

function SceneVictory() {
  const { localTime, duration } = useSprite();

  // Big VENCEU text: enters with overshoot
  const venceuT = Math.min(1, localTime / 0.6);
  const venceuScale = Easing.easeOutBack(venceuT);
  const venceuOpacity = venceuT;

  // Bg flash white at t=0
  const flash = localTime < 0.3 ? 1 - localTime / 0.3 : 0;

  // Stats appear at 1.0s
  const statsT = Math.max(0, Math.min(1, (localTime - 1.0) / 0.6));
  const statsOpacity = statsT;
  const statsY = (1 - Easing.easeOutCubic(statsT)) * 30;

  // Wordmark appears at 2.5s
  const wmT = Math.max(0, Math.min(1, (localTime - 2.4) / 0.7));

  return (
    <div style={{
      position: "absolute", inset: 0,
      background: `radial-gradient(circle at 50% 45%, #1e3a6d 0%, ${C.ink} 50%, #050b1a 100%)`,
      color: C.paper, overflow: "hidden",
    }}>
      {/* Flash */}
      <div style={{ position: "absolute", inset: 0, background: C.lime, opacity: flash, pointerEvents: "none" }} />

      {/* Grain */}
      <div style={{
        position: "absolute", inset: 0,
        backgroundImage: "radial-gradient(rgba(255,255,255,0.03) 1px, transparent 1px)",
        backgroundSize: "5px 5px", pointerEvents: "none",
      }} />

      <Confetti localTime={localTime} />

      {/* Eyebrow */}
      <div style={{
        position: "absolute", left: "50%", top: 130,
        transform: `translateX(-50%) translateY(${(1 - venceuOpacity) * -20}px)`,
        opacity: venceuOpacity,
      }}>
        <div style={{
          display: "inline-flex", alignItems: "center", gap: 12,
          padding: "10px 22px", borderRadius: 999,
          background: `${C.lime}22`, border: `1px solid ${C.lime}66`,
        }}>
          <span style={{ fontSize: 18 }}>🏆</span>
          <span style={{ fontFamily: F.mono, fontSize: 14, letterSpacing: "0.24em", textTransform: "uppercase", color: C.lime }}>
            Pregão arrematado · adjudicação em 14 dias
          </span>
        </div>
      </div>

      {/* VENCEU. */}
      <div style={{
        position: "absolute", left: "50%", top: 230,
        transform: `translateX(-50%) scale(${venceuScale})`,
        opacity: venceuOpacity,
        textAlign: "center",
      }}>
        <h1 style={{
          margin: 0,
          fontFamily: F.display,
          fontSize: 340, lineHeight: 0.9,
          letterSpacing: "-0.05em",
          color: C.paper,
          textShadow: `0 0 80px ${C.lime}66`,
        }}>
          VENCEU<span style={{ color: C.lime }}>.</span>
        </h1>
      </div>

      {/* Stats row */}
      <div style={{
        position: "absolute", left: "50%", top: 600,
        transform: `translateX(-50%) translateY(${statsY}px)`,
        opacity: statsOpacity,
        display: "flex", gap: 20, alignItems: "stretch",
      }}>
        {[
          { l: "Valor adjudicado",  v: "R$ 312.000",  c: C.lime },
          { l: "Economia vs. preço de referência", v: "−74%", c: C.paper },
          { l: "Próxima ação",      v: "Assinar contrato", c: C.paper, sub: "prazo de 14 dias úteis" },
        ].map((s, i) => (
          <div key={i} style={{
            padding: "20px 28px",
            borderRadius: 14,
            background: `${C.ink2}cc`,
            border: `1px solid ${i === 0 ? C.lime + "66" : C.lineDk}`,
            backdropFilter: "blur(8px)",
            minWidth: i === 2 ? 300 : 220,
          }}>
            <div style={{ fontFamily: F.mono, fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: C.stone3 }}>
              {s.l}
            </div>
            <div style={{ fontFamily: F.display, fontSize: 42, lineHeight: 1, color: s.c, marginTop: 8, letterSpacing: "-0.02em", fontVariantNumeric: "tabular-nums" }}>
              {s.v}
            </div>
            {s.sub && <div style={{ fontFamily: F.mono, fontSize: 12, color: C.stone3, marginTop: 6 }}>{s.sub}</div>}
          </div>
        ))}
      </div>

      {/* Tagline + wordmark · empilhado bem abaixo das stats, deixando espaço pro caption */}
      <div style={{
        position: "absolute", left: "50%", top: 800,
        transform: `translateX(-50%) translateY(${(1 - wmT) * 20}px)`,
        opacity: wmT,
        textAlign: "center",
      }}>
        <div style={{ fontFamily: F.display, fontSize: 38, lineHeight: 1.05, color: C.paper, letterSpacing: "-0.02em" }}>
          A Pleita pleiteia por você<span style={{ color: C.lime }}>.</span>
        </div>
        <div style={{ marginTop: 18, display: "flex", justifyContent: "center", alignItems: "center", gap: 18 }}>
          <Wordmark size={36} onDark />
          <span style={{ width: 1, height: 22, background: "rgba(255,255,255,0.18)" }} />
          <span style={{ fontFamily: F.mono, fontSize: 11, letterSpacing: "0.20em", textTransform: "uppercase", color: C.stone3 }}>
            pleita.com.br
          </span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SceneAuction, SceneVictory });
