// ===== CENA 1 (0–7s) — O PROBLEMA · CENA 2 (7–14s) — CAÇA-EDITAIS =====

// ---------- utilidades ----------

const editalSeed = [
  ["EDT-2026-05-A1B2", "Aquisição de equipamentos de TI",        "Pref. Campinas",   "SP", 1247380],
  ["EDT-2026-05-3C8D", "Locação de impressoras outsourcing",     "TRF 3ª Região",    "SP",  385000],
  ["EDT-2026-05-5E11", "Manutenção preventiva de elevadores",    "USP",              "SP",  214500],
  ["EDT-2026-05-9F2C", "Serviços de limpeza e conservação",      "TJ-MG",            "MG",  742000],
  ["EDT-2026-05-B6F0", "Aquisição de mobiliário escolar · L4",   "SEDUC-PE",         "PE", 2420000],
  ["EDT-2026-05-77E1", "Obras de pavimentação asfáltica · L4",   "DNIT",             "BA",18900000],
  ["EDT-2026-05-C9B3", "Aquisição de medicamentos · lote 7",     "SES-RJ",           "RJ", 4870000],
  ["EDT-2026-05-08FE", "Software de gestão escolar (SaaS)",      "SEDUC-GO",         "GO",  890000],
  ["EDT-2026-05-44A0", "Coleta de resíduos sólidos urbanos",     "Pref. Sorocaba",   "SP", 3680000],
  ["EDT-2026-05-A3F1", "Reforma de unidades de saúde · UPA",     "SES-MG",           "MG", 1240000],
  ["EDT-2026-05-B7D2", "Manutenção de frota de viaturas",        "PMERJ",            "RJ",  920000],
  ["EDT-2026-05-29C4", "Serviços de vigilância armada",          "BB",               "DF", 5210000],
  ["EDT-2026-05-EE83", "Aquisição de uniformes escolares",       "Pref. Joinville",  "SC",  470000],
  ["EDT-2026-05-1124", "Locação de veículos com motorista",      "CGE-PR",           "PR", 1080000],
  ["EDT-2026-05-FA09", "Aquisição de gêneros alimentícios",      "FNDE",             "DF", 8950000],
  ["EDT-2026-05-DD3B", "Sistema de gestão hospitalar",           "HRT-DF",           "DF", 2310000],
  ["EDT-2026-05-7A66", "Serviços de tradução juramentada",       "MRE",              "DF",  185000],
  ["EDT-2026-05-90BC", "Aquisição de tomógrafo computadorizado", "INTO-RJ",          "RJ",13400000],
];

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

function EditalRow({ id, obj, orgao, uf, valor, dim }) {
  return (
    <div style={{
      display: "grid", gridTemplateColumns: "180px 1fr 220px 160px",
      gap: 24, padding: "14px 24px", alignItems: "center",
      borderBottom: `1px solid ${C.lineDk}40`,
      opacity: dim,
    }}>
      <span style={{ fontFamily: F.mono, fontSize: 14, color: C.paper, opacity: 0.55 }}>{id}</span>
      <span style={{ fontFamily: F.sans, fontSize: 18, color: C.paper, opacity: 0.9, overflow: "hidden", whiteSpace: "nowrap", textOverflow: "ellipsis" }}>{obj}</span>
      <span style={{ fontFamily: F.sans, fontSize: 15, color: C.paper, opacity: 0.55 }}>{orgao} · {uf}</span>
      <span style={{ fontFamily: F.mono, fontSize: 16, color: C.paper, opacity: 0.7, textAlign: "right", fontVariantNumeric: "tabular-nums" }}>{fmtBR(valor)}</span>
    </div>
  );
}

