/* global React, Sprite, useSprite, useTime, Easing, clamp */

/* ============================================================
   Keelway demo video #2 — "A day on the desk"
   Broker-natural flow · AI sprinkled · 58s · 1920×1080
   ============================================================ */

const C = {
  bg0: "#F5F2E8", bg1: "#FFFFFF", bg2: "#FAF7EE", bg3: "#EFEADB",
  line: "#E2DBC7", lineStrong: "#C7BDA1",
  text: "#0A0A0A", mid: "#4A453B", dim: "#7A7466", faint: "#A89F8A",
  accent: "#B08D57", accentDim: "#8C6F3F", accentBg: "rgba(176, 141, 87, 0.12)",
  blue: "#3B6EA8", blueBg: "rgba(59, 110, 168, 0.10)",
  ok: "#5C8A4A", okBg: "rgba(92, 138, 74, 0.12)",
  warn: "#C68E2C", warnBg: "rgba(198, 142, 44, 0.12)",
  danger: "#B14545", dangerBg: "rgba(177, 69, 69, 0.12)",
  mono: '"IBM Plex Mono", ui-monospace, monospace',
  sans: '"IBM Plex Sans", ui-sans-serif, system-ui, sans-serif',
};

const SCENES = {
  intro:    [0,    3.5],
  morning:  [3.5,  10.0],
  tender:   [10.0, 17.5],
  quote:    [17.5, 24.5],
  post:     [24.5, 35.5],   // signature Keelway moment — longer
  book:     [35.5, 41.5],
  dispatch: [41.5, 49.5],
  pod:      [49.5, 55.0],
  integ:    [55.0, 61.5],
  outro:    [61.5, 68.5],
};

function ease(t, fn = Easing.easeOutCubic) { return fn(clamp(t, 0, 1)); }

function FadeUp({ delay = 0, dur = 0.5, children, style = {} }) {
  const { localTime } = useSprite();
  const t = ease(Math.max(0, (localTime - delay) / dur));
  return <div style={{ opacity: t, transform: `translateY(${(1 - t) * 12}px)`, ...style }}>{children}</div>;
}

function Chip({ kind = "", children, pulse }) {
  const map = {
    accent: [C.accent, C.accentBg], blue: [C.blue, C.blueBg],
    ok: [C.ok, C.okBg], warn: [C.warn, C.warnBg],
    danger: [C.danger, C.dangerBg], "": [C.mid, C.bg3],
  };
  const [color, bg] = map[kind] || map[""];
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 5,
      fontFamily: C.mono, fontSize: 11, textTransform: "uppercase", letterSpacing: "0.08em",
      padding: "3px 8px", borderRadius: 3, background: bg, color, fontWeight: 500,
    }}>
      <span style={{ width: 5, height: 5, borderRadius: "50%", background: color, animation: pulse ? "kw-pulse 1.4s infinite" : "none" }} />
      {children}
    </span>
  );
}

/* Cursor visualization */
function Cursor({ x, y, click }) {
  return (
    <svg width="22" height="26" viewBox="0 0 22 26" style={{
      position: "absolute", left: x, top: y,
      filter: `drop-shadow(0 2px 4px rgba(0,0,0,0.2))`,
      zIndex: 1000,
      transition: "left 0.4s cubic-bezier(0.5, 0, 0.2, 1), top 0.4s cubic-bezier(0.5, 0, 0.2, 1)",
    }}>
      <path d="M3 2 L3 19 L8 15 L11 22 L13 21 L10 14 L17 14 Z" fill="#fff" stroke="#0a0a0a" strokeWidth="1.4" strokeLinejoin="round" />
      {click && <circle cx="3" cy="2" r="14" fill="none" stroke={C.accent} strokeWidth="2" opacity={1 - click} />}
    </svg>
  );
}

/* App shell — same as first video for visual consistency */
function AppShell({ active, children, subtitle }) {
  return (
    <div style={{ position: "absolute", inset: 0, background: C.bg0, display: "grid", gridTemplateColumns: "260px 1fr", gridTemplateRows: "60px 1fr 36px", gridTemplateAreas: '"logo top" "nav main" "nav status"' }}>
      <div style={{ gridArea: "logo", borderRight: `1px solid ${C.line}`, borderBottom: `1px solid ${C.line}`, background: C.bg1, display: "flex", alignItems: "center", gap: 12, padding: "0 18px" }}>
        <div style={{ width: 30, height: 30, borderRadius: 5, background: `linear-gradient(135deg, ${C.accent}, ${C.accentDim})`, display: "grid", placeItems: "center", color: "#fff", fontFamily: C.mono, fontSize: 16, fontWeight: 700 }}>K</div>
        <div style={{ fontFamily: C.mono, fontSize: 15, letterSpacing: "0.1em", fontWeight: 600, color: C.text }}>KEELWAY</div>
        <div style={{ fontFamily: C.mono, fontSize: 10, color: C.dim, marginLeft: "auto", letterSpacing: "0.15em" }}>v4.2</div>
      </div>

      <div style={{ gridArea: "top", borderBottom: `1px solid ${C.line}`, background: C.bg1, display: "flex", alignItems: "center", padding: "0 18px", gap: 18 }}>
        <div style={{ fontFamily: C.mono, fontSize: 11, letterSpacing: "0.1em", color: C.mid, textTransform: "uppercase" }}>
          {subtitle?.[0] || ""} <span style={{ color: C.faint, margin: "0 6px" }}>/</span> <span style={{ color: C.text }}>{subtitle?.[1] || ""}</span>
        </div>
        <div style={{ marginLeft: "auto", display: "flex", gap: 20, alignItems: "center" }}>
          <TbStat label="OPEN" v="147" />
          <TbStat label="TODAY GM" v="$48,210" color={C.ok} />
          <TbStat label="MARGIN" v="17.3%" />
          <div style={{ width: 32, height: 32, borderRadius: "50%", background: C.bg3, border: `1px solid ${C.lineStrong}`, display: "grid", placeItems: "center", fontFamily: C.mono, fontSize: 11, color: C.text, fontWeight: 600 }}>MO</div>
        </div>
      </div>

      <div style={{ gridArea: "nav", borderRight: `1px solid ${C.line}`, background: C.bg1, padding: "12px 0", overflow: "hidden" }}>
        <NavSection label="OPS" items={["Load Board", "AI Check Calls", "Dispatch", "Appointments", "Inbox"]} active={active} />
        <NavSection label="COMMERCE" items={["Rate Desk", "RFP Engine", "Carrier Match", "Onboarding", "CRM"]} active={active} />
        <NavSection label="FINANCE" items={["Accounting", "Claims"]} active={active} />
        <NavSection label="INTELLIGENCE" items={["AI Console", "Fraud Shield", "Document AI", "Compliance", "Analytics"]} active={active} />
      </div>

      <div style={{ gridArea: "main", overflow: "hidden", position: "relative" }}>{children}</div>

      <div style={{ gridArea: "status", borderTop: `1px solid ${C.line}`, background: C.bg1, display: "flex", alignItems: "center", padding: "0 18px", gap: 24, fontFamily: C.mono, fontSize: 11, color: C.dim, letterSpacing: "0.1em", textTransform: "uppercase" }}>
        <span><span style={{ width: 6, height: 6, borderRadius: "50%", background: C.ok, display: "inline-block", marginRight: 8 }} />CONNECTED</span>
        <span>EDI · DAT · TRUCKSTOP · SAFER</span>
        <span style={{ marginLeft: "auto" }}>MAYA ORTIZ · NASHVILLE OPS</span>
      </div>
    </div>
  );
}

function NavSection({ label, items, active }) {
  return (
    <div>
      <div style={{ padding: "12px 18px 4px", fontFamily: C.mono, fontSize: 10, color: C.dim, letterSpacing: "0.16em" }}>{label}</div>
      {items.map(it => (
        <div key={it} style={{
          padding: "7px 18px", fontSize: 13,
          color: active === it ? C.accent : C.mid,
          background: active === it ? C.accentBg : "transparent",
          borderLeft: active === it ? `2px solid ${C.accent}` : "2px solid transparent",
        }}>{it}</div>
      ))}
    </div>
  );
}
function TbStat({ label, v, color }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end" }}>
      <span style={{ fontFamily: C.mono, fontSize: 10, color: C.dim, letterSpacing: "0.12em" }}>{label}</span>
      <span style={{ fontFamily: C.mono, fontSize: 14, color: color || C.text, fontWeight: 500 }}>{v}</span>
    </div>
  );
}

function Caption({ start, end, kicker, line }) {
  const t = useTime();
  if (t < start || t > end) return null;
  const local = t - start;
  const dur = end - start;
  let opacity = 1;
  if (local < 0.4) opacity = ease(local / 0.4);
  else if (local > dur - 0.5) opacity = 1 - ease((local - (dur - 0.5)) / 0.5);
  return (
    <div style={{
      position: "absolute", left: 60, bottom: 80, opacity, maxWidth: 820,
      fontFamily: C.sans,
      pointerEvents: "none",
    }}>
      {kicker && <div style={{ fontFamily: C.mono, fontSize: 13, letterSpacing: "0.22em", color: C.accent, textTransform: "uppercase", marginBottom: 8 }}>{kicker}</div>}
      <div style={{
        fontSize: 38, fontWeight: 600, color: C.text, lineHeight: 1.2, letterSpacing: "-0.01em",
        textShadow: `0 1px 0 ${C.bg0}, 0 0 24px ${C.bg0}`,
      }}>{line}</div>
    </div>
  );
}

/* ============================================================
   SCENE 1 — Cold open
   ============================================================ */
function SceneIntro() {
  const { localTime } = useSprite();
  return (
    <div style={{ position: "absolute", inset: 0, background: C.bg0, display: "flex", alignItems: "center", justifyContent: "center", flexDirection: "column", gap: 30 }}>
      {/* Top right nautical marker */}
      <div style={{ position: "absolute", top: 40, right: 60, textAlign: "right", fontFamily: C.mono, fontSize: 13, color: C.dim, letterSpacing: "0.2em", opacity: ease(localTime / 0.5) }}>
        <div>KW · DEMO · 02</div>
        <div style={{ marginTop: 4 }}>A DAY ON THE DESK</div>
      </div>

      <div style={{ opacity: ease(localTime / 0.5), transform: `scale(${0.92 + 0.08 * ease(localTime / 0.5)})` }}>
        <div style={{
          width: 96, height: 96, borderRadius: 18,
          background: `linear-gradient(135deg, ${C.accent}, ${C.accentDim})`,
          display: "grid", placeItems: "center",
          fontFamily: C.mono, fontSize: 52, fontWeight: 700, color: "#FFFFFF",
          boxShadow: `0 20px 60px rgba(176,141,87,0.35)`,
        }}>K</div>
      </div>

      <FadeUp delay={0.3} dur={0.6}>
        <div style={{ textAlign: "center" }}>
          <div style={{ fontFamily: C.mono, fontSize: 16, letterSpacing: "0.42em", color: C.accent, textTransform: "uppercase" }}>Keelway</div>
          <div style={{ fontFamily: C.sans, fontSize: 76, fontWeight: 600, color: C.text, marginTop: 16, letterSpacing: "-0.02em" }}>
            A day on the desk.
          </div>
          <div style={{ fontFamily: C.sans, fontSize: 22, color: C.mid, marginTop: 14 }}>
            How Maya runs her brokerage with Keelway.
          </div>
        </div>
      </FadeUp>
    </div>
  );
}

/* ============================================================
   SCENE 2 — Morning standup at the Load Board
   ============================================================ */
function SceneMorning() {
  const { localTime } = useSprite();
  return (
    <AppShell active="Load Board" subtitle={["OPS", "Load Board"]}>
      <div style={{ padding: 28 }}>
        <FadeUp delay={0} dur={0.4}>
          <div style={{ display: "flex", alignItems: "center", gap: 16, marginBottom: 20 }}>
            <div style={{ fontSize: 28, fontWeight: 600, color: C.text }}>Load Board</div>
            <div style={{ fontFamily: C.mono, fontSize: 12, color: C.dim, letterSpacing: "0.12em" }}>06:14 CT · MONDAY 05/26</div>
            <span style={{ marginLeft: "auto" }} />
            <Chip kind="ok">14 NEED COVER</Chip>
            <Chip kind="">38 IN TRANSIT</Chip>
            <Chip kind="">22 DELIVERED</Chip>
          </div>
        </FadeUp>

        {/* The board itself */}
        <FadeUp delay={0.3} dur={0.4}>
          <div style={{ background: C.bg1, border: `1px solid ${C.line}`, borderRadius: 6, overflow: "hidden" }}>
            <div style={{ display: "grid", gridTemplateColumns: "110px 110px 1.8fr 160px 1fr 100px 80px 100px", gap: 0, padding: "12px 16px", borderBottom: `1px solid ${C.line}`, fontFamily: C.mono, fontSize: 10, color: C.dim, letterSpacing: "0.14em", textTransform: "uppercase" }}>
              <span>STATUS</span><span>LOAD #</span><span>LANE</span><span>PICKUP</span><span>CUSTOMER</span><span style={{ textAlign: "right" }}>RATE</span><span style={{ textAlign: "right" }}>GM %</span><span style={{ textAlign: "right" }}>CARRIER</span>
            </div>
            {[
              { st: "ATRISK",   id: "KW-48217", lane: "Laredo, TX → Memphis, TN",        pu: "05/26 18:00", cust: "Walmart DC",   rate: "$2,980", gm: "17.8%", carr: "Hidalgo" },
              { st: "INTRANSIT",id: "KW-48216", lane: "Atlanta, GA → Chicago, IL",       pu: "Loaded",       cust: "Home Depot",  rate: "$2,200", gm: "15.9%", carr: "BluePeak" },
              { st: "COVERED",  id: "KW-48215", lane: "Long Beach, CA → Phoenix, AZ",    pu: "05/26 10:00", cust: "Sprouts",     rate: "$1,450", gm: "21.4%", carr: "Coastal" },
              { st: "OPEN",     id: "KW-48214", lane: "Dallas, TX → Newark, NJ",         pu: "05/26 06:00", cust: "Target DC",   rate: "$3,850", gm: "18.2%", carr: "—" },
              { st: "OPEN",     id: "KW-48213", lane: "Seattle, WA → Denver, CO",        pu: "05/26 09:00", cust: "Costco",      rate: "$2,940", gm: "19.0%", carr: "—" },
              { st: "OPEN",     id: "KW-48212", lane: "Houston, TX → Tampa, FL",         pu: "05/26 11:00", cust: "Publix",      rate: "$2,480", gm: "18.9%", carr: "—" },
              { st: "OPEN",     id: "KW-48211", lane: "SLC, UT → Kansas City, MO",       pu: "05/26 06:00", cust: "FedEx Frt.",  rate: "$2,780", gm: "16.9%", carr: "—" },
            ].map((l, i) => {
              const op = ease(Math.max(0, (localTime - 0.5 - i * 0.08) / 0.3));
              return (
                <div key={i} style={{
                  display: "grid", gridTemplateColumns: "110px 110px 1.8fr 160px 1fr 100px 80px 100px", gap: 0,
                  padding: "11px 16px", borderBottom: `1px solid ${C.line}`,
                  opacity: op, alignItems: "center",
                }}>
                  <Chip kind={l.st === "ATRISK" ? "danger" : l.st === "INTRANSIT" ? "blue" : l.st === "COVERED" ? "accent" : "warn"} pulse={l.st === "ATRISK"}>{l.st === "ATRISK" ? "AT RISK" : l.st === "INTRANSIT" ? "IN TRANSIT" : l.st}</Chip>
                  <span style={{ fontFamily: C.mono, fontSize: 12, color: C.dim }}>{l.id}</span>
                  <span style={{ fontSize: 13, color: C.text }}>{l.lane}</span>
                  <span style={{ fontFamily: C.mono, fontSize: 11, color: C.dim }}>{l.pu}</span>
                  <span style={{ fontSize: 12, color: C.text }}>{l.cust}</span>
                  <span style={{ fontFamily: C.mono, fontSize: 13, color: C.text, textAlign: "right" }}>{l.rate}</span>
                  <span style={{ fontFamily: C.mono, fontSize: 12, color: C.text, textAlign: "right" }}>{l.gm}</span>
                  <span style={{ fontFamily: C.mono, fontSize: 11, color: l.carr === "—" ? C.faint : C.text, textAlign: "right" }}>{l.carr}</span>
                </div>
              );
            })}
          </div>
        </FadeUp>

        {/* Pulse the cursor toward KW-48214 (the load we'll work today) */}
        {localTime > 2.6 && (
          <Cursor x={840 + (localTime > 3.2 ? 0 : 200)} y={310} click={localTime > 3.4 ? Math.max(0, 1 - (localTime - 3.4) * 1.5) : 0} />
        )}
      </div>
    </AppShell>
  );
}

/* ============================================================
   SCENE 3 — Tender arrives, Maya converts it to a load
   ============================================================ */