// ---------- CENA 1 ----------
function SceneProblem() {
  const { localTime, duration } = useSprite();

  // Animated counter 0 → 312
  const count = Math.round(interpolate([0, 1.6], [0, 312], Easing.easeOutCubic)(localTime));

  // Exit fade
  const exitT = Math.max(0, duration - 0.6);
  const exitOpacity = localTime > exitT ? 1 - (localTime - exitT) / 0.6 : 1;

  // Scrolling column: doubled list, translateY based on time
  const scrollSpeed = 110; // px/s
  const scrollY = -localTime * scrollSpeed;

  return (
    <div style={{
      position: "absolute", inset: 0,
      background: `linear-gradient(180deg, ${C.ink} 0%, #08132a 100%)`,
      color: C.paper, opacity: exitOpacity,
    }}>
      {/* Grain */}
      <div style={{
        position: "absolute", inset: 0,
        backgroundImage: "radial-gradient(rgba(255,255,255,0.03) 1px, transparent 1px)",
        backgroundSize: "4px 4px", pointerEvents: "none",
      }} />

      {/* Right column · scrolling editais */}
      <div style={{
        position: "absolute", right: 0, top: 0, bottom: 0, width: 980,
        overflow: "hidden",
        maskImage: "linear-gradient(180deg, transparent 0%, #000 12%, #000 88%, transparent 100%)",
        WebkitMaskImage: "linear-gradient(180deg, transparent 0%, #000 12%, #000 88%, transparent 100%)",
      }}>
        <div style={{ transform: `translateY(${scrollY}px)`, willChange: "transform" }}>
          {[...editalSeed, ...editalSeed, ...editalSeed].map((r, i) => (
            <EditalRow key={i} id={r[0]} obj={r[1]} orgao={r[2]} uf={r[3]} valor={r[4]} dim={0.85} />
          ))}
        </div>
      </div>

      {/* Vignette behind type */}
      <div style={{
        position: "absolute", left: 0, top: 0, bottom: 0, width: 1100,
        background: `linear-gradient(90deg, ${C.ink} 60%, transparent 100%)`,
      }} />

      {/* Type stack */}
      <div style={{ position: "absolute", left: 120, top: 220, maxWidth: 900 }}>
        <div style={{
          fontFamily: F.mono, fontSize: 14, letterSpacing: "0.24em", textTransform: "uppercase",
          color: C.lime, marginBottom: 30,
          opacity: localTime > 0.15 ? 1 : 0, transition: "opacity 400ms",
        }}>
          <span style={{ display: "inline-block", width: 8, height: 8, borderRadius: 999, background: C.lime, marginRight: 12, verticalAlign: "middle" }} />
          Toda segunda-feira no Brasil
        </div>

        <div style={{
          fontFamily: F.display, fontSize: 280, lineHeight: 0.86, letterSpacing: "-0.04em",
          color: C.paper, fontVariantNumeric: "tabular-nums",
        }}>
          {count}<span style={{ color: C.lime }}>.</span>
        </div>

        <div style={{
          fontFamily: F.display, fontSize: 60, lineHeight: 1.05, marginTop: 16,
          color: C.paper, letterSpacing: "-0.02em",
          opacity: localTime > 1.6 ? 1 : 0,
          transform: `translateY(${localTime > 1.6 ? 0 : 16}px)`,
          transition: "opacity 600ms, transform 600ms",
        }}>
          editais novos.
        </div>

        {/* Chips */}
        <div style={{ display: "flex", gap: 16, marginTop: 60 }}>
          {[
            { v: "8.231", l: "páginas" },
            { v: "67",    l: "órgãos públicos" },
            { v: "3 dias úteis", l: "pra decidir" },
          ].map((s, i) => {
            const appearAt = 2.4 + i * 0.35;
            const show = localTime > appearAt;
            const tt = Math.max(0, Math.min(1, (localTime - appearAt) / 0.5));
            const eased = Easing.easeOutBack(tt);
            return (
              <div key={i} style={{
                padding: "16px 22px",
                borderRadius: 14,
                border: `1px solid ${C.lineDk}`,
                background: `${C.ink2}80`,
                opacity: show ? 1 : 0,
                transform: `translateY(${(1 - eased) * 20}px)`,
              }}>
                <div style={{ fontFamily: F.mono, fontSize: 26, color: C.paper, fontVariantNumeric: "tabular-nums", letterSpacing: "-0.01em" }}>{s.v}</div>
                <div style={{ fontFamily: F.mono, fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: C.stone3, marginTop: 4 }}>{s.l}</div>
              </div>
            );
          })}
        </div>

        {/* Tagline humana */}
        <div style={{
          marginTop: 64,
          fontFamily: F.sans, fontSize: 24, color: "#A8B2CC", lineHeight: 1.4, maxWidth: 720,
          opacity: localTime > 4.0 ? 1 : 0,
          transform: `translateY(${localTime > 4.0 ? 0 : 12}px)`,
          transition: "opacity 600ms, transform 600ms",
        }}>
          E você ainda <em style={{ color: C.paper, fontStyle: "normal", textDecoration: "underline", textDecorationColor: C.lime, textUnderlineOffset: 6 }}>vende</em>, atende, paga conta. Não tem como ler tudo.
        </div>
      </div>
    </div>
  );
}