function SceneTender() {
  const { localTime } = useSprite();
  return (
    <AppShell active="Inbox" subtitle={["OPS", "Agent Inbox"]}>
      <div style={{ padding: 0, display: "grid", gridTemplateColumns: "300px 1fr", height: "100%" }}>
        <div style={{ borderRight: `1px solid ${C.line}`, padding: "12px 0" }}>
          {[
            { from: "Walmart EDI 204",     subj: "Tender · Dallas → Newark · 5/26",  t: "now",     hi: localTime > 0.4 },
            { from: "Jen · Target",        subj: "Pickup confirmation KW-48214",     t: "Yesterday", hi: false },
            { from: "Marco · Western Mtn", subj: "Re: Seattle → Denver bid",         t: "06:08",   hi: false },
            { from: "Costco Procurement",  subj: "Q3 lane contract renewal",         t: "Friday",  hi: false },
          ].map((th, i) => (
            <div key={i} style={{
              padding: "12px 16px", borderBottom: `1px solid ${C.line}`,
              borderLeft: th.hi ? `2px solid ${C.accent}` : "2px solid transparent",
              background: th.hi ? C.accentBg : "transparent",
              opacity: i === 0 ? ease(Math.max(0, localTime / 0.5)) : 1,
              transform: i === 0 ? `translateX(${(1 - ease(Math.max(0, localTime / 0.5))) * -20}px)` : "none",
            }}>
              <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 4 }}>
                <span style={{ fontFamily: C.mono, fontSize: 10, color: C.dim, padding: "1px 5px", border: `1px solid ${C.line}`, borderRadius: 2 }}>{i === 0 ? "EDI" : "EMAIL"}</span>
                {i === 0 && <Chip kind="accent" pulse>NEW TENDER</Chip>}
                <span style={{ fontFamily: C.mono, fontSize: 10, color: C.dim, marginLeft: "auto" }}>{th.t}</span>
              </div>
              <div style={{ fontSize: 13, fontWeight: 600, color: C.text }}>{th.from}</div>
              <div style={{ fontSize: 11, color: C.dim, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{th.subj}</div>
            </div>
          ))}
        </div>

        <div style={{ padding: 32 }}>
          <FadeUp delay={0.7} dur={0.4}>
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 8 }}>
              <div style={{ fontSize: 22, fontWeight: 600, color: C.text }}>Walmart EDI 204 · Tender 5512-A</div>
              <Chip kind="ok">VALID</Chip>
            </div>
            <div style={{ fontFamily: C.mono, fontSize: 12, color: C.dim, letterSpacing: "0.08em" }}>RECEIVED 06:14 · PARSED FROM PDF + EDI</div>
          </FadeUp>

          {/* Tender preview */}
          <FadeUp delay={1.1} dur={0.4} style={{ marginTop: 18 }}>
            <div style={{ background: C.bg1, border: `1px solid ${C.line}`, borderRadius: 6, padding: 22 }}>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24 }}>
                <div>
                  <FieldRow label="SHIPPER"      v="Walmart DC #1142" sub="3702 N Stemmons Fwy, Dallas TX 75247" />
                  <FieldRow label="PICKUP"       v="05/26 06:00 CT"   sub="appt required" />
                  <FieldRow label="COMMODITY"    v="Consumer goods · 36,800 lbs" />
                  <FieldRow label="EQUIPMENT"    v="53' Dry Van · no team" />
                </div>
                <div>
                  <FieldRow label="CONSIGNEE"    v="Walmart DC #2204" sub="5300 Avenue D, Newark NJ 07105" />
                  <FieldRow label="DELIVERY"     v="05/28 14:00 ET"   sub="appt required" />
                  <FieldRow label="DISTANCE"     v="1,547 mi"         sub="PC Miler · standard route" />
                  <FieldRow label="TENDERED $"   v="$3,850"           sub="customer offer" />
                </div>
              </div>
            </div>
          </FadeUp>

          {/* Subtle AI helper bar */}
          {localTime > 3.0 && (
            <div style={{ marginTop: 14, display: "flex", alignItems: "center", gap: 10, padding: "10px 16px", background: C.accentBg, borderLeft: `2px solid ${C.accent}`, borderRadius: 3, opacity: ease((localTime - 3.0) / 0.4) }}>
              <span style={{ fontFamily: C.mono, fontSize: 10, color: C.accent, letterSpacing: "0.14em" }}>KEELWAY</span>
              <span style={{ fontSize: 13, color: C.text }}>Parsed all 18 fields from the PDF + EDI · 99% confidence · no overrides needed.</span>
            </div>
          )}

          {/* Accept button + cursor */}
          {localTime > 4.5 && (
            <div style={{ marginTop: 20, display: "flex", gap: 8, opacity: ease((localTime - 4.5) / 0.4) }}>
              <button style={{ padding: "10px 18px", background: C.bg2, border: `1px solid ${C.lineStrong}`, color: C.text, borderRadius: 4, fontFamily: C.sans, fontSize: 13 }}>Edit fields</button>
              <button style={{ padding: "10px 18px", background: C.bg2, border: `1px solid ${C.lineStrong}`, color: C.text, borderRadius: 4, fontFamily: C.sans, fontSize: 13 }}>Decline</button>
              <button style={{ padding: "10px 22px", background: C.accent, border: `1px solid ${C.accent}`, color: "#fff", borderRadius: 4, fontFamily: C.sans, fontSize: 13, fontWeight: 600, position: "relative" }}>
                ✓ Accept · Create Load
              </button>
              {localTime > 5.0 && localTime < 6.2 && (
                <Cursor x={localTime < 5.5 ? 1100 : 720 + (localTime - 5.5) * 200} y={localTime < 5.5 ? 460 : 480} click={localTime > 6.0 ? Math.max(0, 1 - (localTime - 6.0) * 2) : 0} />
              )}
            </div>
          )}

          {localTime > 6.4 && (
            <div style={{ marginTop: 18, padding: 14, background: C.okBg, border: `1px solid ${C.ok}`, borderRadius: 4, fontSize: 14, color: C.text, opacity: ease((localTime - 6.4) / 0.4) }}>
              <Chip kind="ok">CREATED</Chip>
              <span style={{ marginLeft: 12 }}><b style={{ fontFamily: C.mono, fontSize: 13 }}>KW-48218</b> added to Load Board · status: OPEN · ready to quote</span>
            </div>
          )}
        </div>
      </div>
    </AppShell>
  );
}

function FieldRow({ label, v, sub }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{ fontFamily: C.mono, fontSize: 10, color: C.dim, letterSpacing: "0.14em", marginBottom: 3 }}>{label}</div>
      <div style={{ fontSize: 14, color: C.text }}>{v}</div>
      {sub && <div style={{ fontFamily: C.mono, fontSize: 11, color: C.dim, marginTop: 2 }}>{sub}</div>}
    </div>
  );
}

/* ============================================================
   SCENE 4 — Quoting the rate (Rate Desk, broker-driven)
   ============================================================ */
function SceneQuote() {
  const { localTime } = useSprite();
  // Maya types $3.02 character by character
  const typed = Math.min(4, Math.floor(localTime * 1.5));
  const typedStr = ["", "$", "$3", "$3.", "$3.02"][typed];

  return (
    <AppShell active="Rate Desk" subtitle={["COMMERCE", "Rate Desk"]}>
      <div style={{ padding: 32 }}>
        <FadeUp delay={0} dur={0.3}>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <div style={{ fontSize: 24, fontWeight: 600, color: C.text }}>Quote · KW-48218</div>
            <span style={{ fontFamily: C.mono, fontSize: 13, color: C.dim }}>Dallas, TX → Newark, NJ · 1,547 mi · 53' DV</span>
          </div>
        </FadeUp>

        <div style={{ marginTop: 22, display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 20 }}>
          {/* Left: broker's quote form */}
          <FadeUp delay={0.3} dur={0.4}>
            <div style={{ background: C.bg1, border: `1px solid ${C.line}`, borderRadius: 6, padding: 22 }}>
              <div style={{ fontFamily: C.mono, fontSize: 11, color: C.dim, letterSpacing: "0.14em", marginBottom: 16 }}>YOUR QUOTE</div>

              <div style={{ display: "flex", alignItems: "baseline", gap: 16, padding: "18px 0", borderBottom: `1px solid ${C.line}` }}>
                <div style={{ fontFamily: C.mono, fontSize: 11, color: C.dim, letterSpacing: "0.14em", minWidth: 100 }}>RATE / MILE</div>
                <div style={{
                  fontFamily: C.mono, fontSize: 48, color: C.text, fontWeight: 500,
                  minHeight: 56, flex: 1,
                  borderBottom: localTime % 1 > 0.5 && typed < 4 ? `2px solid ${C.accent}` : `2px solid transparent`,
                }}>
                  {typedStr}<span style={{ color: C.accent, opacity: localTime % 1 > 0.5 && typed === 4 ? 1 : 0 }}>|</span>
                </div>
              </div>

              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginTop: 18 }}>
                <SmallStat label="LINEHAUL"    v={typed === 4 ? "$4,672" : "—"} />
                <SmallStat label="FUEL SURCH." v={typed === 4 ? "Included" : "—"} />
                <SmallStat label="GROSS MARGIN" v={typed === 4 ? "$1,072" : "—"} color={C.ok} />
                <SmallStat label="GM %"         v={typed === 4 ? "22.9%"  : "—"} color={C.ok} />
              </div>

              {/* Send button */}
              {localTime > 4.5 && (
                <div style={{ marginTop: 22, display: "flex", gap: 8, opacity: ease((localTime - 4.5) / 0.4) }}>
                  <button style={{ padding: "10px 18px", background: C.bg2, border: `1px solid ${C.lineStrong}`, color: C.text, borderRadius: 4, fontFamily: C.sans, fontSize: 13 }}>Save draft</button>
                  <button style={{ padding: "10px 22px", background: C.accent, border: `1px solid ${C.accent}`, color: "#fff", borderRadius: 4, fontFamily: C.sans, fontSize: 13, fontWeight: 600 }}>Send quote to Walmart</button>
                </div>
              )}
            </div>
          </FadeUp>

          {/* Right: lane data (DAT board + history) */}
          <FadeUp delay={0.5} dur={0.4}>
            <div style={{ background: C.bg1, border: `1px solid ${C.line}`, borderRadius: 6, padding: 18 }}>
              <div style={{ fontFamily: C.mono, fontSize: 11, color: C.dim, letterSpacing: "0.14em", marginBottom: 14 }}>LANE INTELLIGENCE</div>
              <Row k="DAT 7d MEDIAN"   v="$2.84 / mi" />
              <Row k="DAT TREND"        v="+6% wk-over-wk" />
              <Row k="OUR LAST BOOKED"  v="$3.55 (4/18)" />
              <Row k="L/T RATIO"        v="4.2 · tight"  warn />
              <Row k="WEATHER"          v="moderate · OH/PA storms" warn />
              <div style={{ marginTop: 14, paddingTop: 14, borderTop: `1px solid ${C.line}` }}>
                <Row k="WALMART PAID 4/18" v="$3.55 · same lane" hi />
                <Row k="TARGET PAYS"       v="$3.85 same lane" hi />
              </div>
            </div>

            {/* Subtle AI nudge */}
            {localTime > 3.2 && (
              <div style={{ marginTop: 12, padding: "10px 14px", background: C.accentBg, borderLeft: `2px solid ${C.accent}`, borderRadius: 3, fontSize: 13, color: C.text, opacity: ease((localTime - 3.2) / 0.4) }}>
                <span style={{ fontFamily: C.mono, fontSize: 10, color: C.accent, letterSpacing: "0.14em", marginRight: 8 }}>KEELWAY</span>
                $3.02 sits at the 72% win-probability mark. Looks right.
              </div>
            )}
          </FadeUp>
        </div>
      </div>
    </AppShell>
  );
}

function SmallStat({ label, v, color }) {
  return (
    <div>
      <div style={{ fontFamily: C.mono, fontSize: 10, color: C.dim, letterSpacing: "0.14em" }}>{label}</div>
      <div style={{ fontFamily: C.mono, fontSize: 18, color: color || C.text, fontWeight: 500, marginTop: 3 }}>{v}</div>
    </div>
  );
}
function Row({ k, v, warn, hi }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", padding: "6px 0", fontSize: 13 }}>
      <span style={{ color: C.dim, fontFamily: C.mono, fontSize: 11, letterSpacing: "0.08em" }}>{k}</span>
      <span style={{ color: warn ? C.warn : hi ? C.accent : C.text, fontFamily: C.mono, fontSize: 12, fontWeight: hi ? 600 : 400 }}>{v}</span>
    </div>
  );
}

/* ============================================================
   SCENE 5 — Posted to load boards · carrier replies pour in (signature)
   ============================================================ */
function ScenePost() {
  const { localTime } = useSprite();
  return (
    <AppShell active="Carrier Match" subtitle={["COMMERCE", "Cover · KW-48218"]}>
      <div style={{ padding: 28 }}>
        <FadeUp delay={0} dur={0.3}>
          <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 14 }}>
            <div style={{ fontSize: 22, fontWeight: 600, color: C.text }}>Cover · KW-48218 · Dallas → Newark</div>
            <Chip kind="ok">POSTED · DAT · TRUCKSTOP</Chip>
            <span style={{ fontFamily: C.mono, fontSize: 13, color: C.dim, marginLeft: "auto" }}>
              elapsed {Math.floor(localTime * 12).toString().padStart(2, "0")}:{Math.floor((localTime * 60) % 60).toString().padStart(2, "0")}
            </span>
          </div>
        </FadeUp>

        {/* The keel — replies pour in, then get triaged */}
        <div style={{ background: C.bg1, border: `1px solid ${C.line}`, borderRadius: 6, position: "relative", minHeight: 540 }}>
          {/* Header */}
          <div style={{ padding: "12px 16px", borderBottom: `1px solid ${C.line}`, display: "flex", alignItems: "center", gap: 14 }}>
            <span style={{ fontFamily: C.mono, fontSize: 11, color: C.dim, letterSpacing: "0.14em" }}>CARRIER REPLIES</span>
            <span style={{ fontFamily: C.mono, fontSize: 14, color: C.text, fontWeight: 500 }}>
              {Math.min(42, Math.floor(localTime * 6))}
            </span>
            {localTime > 4.5 && (
              <span style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 10 }}>
                <Chip kind="accent" pulse>KEELWAY TRIAGE</Chip>
                <span style={{ fontFamily: C.mono, fontSize: 11, color: C.dim }}>FMCSA · MARKET · RATE</span>
              </span>
            )}
          </div>

          {/* Replies — phase 1: pour in chronologically (0-4.5s), phase 2: triaged + ranked (4.5+) */}
          <div style={{ padding: 14 }}>
            {generateReplies(38).map((r, i) => {
              // Phase logic
              const arriveDelay = (i / 38) * 4.2;
              const arrived = localTime > arriveDelay;
              if (!arrived) return null;
              const rankRevealStart = 4.5;
              const ranked = localTime > rankRevealStart;

              const accepted = r.rank > 0;
              const rejected = r.rank === 0;

              // In ranked phase, top 5 align to the keel at the top, rest fade
              if (ranked && rejected) {
                const fadeT = Math.min(1, (localTime - rankRevealStart) / 1.0);
                if (fadeT >= 1) return null;
                return <ReplyChip key={i} r={r} dim opacity={1 - fadeT} />;
              }

              if (ranked && accepted) {
                // Slide to its keel position
                return <ReplyChipRanked key={i} r={r} localTime={localTime - rankRevealStart} />;
              }

              return <ReplyChip key={i} r={r} />;
            })}

            {localTime > 7.0 && (
              <div style={{ marginTop: 18, padding: 14, background: C.accentBg, borderLeft: `3px solid ${C.accent}`, borderRadius: 3, opacity: ease((localTime - 7.0) / 0.4), display: "flex", alignItems: "center", gap: 12 }}>
                <span style={{ fontFamily: C.mono, fontSize: 10, color: C.accent, letterSpacing: "0.14em" }}>KEELWAY</span>
                <span style={{ fontSize: 14, color: C.text }}>Best <b>5 carriers</b> ranked along the keel. Trust score · rate · lane history. <span style={{ color: C.dim }}>Press</span> <kbd style={{ fontFamily: C.mono, fontSize: 11, background: C.bg2, padding: "2px 6px", borderRadius: 3, border: `1px solid ${C.line}` }}>A</kbd> <span style={{ color: C.dim }}>to accept #1.</span></span>
              </div>
            )}
          </div>
        </div>
      </div>
    </AppShell>
  );
}

function ReplyChip({ r, dim, opacity = 1 }) {
  return (
    <div style={{
      display: "inline-block",
      margin: 4,
      padding: "8px 12px",
      background: C.bg2,
      border: `1px solid ${C.line}`,
      borderRadius: 3,
      fontFamily: C.mono,
      fontSize: 11,
      color: dim ? C.faint : C.text,
      opacity,
      transition: "opacity 0.4s",
    }}>
      <span style={{ color: dim ? C.faint : C.text, fontWeight: 500 }}>{r.carrier}</span>
      <span style={{ color: dim ? C.faint : C.dim, margin: "0 8px" }}>·</span>
      <span style={{ color: dim ? C.faint : C.dim }}>MC# {r.mc}</span>
      <span style={{ color: dim ? C.faint : C.dim, margin: "0 8px" }}>·</span>
      <span style={{ color: dim ? C.faint : C.text }}>${r.rate}</span>
      {dim && <span style={{ marginLeft: 8, fontSize: 9, color: C.faint, letterSpacing: "0.1em" }}>REJECTED</span>}
    </div>
  );
}

function ReplyChipRanked({ r, localTime }) {
  // top 5 slide to ranked positions
  const t = ease(Math.min(1, localTime / 1.2));
  return (
    <div style={{
      display: "flex", alignItems: "center", gap: 14,
      margin: "6px 0",
      padding: "10px 14px",
      background: r.rank === 1 ? C.accentBg : C.bg1,
      border: `1px solid ${r.rank === 1 ? C.accent : C.line}`,
      borderLeft: `3px solid ${r.rank === 1 ? C.accent : C.lineStrong}`,
      borderRadius: 3,
      transform: `translateY(${(1 - t) * -8}px)`,
      opacity: t,
    }}>
      <span style={{ fontFamily: C.mono, fontSize: 18, color: C.accent, fontWeight: 700, minWidth: 30 }}>#{r.rank}</span>
      <span style={{ fontFamily: C.mono, fontSize: 13, color: C.text, fontWeight: 500, minWidth: 220 }}>{r.carrier}</span>
      <span style={{ fontFamily: C.mono, fontSize: 11, color: C.dim, minWidth: 110 }}>MC#{r.mc}</span>
      <span style={{ fontFamily: C.mono, fontSize: 11, color: C.dim, minWidth: 90 }}>{r.lane}</span>
      <span style={{ fontFamily: C.mono, fontSize: 13, color: C.text, marginLeft: "auto" }}>${r.rate}</span>
      <span style={{ fontFamily: C.mono, fontSize: 11, color: C.dim }}>{r.pct}%</span>
      <Chip kind="ok">TRUST {r.trust}</Chip>
    </div>
  );
}