// ---------- CENA 2 ----------
const PORTAIS = [
  "ComprasNet",   "BEC-SP",            "PNCP",
  "Licitações-e", "Compras.gov.br",    "PCP-MG",
  "BLL",          "Comprasnet-Bahia",  "Portal Compras Públicas",
];

function PortalCard({ name, scanProgress, done, idx }) {
  // scanProgress 0..1 — sweep line across; when done, card brightens green
  const sweepX = scanProgress * 100;
  return (
    <div style={{
      position: "relative", overflow: "hidden",
      padding: "26px 28px", borderRadius: 14,
      border: `1px solid ${done ? C.lime + "80" : C.lineDk}`,
      background: done ? `${C.lime}14` : `${C.ink2}cc`,
      transition: "border-color 200ms, background 200ms",
      height: 124,
      display: "flex", flexDirection: "column", justifyContent: "space-between",
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <span style={{
          width: 10, height: 10, borderRadius: 999,
          background: done ? C.lime : C.stone3,
          boxShadow: done ? `0 0 12px ${C.lime}` : "none",
        }} />
        <span style={{ fontFamily: F.mono, fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: done ? C.lime : C.stone3 }}>
          {done ? "varrido" : "varrendo…"}
        </span>
      </div>
      <div style={{ fontFamily: F.sans, fontSize: 22, color: C.paper, fontWeight: 500, letterSpacing: "-0.01em" }}>
        {name}
      </div>
      <div style={{ fontFamily: F.mono, fontSize: 12, color: C.stone3 }}>
        portal #{String(idx + 1).padStart(2, "0")}
      </div>

      {/* Sweep line */}
      {!done && scanProgress > 0 && scanProgress < 1 && (
        <div style={{
          position: "absolute", top: 0, bottom: 0, width: 2,
          left: `${sweepX}%`,
          background: `linear-gradient(180deg, transparent, ${C.lime}, transparent)`,
          boxShadow: `0 0 16px ${C.lime}`,
        }} />
      )}
    </div>
  );
}

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

  // 9 portais, varredura paralela mas com staggers
  // Cada portal: starts at 0.4 + i*0.15s, takes 1.4s
  const portalStates = PORTAIS.map((name, i) => {
    const start = 0.6 + i * 0.18;
    const dur = 1.6;
    const t = localTime - start;
    if (t < 0) return { name, scanProgress: 0, done: false, idx: i };
    if (t > dur) return { name, scanProgress: 1, done: true, idx: i };
    return { name, scanProgress: t / dur, done: false, idx: i };
  });

  // Counter: 312 → 8
  // Phase: from 2.4s to 4.6s, ramp down through funnel stops
  const funnel = [
    { at: 0.4, n: 312, label: "editais brutos" },
    { at: 2.2, n: 184, label: "depois dos filtros" },
    { at: 3.2, n:  46, label: "compatíveis" },
    { at: 4.2, n:  19, label: "no orçamento" },
    { at: 5.0, n:   8, label: "matches pra você" },
  ];
  const stage = [...funnel].reverse().find((s) => localTime >= s.at) || funnel[0];

  return (
    <div style={{
      position: "absolute", inset: 0,
      background: `linear-gradient(180deg, #08132a 0%, ${C.ink} 50%, #08132a 100%)`,
      color: C.paper, opacity: exitOpacity,
    }}>
      {/* Header eyebrow + agent strip */}
      <div style={{ position: "absolute", left: 96, top: 110, right: 96, display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 40 }}>
        <div>
          <div style={{ fontFamily: F.mono, fontSize: 13, letterSpacing: "0.24em", textTransform: "uppercase", color: C.lime, marginBottom: 12 }}>
            <span style={{ display: "inline-block", width: 8, height: 8, borderRadius: 999, background: C.lime, marginRight: 12, verticalAlign: "middle", boxShadow: `0 0 10px ${C.lime}` }} />
            Agente 1 / 6 · em ação agora
          </div>
          <div style={{ fontFamily: F.display, fontSize: 78, lineHeight: 0.95, letterSpacing: "-0.03em" }}>
            🔍 Caça-Editais<span style={{ color: C.lime }}>.</span>
          </div>
          <div style={{ fontFamily: F.sans, fontSize: 22, color: "#A8B2CC", marginTop: 14 }}>
            Vasculha 9 portais públicos a cada 15 minutos.
          </div>
        </div>

        {/* Counter funnel */}
        <div style={{ textAlign: "right", flexShrink: 0 }}>
          <div style={{ fontFamily: F.mono, fontSize: 12, letterSpacing: "0.18em", textTransform: "uppercase", color: C.stone3, marginBottom: 6 }}>
            {stage.label}
          </div>
          <div key={stage.n} style={{
            fontFamily: F.display, fontSize: 168, lineHeight: 0.88,
            color: stage.n === 8 ? C.lime : C.paper,
            fontVariantNumeric: "tabular-nums",
            animation: "popCount 350ms cubic-bezier(0.18, 0.89, 0.32, 1.28)",
            animationFillMode: "both",
            letterSpacing: "-0.04em",
            textShadow: stage.n === 8 ? `0 0 40px ${C.lime}80` : "none",
          }}>
            {stage.n}
          </div>
        </div>
      </div>

      {/* 3×3 grid */}
      <div style={{
        position: "absolute", left: 96, right: 96, top: 420,
        display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 18,
      }}>
        {portalStates.map((p) => (
          <PortalCard key={p.name} {...p} />
        ))}
      </div>

      {/* Stat strip bottom */}
      <div style={{
        position: "absolute", left: 96, right: 96, bottom: 180,
        display: "flex", alignItems: "center", justifyContent: "space-between",
        opacity: localTime > 4.6 ? 1 : 0,
        transform: `translateY(${localTime > 4.6 ? 0 : 12}px)`,
        transition: "opacity 500ms, transform 500ms",
      }}>
        <div style={{ fontFamily: F.sans, fontSize: 26, color: C.paper, lineHeight: 1.3 }}>
          De <span style={{ fontFamily: F.mono, color: C.stone3, textDecoration: "line-through" }}>312</span>{" "}
          para <span style={{ fontFamily: F.mono, color: C.lime, fontSize: 36, verticalAlign: "baseline" }}>8</span>{" "}
          editais que <em style={{ fontStyle: "normal", textDecoration: "underline", textDecorationColor: C.lime, textUnderlineOffset: 6 }}>realmente</em> fazem sentido pra você.
        </div>
        <div style={{ fontFamily: F.mono, fontSize: 14, letterSpacing: "0.16em", textTransform: "uppercase", color: C.stone3 }}>
          ~2,3s · haiku 4.5
        </div>
      </div>

      <style>{`
        @keyframes popCount {
          0%   { transform: scale(0.7); opacity: 0; }
          60%  { transform: scale(1.06); opacity: 1; }
          100% { transform: scale(1); opacity: 1; }
        }
      `}</style>
    </div>
  );
}

Object.assign(window, { SceneProblem, SceneHunter });