function generateReplies(n) {
  const carriers = [
    ["Western Mountain Trans", "748291", 2920, 76, "DAL→EWR", 96],
    ["BluePeak Carriers",      "682144", 2950, 77, "DAL→EWR", 94],
    ["Gearhart Hauling",       "892156", 2980, 77, "DAL→EWR", 91],
    ["Coastal Freight",        "998121", 3020, 78, "DAL→EWR", 88],
    ["Hidalgo Logistics",      "441887", 3080, 80, "DAL→EWR", 86],
    ["Bridgeport Line",        "738222", 3680, 95, "—", 0],
    ["Quarry Ridge",           "287443", 3140, 81, "—", 0],
    ["Pacific Arc Freight",    "759001", 3580, 93, "—", 0],
    ["Sand Creek Logistics",   "412889", 3540, 91, "—", 0],
    ["Anvil Road Co.",         "993127", 3140, 81, "—", 0],
    ["Copper Canyon",          "147002", 2840, 73, "—", 0],
    ["Chesapeake Transit",     "772038", 2660, 69, "—", 0],
    ["Cascade Reefer Group",   "882013", 3580, 93, "—", 0],
    ["Flintlock Motor Lines",  "102557", 3180, 83, "—", 0],
    ["Longhorn Motor Lines",   "506714", 3260, 85, "—", 0],
    ["High Plains Transit",    "802334", 2620, 68, "—", 0],
    ["Riverfork Transit",      "468220", 3460, 91, "—", 0],
    ["Sierra Vista Freight",   "498750", 3320, 86, "—", 0],
    ["Great Basin Express",    "714220", 2780, 72, "—", 0],
    ["Lake Effect Logistics",  "255408", 3220, 84, "—", 0],
    ["Pinecone Hauling",       "441002", 2980, 77, "—", 0],
    ["Eastern Star",           "228841", 3020, 78, "—", 0],
    ["Heartland Hauling",      "998001", 2920, 76, "—", 0],
    ["Pinehurst Carriers",     "515902", 3180, 83, "—", 0],
    ["Midland Haulers",        "612540", 3400, 88, "—", 0],
    ["Cold Chain Logistics",   "445821", 3220, 84, "—", 0],
    ["Summit Pass Trucking",   "702998", 3120, 81, "—", 0],
    ["Hudson Valley Lines",    "856114", 3420, 89, "—", 0],
    ["Ozark Line",             "421789", 2820, 73, "—", 0],
    ["Blackwater Carriers",    "381602", 2980, 77, "—", 0],
    ["Frontier Hauling",       "276811", 3340, 87, "—", 0],
    ["Big Sky Carriers",       "198345", 3180, 83, "—", 0],
    ["Newark Line Express",    "671284", 3060, 80, "—", 0],
    ["Harbor Star Trucking",   "559018", 3440, 89, "—", 0],
    ["Old Dominion Reefer",    "911257", 3260, 85, "—", 0],
    ["Pioneer Grain",          "281034", 3320, 86, "—", 0],
    ["Meridian Transit",       "340122", 3280, 85, "—", 0],
    ["Eastwind Transit",       "555031", 3060, 80, "—", 0],
  ];
  return carriers.slice(0, n).map((c, i) => ({
    rank: i < 5 ? i + 1 : 0,
    carrier: c[0],
    mc: c[1],
    rate: c[2],
    pct: c[3],
    lane: c[4],
    trust: c[5],
  }));
}

/* ============================================================
   SCENE 6 — Book the carrier (one keystroke)
   ============================================================ */
function SceneBook() {
  const { localTime } = useSprite();
  return (
    <AppShell active="Carrier Match" subtitle={["COMMERCE", "Cover · KW-48218"]}>
      <div style={{ padding: 28 }}>
        <FadeUp delay={0} dur={0.3}>
          <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 14 }}>
            <div style={{ fontSize: 22, fontWeight: 600, color: C.text }}>Best 5 along the keel · KW-48218</div>
            <span style={{ marginLeft: "auto", fontFamily: C.mono, fontSize: 11, color: C.dim }}>
              <kbd style={{ fontFamily: C.mono, background: C.bg2, padding: "2px 6px", borderRadius: 3, border: `1px solid ${C.line}` }}>J/K</kbd> navigate &nbsp;
              <kbd style={{ fontFamily: C.mono, background: C.bg2, padding: "2px 6px", borderRadius: 3, border: `1px solid ${C.line}` }}>A</kbd> accept &nbsp;
              <kbd style={{ fontFamily: C.mono, background: C.bg2, padding: "2px 6px", borderRadius: 3, border: `1px solid ${C.line}` }}>C</kbd> counter
            </span>
          </div>
        </FadeUp>

        {/* The 5 carriers */}
        <div>
          {[
            { rank: 1, carrier: "Western Mountain Trans", mc: "748291", rate: 2920, trust: 96, base: "Salt Lake City, UT", lanes: 14, ot: 98.4 },
            { rank: 2, carrier: "BluePeak Carriers",      mc: "682144", rate: 2950, trust: 94, base: "Boise, ID",          lanes: 8,  ot: 96.1 },
            { rank: 3, carrier: "Gearhart Hauling",       mc: "892156", rate: 2980, trust: 91, base: "Chicago, IL",        lanes: 5,  ot: 92.0 },
            { rank: 4, carrier: "Coastal Freight",        mc: "998121", rate: 3020, trust: 88, base: "Long Beach, CA",     lanes: 3,  ot: 94.3 },
            { rank: 5, carrier: "Hidalgo Logistics",      mc: "441887", rate: 3080, trust: 86, base: "Laredo, TX",         lanes: 6,  ot: 91.0 },
          ].map((c, i) => {
            const op = ease(Math.max(0, (localTime - 0.2 - i * 0.08) / 0.3));
            const selected = c.rank === 1;
            const expanded = selected && localTime > 1.6;
            return (
              <div key={i} style={{
                background: selected ? C.accentBg : C.bg1,
                border: `1px solid ${selected ? C.accent : C.line}`,
                borderLeft: `4px solid ${selected ? C.accent : C.lineStrong}`,
                borderRadius: 4,
                marginBottom: 10,
                opacity: op,
                overflow: "hidden",
                transition: "all 0.3s",
              }}>
                <div style={{ display: "flex", alignItems: "center", gap: 18, padding: "14px 18px" }}>
                  <span style={{ fontFamily: C.mono, fontSize: 22, color: C.accent, fontWeight: 700, minWidth: 30 }}>#{c.rank}</span>
                  <div style={{ minWidth: 260 }}>
                    <div style={{ fontSize: 15, color: C.text, fontWeight: 500 }}>{c.carrier}</div>
                    <div style={{ fontFamily: C.mono, fontSize: 11, color: C.dim }}>MC#{c.mc} · {c.base}</div>
                  </div>
                  <Chip kind="ok">TRUST {c.trust}</Chip>
                  <span style={{ fontFamily: C.mono, fontSize: 12, color: C.dim }}>{c.lanes} prior · OT {c.ot}%</span>
                  <span style={{ fontFamily: C.mono, fontSize: 17, color: C.text, fontWeight: 500, marginLeft: "auto" }}>${c.rate.toLocaleString()}</span>
                </div>

                {expanded && (
                  <div style={{ borderTop: `1px solid ${C.accent}`, padding: "16px 18px", background: C.bg1, opacity: ease((localTime - 1.6) / 0.4) }}>
                    <div style={{ fontFamily: C.mono, fontSize: 10, color: C.dim, letterSpacing: "0.14em", marginBottom: 8 }}>DRAFT REPLY · IN MAYA'S VOICE</div>
                    <div style={{ fontSize: 14, color: C.text, lineHeight: 1.6 }}>
                      Marco — confirmed. $2,920 firm. PU Walmart DC #1142 Dallas, 5/26 06:00. Trailer must be food-grade swept. Rate con + dispatch sheet attached. — MO
                    </div>
                    {localTime > 2.8 && (
                      <div style={{ marginTop: 14, display: "flex", gap: 8, opacity: ease((localTime - 2.8) / 0.3) }}>
                        <button style={{ padding: "8px 16px", background: C.bg2, border: `1px solid ${C.lineStrong}`, color: C.text, borderRadius: 4, fontFamily: C.sans, fontSize: 13 }}>Edit reply</button>
                        <button style={{ padding: "8px 20px", background: C.accent, border: `1px solid ${C.accent}`, color: "#fff", borderRadius: 4, fontFamily: C.sans, fontSize: 13, fontWeight: 600 }}>
                          ✓ Send · A
                        </button>
                      </div>
                    )}
                  </div>
                )}
              </div>
            );
          })}
        </div>

        {localTime > 4.4 && (
          <div style={{ marginTop: 16, padding: 14, background: C.okBg, border: `1px solid ${C.ok}`, borderRadius: 4, fontSize: 14, color: C.text, opacity: ease((localTime - 4.4) / 0.4), display: "flex", alignItems: "center", gap: 12 }}>
            <Chip kind="ok">BOOKED</Chip>
            <span><b>Western Mountain</b> confirmed at <b>$2,920</b>. Rate con + dispatch sheet sent. Maya saved <b>$130</b> vs. target.</span>
          </div>
        )}
      </div>
    </AppShell>
  );
}

/* ============================================================
   SCENE 7 — Dispatch + AI quietly runs the check call
   ============================================================ */
function SceneDispatch() {
  const { localTime } = useSprite();
  return (
    <AppShell active="Dispatch" subtitle={["OPS", "Dispatch & Track"]}>
      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", height: "100%" }}>
        {/* Map */}
        <div style={{
          background: C.bg0, position: "relative", overflow: "hidden",
          backgroundImage: `repeating-linear-gradient(0deg, ${C.line} 0 1px, transparent 1px 60px), repeating-linear-gradient(90deg, ${C.line} 0 1px, transparent 1px 60px)`,
        }}>
          {/* US outline */}
          <svg viewBox="0 0 100 80" preserveAspectRatio="none" style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
            <path d="M5,30 Q10,10 30,12 Q55,8 70,15 Q90,18 95,35 Q92,55 80,65 Q60,75 40,72 Q15,68 8,55 Z" stroke={C.lineStrong} strokeDasharray="2 3" fill="none" strokeWidth="0.4" />
            {/* Route from Dallas to Newark */}
            <path d="M38,55 Q58,45 80,32" stroke={C.accent} strokeWidth="0.5" fill="none" strokeDasharray="1.5 1" />
          </svg>

          {/* Origin */}
          <div style={{ position: "absolute", left: "38%", top: "55%", transform: "translate(-50%, -50%)" }}>
            <div style={{ width: 12, height: 12, background: C.faint, borderRadius: "50%", border: `2px solid ${C.bg1}` }} />
            <div style={{ position: "absolute", left: 16, top: -4, fontFamily: C.mono, fontSize: 11, color: C.dim, whiteSpace: "nowrap" }}>DALLAS</div>
          </div>
          {/* Destination */}
          <div style={{ position: "absolute", left: "80%", top: "32%", transform: "translate(-50%, -50%)" }}>
            <div style={{ width: 12, height: 12, background: C.ok, borderRadius: "50%", border: `2px solid ${C.bg1}` }} />
            <div style={{ position: "absolute", right: 16, top: -4, fontFamily: C.mono, fontSize: 11, color: C.dim, whiteSpace: "nowrap" }}>NEWARK</div>
          </div>
          {/* Moving truck */}
          {(() => {
            const p = clamp(localTime / 6, 0, 0.7);
            const x = 38 + (80 - 38) * p;
            const y = 55 + (32 - 55) * p;
            return (
              <div style={{ position: "absolute", left: `${x}%`, top: `${y}%`, transform: "translate(-50%, -50%)" }}>
                <div style={{
                  width: 18, height: 18, background: C.accent, borderRadius: "50%",
                  border: `3px solid ${C.bg1}`,
                  boxShadow: `0 0 0 6px ${C.accentBg}, 0 0 20px ${C.accent}`,
                }} />
                <div style={{
                  position: "absolute", left: 24, top: -22, padding: "4px 10px",
                  background: C.bg1, border: `1px solid ${C.accent}`, borderRadius: 4,
                  fontFamily: C.mono, fontSize: 11, color: C.text, whiteSpace: "nowrap",
                }}>
                  KW-48218 · M. VELASQUEZ
                </div>
              </div>
            );
          })()}

          <div style={{ position: "absolute", left: 20, bottom: 20, fontFamily: C.mono, fontSize: 11, color: C.dim, letterSpacing: "0.1em" }}>
            GPS · UPDATED 13:00:42 · ETA 05/28 13:48 ET (-12 MIN)
          </div>
        </div>

        {/* Right side — AI handling check call quietly */}
        <div style={{ background: C.bg1, borderLeft: `1px solid ${C.line}`, padding: 22, overflowY: "hidden" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}>
            <Chip kind="accent" pulse>AI HANDLING · CHECK-IN</Chip>
            <span style={{ fontFamily: C.mono, fontSize: 11, color: C.dim, marginLeft: "auto" }}>00:38</span>
          </div>

          <div style={{ fontFamily: C.mono, fontSize: 11, color: C.dim, letterSpacing: "0.14em", marginBottom: 10 }}>TRANSCRIPT</div>
          {[
            { who: "ai",     t: 0.4, said: "Hey Marco — Maya from Keelway checking in on the Dallas → Newark." },
            { who: "driver", t: 1.4, said: "Yeah, all good. Just past Memphis." },
            { who: "ai",     t: 2.4, said: "Nice. Still on track for Wednesday 14:00 delivery?" },
            { who: "driver", t: 3.6, said: "Should be there 13:30, ahead of schedule." },
            { who: "ai",     t: 4.6, said: "Great. I'll let receiving know. Drive safe.", live: true },
          ].map((turn, i) => {
            if (localTime < turn.t) return null;
            const op = ease(Math.min(1, (localTime - turn.t) / 0.3));
            return (
              <div key={i} style={{
                display: "grid", gridTemplateColumns: "70px 1fr", gap: 10, padding: "5px 0",
                opacity: op, transform: `translateY(${(1 - op) * 4}px)`,
              }}>
                <div style={{ fontFamily: C.mono, fontSize: 10, color: turn.who === "ai" ? C.accent : C.blue, letterSpacing: "0.14em", paddingTop: 3 }}>
                  {turn.who === "ai" ? "KEELWAY" : "DRIVER"}
                </div>
                <div style={{ fontSize: 13, color: C.text, lineHeight: 1.55 }}>
                  {turn.said}
                  {turn.live && <Chip kind="danger" pulse>SPEAKING</Chip>}
                </div>
              </div>
            );
          })}

          {localTime > 5.5 && (
            <div style={{ marginTop: 18, padding: 12, background: C.bg2, border: `1px solid ${C.line}`, borderRadius: 4, opacity: ease((localTime - 5.5) / 0.4) }}>
              <div style={{ fontFamily: C.mono, fontSize: 10, color: C.dim, letterSpacing: "0.14em", marginBottom: 6 }}>UPDATED IN TMS</div>
              <div style={{ fontSize: 13, color: C.text, lineHeight: 1.6 }}>
                ✓ Status: ON TRACK<br/>
                ✓ ETA pulled forward 12 min → 13:48 ET<br/>
                ✓ Receiver notified via portal
              </div>
            </div>
          )}

          {localTime > 6.3 && (
            <div style={{ marginTop: 14, padding: 10, fontSize: 12, color: C.dim, fontStyle: "italic", opacity: ease((localTime - 6.3) / 0.4) }}>
              Meanwhile, Maya is on the phone with Costco about the Q3 RFP.
            </div>
          )}
        </div>
      </div>
    </AppShell>
  );
}

/* ============================================================
   SCENE 8 — Delivered + POD + invoiced
   ============================================================ */
function ScenePOD() {
  const { localTime } = useSprite();
  return (
    <AppShell active="Load Board" subtitle={["OPS", "KW-48218"]}>
      <div style={{ padding: 32 }}>
        <FadeUp delay={0} dur={0.3}>
          <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 18 }}>
            <Chip kind="ok">DELIVERED · 13:42 ET</Chip>
            <div style={{ fontSize: 24, fontWeight: 600, color: C.text }}>KW-48218 · Dallas → Newark · CLOSED</div>
          </div>
        </FadeUp>

        <div style={{ display: "grid", gridTemplateColumns: "320px 1fr", gap: 22 }}>
          {/* Fake POD */}
          <FadeUp delay={0.3} dur={0.5}>
            <div style={{
              background: "#FCFCFA",
              color: "#222",
              padding: 20,
              borderRadius: 4,
              boxShadow: "0 4px 24px rgba(0,0,0,0.18)",
              transform: "rotate(-1.5deg)",
              fontFamily: "Georgia, serif",
              fontSize: 11,
              lineHeight: 1.5,
            }}>
              <div style={{ fontSize: 16, fontWeight: 700, borderBottom: "1px solid #aaa", paddingBottom: 6 }}>PROOF OF DELIVERY</div>
              <div style={{ marginTop: 10 }}><b>Walmart DC #2204</b><br/>5300 Avenue D, Newark NJ</div>
              <div style={{ marginTop: 10 }}>BOL: KW-48218<br/>Delivered: 05/28 13:42 ET<br/>Received by: J. RIVERA</div>
              <div style={{
                marginTop: 22, padding: 14, background: "#FAF6E8",
                fontFamily: "Brush Script MT, cursive", fontSize: 24, color: "#1a3a5c",
                borderTop: "1px dashed #aaa",
              }}>J. Rivera</div>
              <div style={{ fontSize: 9, color: "#666", marginTop: 4 }}>Signed · captured via driver phone</div>
            </div>
          </FadeUp>

          {/* Settlement card */}
          <div>
            <FadeUp delay={0.6} dur={0.4}>
              <div style={{ background: C.bg1, border: `1px solid ${C.line}`, borderRadius: 6, padding: 22 }}>
                <div style={{ fontFamily: C.mono, fontSize: 11, color: C.dim, letterSpacing: "0.14em", marginBottom: 16 }}>LOAD CLOSEOUT</div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 14 }}>
                  <SmallStat label="REVENUE"      v="$4,672" />
                  <SmallStat label="CARRIER PAY"  v="$2,920" />
                  <SmallStat label="GROSS MARGIN" v="$1,752" color={C.ok} />
                  <SmallStat label="GM %"         v="37.5%" color={C.ok} />
                  <SmallStat label="ON-TIME"      v="✓ +12 MIN" color={C.ok} />
                  <SmallStat label="DETENTION"    v="$0" />
                </div>

                <div style={{ marginTop: 18, paddingTop: 16, borderTop: `1px solid ${C.line}` }}>
                  {[
                    { t: "13:42", what: "POD captured + auto-parsed from driver phone", delay: 1.4 },
                    { t: "13:43", what: "Invoice INV-241218 generated · sent to Walmart AP", delay: 1.9 },
                    { t: "13:44", what: "Western Mountain queued for Friday settlement", delay: 2.4 },
                  ].map((r, i) => {
                    const op = ease(Math.max(0, (localTime - r.delay) / 0.3));
                    return (
                      <div key={i} style={{ display: "grid", gridTemplateColumns: "60px 14px 1fr", gap: 10, padding: "6px 0", opacity: op, alignItems: "center" }}>
                        <span style={{ fontFamily: C.mono, fontSize: 11, color: C.dim }}>{r.t}</span>
                        <span style={{ color: C.ok, fontFamily: C.mono }}>✓</span>
                        <span style={{ fontSize: 13, color: C.text }}>{r.what}</span>
                      </div>
                    );
                  })}
                </div>
              </div>
            </FadeUp>
          </div>
        </div>
      </div>
    </AppShell>
  );
}

/* ============================================================
   SCENE 9 — EOD wrap
   ============================================================ */
function SceneOutro() {
  const { localTime } = useSprite();
  const stats = [
    { label: "LOADS COVERED",    end: 14,    suffix: "" },
    { label: "GM TODAY",         end: 48210, prefix: "$" },
    { label: "AVG MARGIN",       end: 18.4,  suffix: "%", decimals: 1 },
    { label: "ON-TIME",          end: 98.4,  suffix: "%", decimals: 1 },
  ];
  return (
    <div style={{ position: "absolute", inset: 0, background: C.bg0, padding: 56, display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center" }}>
      <FadeUp dur={0.5}>
        <div style={{ fontFamily: C.mono, fontSize: 13, color: C.accent, letterSpacing: "0.42em", textTransform: "uppercase", textAlign: "center", marginBottom: 16 }}>
          End of Day · Monday 05/26
        </div>
        <div style={{ fontFamily: C.sans, fontSize: 60, fontWeight: 600, color: C.text, textAlign: "center", letterSpacing: "-0.02em", lineHeight: 1.15 }}>
          Maya covered 14 loads.<br/>Lunch was hot for once.
        </div>
      </FadeUp>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 24, marginTop: 56, maxWidth: 1400, width: "100%" }}>
        {stats.map((s, i) => {
          const t = ease(Math.max(0, (localTime - 0.8 - i * 0.15) / 1.0));
          const v = s.end * t;
          const fmt = s.decimals ? v.toFixed(s.decimals) : (s.prefix === "$" ? Math.floor(v).toLocaleString() : Math.floor(v).toString());
          return (
            <div key={i} style={{ background: C.bg1, border: `1px solid ${C.line}`, borderLeft: `3px solid ${C.accent}`, borderRadius: 6, padding: 22 }}>
              <div style={{ fontFamily: C.mono, fontSize: 11, color: C.dim, letterSpacing: "0.18em", textTransform: "uppercase" }}>{s.label}</div>
              <div style={{ fontFamily: C.mono, fontSize: 44, color: C.text, fontWeight: 500, marginTop: 8 }}>
                {s.prefix || ""}{fmt}{s.suffix || ""}
              </div>
            </div>
          );
        })}
      </div>

      <FadeUp delay={2.2} dur={0.5} style={{ marginTop: 32 }}>
        <div style={{
          padding: "14px 22px", background: C.accentBg, borderLeft: `3px solid ${C.accent}`, borderRadius: 4,
          fontFamily: C.sans, fontSize: 16, color: C.text, maxWidth: 980, textAlign: "center",
        }}>
          <span style={{ fontFamily: C.mono, fontSize: 11, color: C.accent, letterSpacing: "0.14em", marginRight: 10 }}>KEELWAY</span>
          handled 312 background tasks today — check-calls, claim filings, RFP pricing, fraud blocks. So Maya could close 14 loads instead of 7.
        </div>
      </FadeUp>

      <FadeUp delay={3.0} dur={0.5} style={{ marginTop: 36 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
          <div style={{ width: 50, height: 50, borderRadius: 10, background: `linear-gradient(135deg, ${C.accent}, ${C.accentDim})`, display: "grid", placeItems: "center", fontFamily: C.mono, fontSize: 28, fontWeight: 700, color: "#fff" }}>K</div>
          <div>
            <div style={{ fontFamily: C.mono, fontSize: 14, letterSpacing: "0.32em", color: C.accent, textTransform: "uppercase" }}>Keelway</div>
            <div style={{ fontFamily: C.sans, fontSize: 22, color: C.text, marginTop: 2 }}>The spine of a modern freight brokerage.</div>
          </div>
        </div>
      </FadeUp>
    </div>
  );
}

/* ============================================================
   SCENE — Integrations spine (penultimate)
   ============================================================ */
function SceneIntegrations() {
  const { localTime } = useSprite();
  const inbound = [
    { name: "DAT One",          logo: { l: "DAT", c: "#FFF",    bg: "#E03C31" }, label: "loads + capacity" },
    { name: "Highway",          logo: { l: "H",   c: "#FBBF24", bg: "#1A1A1A" }, label: "carrier identity" },
    { name: "MacroPoint",       logo: { l: "MP",  c: "#FFF",    bg: "#003366" }, label: "GPS visibility" },
    { name: "Samsara",          logo: { l: "S",   c: "#FFF",    bg: "#003153" }, label: "ELD · HOS" },
    { name: "RMIS",             logo: { l: "RM",  c: "#FFF",    bg: "#003B71" }, label: "insurance / COI" },
    { name: "SPS Commerce",     logo: { l: "SPS", c: "#FFF",    bg: "#FF6B00" }, label: "EDI 204 / 214" },
    { name: "Twilio",           logo: { l: "Tw",  c: "#FFF",    bg: "#F22F46" }, label: "calls + SMS" },
  ];
  const outbound = [
    { name: "Trucker Tools",    logo: { l: "TT",  c: "#FFF", bg: "#0066CC" }, label: "driver app + POD" },
    { name: "QuickBooks",       logo: { l: "QB",  c: "#FFF", bg: "#2CA01C" }, label: "invoices + bills" },
    { name: "TriumphPay",       logo: { l: "T$",  c: "#FFF", bg: "#1A4480" }, label: "carrier payments" },
    { name: "Apex Capital",     logo: { l: "A",   c: "#FFF", bg: "#0066B2" }, label: "factor NOAs" },
    { name: "Comdata",          logo: { l: "CO",  c: "#FFF", bg: "#E03C31" }, label: "fuel + advances" },
    { name: "Slack",            logo: { l: "S",   c: "#FFF", bg: "#4A154B" }, label: "alerts" },
    { name: "PC*MILER",         logo: { l: "PC",  c: "#FFF", bg: "#1B5E20" }, label: "mileage / routing" },
  ];

  return (
    <div style={{ position: "absolute", inset: 0, background: C.bg0, padding: "50px 60px" }}>
      <FadeUp delay={0} dur={0.4}>
        <div style={{ textAlign: "center", marginBottom: 28 }}>
          <div style={{ fontFamily: C.mono, fontSize: 13, color: C.accent, letterSpacing: "0.32em", textTransform: "uppercase" }}>The Spine</div>
          <div style={{ fontFamily: C.sans, fontSize: 52, fontWeight: 600, color: C.text, marginTop: 12, letterSpacing: "-0.02em", lineHeight: 1.15 }}>
            Plugged into the tools brokers already use.
          </div>
        </div>
      </FadeUp>

      <div style={{ display: "grid", gridTemplateColumns: "300px 1fr 300px", gap: 30, alignItems: "stretch", maxWidth: 1700, margin: "0 auto", minHeight: 580 }}>
        {/* Inbound */}
        <div style={{ display: "flex", flexDirection: "column", gap: 9, justifyContent: "center" }}>
          {inbound.map((i, k) => {
            const delay = 0.4 + k * 0.12;
            const op = ease(Math.max(0, (localTime - delay) / 0.32));
            return (
              <div key={k} style={{
                display: "flex", alignItems: "center", gap: 12,
                padding: "10px 14px",
                background: C.bg1, border: `1px solid ${C.line}`,
                borderLeft: `3px solid ${C.accent}`,
                borderRadius: 3,
                opacity: op, transform: `translateX(${(1 - op) * -16}px)`,
              }}>
                <IntegLogo logo={i.logo} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, color: C.text, fontWeight: 500 }}>{i.name}</div>
                  <div style={{ fontFamily: C.mono, fontSize: 10, color: C.dim, letterSpacing: "0.08em" }}>{i.label}</div>
                </div>
              </div>
            );
          })}
        </div>

        {/* Center: Keelway core with lines */}
        <div style={{ position: "relative", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <svg viewBox="0 0 800 580" preserveAspectRatio="none" style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
            <defs>
              <linearGradient id="in-line" x1="0" y1="0" x2="1" y2="0">
                <stop offset="0" stopColor={C.accent} stopOpacity="0.1" />
                <stop offset="1" stopColor={C.accent} stopOpacity="0.6" />
              </linearGradient>
              <linearGradient id="out-line" x1="0" y1="0" x2="1" y2="0">
                <stop offset="0" stopColor={C.blue} stopOpacity="0.6" />
                <stop offset="1" stopColor={C.blue} stopOpacity="0.1" />
              </linearGradient>
            </defs>
            {inbound.map((_, i) => {
              const y = 50 + i * (480 / inbound.length);
              const op = ease(Math.max(0, (localTime - 0.5 - i * 0.12) / 0.4));
              return <path key={`il${i}`} d={`M0,${y} C260,${y} 280,290 400,290`} stroke="url(#in-line)" strokeWidth="1.6" fill="none" opacity={op} />;
            })}
            {outbound.map((_, i) => {
              const y = 50 + i * (480 / outbound.length);
              const op = ease(Math.max(0, (localTime - 1.4 - i * 0.12) / 0.4));
              return <path key={`ol${i}`} d={`M400,290 C520,290 540,${y} 800,${y}`} stroke="url(#out-line)" strokeWidth="1.6" fill="none" opacity={op} />;
            })}
          </svg>

          <div style={{
            width: 220, height: 220, borderRadius: "50%",
            background: C.bg1,
            border: `3px solid ${C.accent}`,
            display: "grid", placeItems: "center",
            boxShadow: `0 0 0 14px ${C.accentBg}, 0 12px 40px rgba(0,0,0,0.08)`,
            zIndex: 1,
            position: "relative",
            opacity: ease(Math.max(0, localTime / 0.4)),
          }}>
            <div style={{ textAlign: "center" }}>
              <div style={{ width: 60, height: 60, margin: "0 auto", borderRadius: 11, background: `linear-gradient(135deg, ${C.accent}, ${C.accentDim})`, display: "grid", placeItems: "center", color: "#fff", fontFamily: C.mono, fontSize: 32, fontWeight: 700, boxShadow: "0 4px 12px rgba(176,141,87,0.3)" }}>K</div>
              <div style={{ marginTop: 12, fontFamily: C.mono, fontSize: 13, color: C.accent, letterSpacing: "0.22em" }}>KEELWAY</div>
              <div style={{ fontFamily: C.mono, fontSize: 10, color: C.dim, letterSpacing: "0.16em", marginTop: 3 }}>CORE</div>
              <div style={{ marginTop: 10, fontSize: 10, color: C.dim, lineHeight: 1.5 }}>event bus<br/>84 event types</div>
            </div>
          </div>
        </div>

        {/* Outbound */}
        <div style={{ display: "flex", flexDirection: "column", gap: 9, justifyContent: "center" }}>
          {outbound.map((i, k) => {
            const delay = 1.4 + k * 0.12;
            const op = ease(Math.max(0, (localTime - delay) / 0.32));
            return (
              <div key={k} style={{
                display: "flex", alignItems: "center", gap: 12,
                padding: "10px 14px",
                background: C.bg1, border: `1px solid ${C.line}`,
                borderRight: `3px solid ${C.blue}`,
                borderRadius: 3,
                opacity: op, transform: `translateX(${(1 - op) * 16}px)`,
                flexDirection: "row-reverse",
              }}>
                <IntegLogo logo={i.logo} />
                <div style={{ flex: 1, minWidth: 0, textAlign: "right" }}>
                  <div style={{ fontSize: 13, color: C.text, fontWeight: 500 }}>{i.name}</div>
                  <div style={{ fontFamily: C.mono, fontSize: 10, color: C.dim, letterSpacing: "0.08em" }}>{i.label}</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      <FadeUp delay={3.0} dur={0.5} style={{ marginTop: 24 }}>
        <div style={{ textAlign: "center", fontFamily: C.mono, fontSize: 13, color: C.dim, letterSpacing: "0.24em" }}>
          12 CATEGORIES · 41 INTEGRATIONS · 9.2M API CALLS · P50 64ms
        </div>
      </FadeUp>
    </div>
  );
}

function IntegLogo({ logo }) {
  return (
    <div style={{
      width: 34, height: 34, flexShrink: 0,
      borderRadius: 5, background: logo.bg, color: logo.c,
      display: "grid", placeItems: "center",
      fontFamily: C.mono, fontSize: logo.l.length > 2 ? 9 : 14, fontWeight: 700,
      letterSpacing: logo.l.length > 2 ? "0.04em" : "0",
      border: "1px solid rgba(0,0,0,0.06)",
    }}>{logo.l}</div>
  );
}

/* ============================================================
   Master video composition
   ============================================================ */
function BrokerVideoComposition() {
  return (
    <>
      <style>{`
        @keyframes kw-pulse {
          0%   { box-shadow: 0 0 0 0 currentColor; opacity: 1; }
          100% { box-shadow: 0 0 0 8px transparent; opacity: 0.4; }
        }
      `}</style>

      <Sprite start={SCENES.intro[0]}    end={SCENES.intro[1]}>   <SceneIntro /></Sprite>
      <Sprite start={SCENES.morning[0]}  end={SCENES.morning[1]}> <SceneMorning /></Sprite>
      <Sprite start={SCENES.tender[0]}   end={SCENES.tender[1]}>  <SceneTender /></Sprite>
      <Sprite start={SCENES.quote[0]}    end={SCENES.quote[1]}>   <SceneQuote /></Sprite>
      <Sprite start={SCENES.post[0]}     end={SCENES.post[1]}>    <ScenePost /></Sprite>
      <Sprite start={SCENES.book[0]}     end={SCENES.book[1]}>    <SceneBook /></Sprite>
      <Sprite start={SCENES.dispatch[0]} end={SCENES.dispatch[1]}><SceneDispatch /></Sprite>
      <Sprite start={SCENES.pod[0]}      end={SCENES.pod[1]}>     <ScenePOD /></Sprite>
      <Sprite start={SCENES.integ[0]}    end={SCENES.integ[1]}>   <SceneIntegrations /></Sprite>
      <Sprite start={SCENES.outro[0]}    end={SCENES.outro[1]}>   <SceneOutro /></Sprite>

      <Caption start={SCENES.morning[0] + 0.5}  end={SCENES.morning[1] - 0.3}  kicker="06:14 · MONDAY" line="Maya's at her desk. 14 loads to cover today." />
      <Caption start={SCENES.tender[0] + 0.7}   end={SCENES.tender[1] - 0.3}   kicker="INBOUND TENDER" line="Walmart sends an EDI 204. Two clicks to accept." />
      <Caption start={SCENES.quote[0] + 0.5}    end={SCENES.quote[1] - 0.3}    kicker="QUOTE THE LANE" line="DAT says $2.84. Maya quotes $3.02. Confident — the lane data agrees." />
      <Caption start={SCENES.post[0] + 0.5}     end={SCENES.post[1] - 0.3}     kicker="POST + TRIAGE" line="38 carrier replies in 4 minutes. Keelway lines up the best five along the keel." />
      <Caption start={SCENES.book[0] + 0.5}     end={SCENES.book[1] - 0.3}     kicker="BOOK · ONE KEYSTROKE" line='Maya hits "A". Rate con sent. Saved $130 vs. target.' />
      <Caption start={SCENES.dispatch[0] + 0.5} end={SCENES.dispatch[1] - 0.3} kicker="EN ROUTE" line="The 13:00 check-in runs itself while Maya pitches Costco." />
      <Caption start={SCENES.pod[0] + 0.5}      end={SCENES.pod[1] - 0.3}      kicker="DELIVERED · INVOICED" line="POD parsed. Invoice out. The load closes itself." />
      <Caption start={SCENES.integ[0] + 0.5}    end={SCENES.integ[1] - 0.3}    kicker="THE SPINE" line="41 integrations behind every keystroke." />
    </>
  );
}

window.BrokerVideoComposition = BrokerVideoComposition;
