// pay-with-fina/scenes.jsx — smart-animate through Pay-with-Fina frames 1→5.
// One device canvas, persistent dark surface, elements morph in-place.
//
// Frame timeline (~22s):
//   0.0–4.5    F1  "Fina – standing by / Pay with Fina" + dashed dropzone "Drop your invoice"
//                  Cloud-upload icon + invoice document descends into the dropzone.
//   4.5–9.5    F2  Header → "Paying supplier now... / 1/1 Invoice Approved"
//                  Body → invoice document card (line items + SAR 48,000 amount due)
//                  Glass pills "SAR 34,000" + "Invoice Submitted" appear.
//   9.5–14.0   F3  Header morphs → "Invoice Paid with Fina / Payment Complete – SAR 34,000"
//                  Body morphs → 2 stacked: "Goods ships to Merchant" row + Merchant-repays terms
//                  Cursor selects "Pay in 60 days" pill (60 selected = white border).
//   14.0–18.0  F4  Goods-ships row promotes to header (Fina header morphs to supplier).
//                  Body collapses to terms only with 60-day SELECTED (lime + check).
//                  Footer card slides in: "Merchant Pay in 60 days / Awaiting repayment on terms"
//   18.0–22.0  F5  Stack collapses; dark surface fills; concentric rings + sparkle pulse;
//                  "Pay with Fina" wordmark + "Invoices: 16, +6.5%" glass stat card.
//
// Geometry mirrors Figma (755.34 × 503.89). Rendered at 2× scale, centered.

const { useTime, Sprite, interpolate: _interpolate, Easing } = window;
const easeOut = Easing.easeOutCubic;
const easeInOut = Easing.easeInOutCubic;
const easeOutBack = Easing.easeOutBack;
const interpolate = (t, keys, outs, ease) => _interpolate(keys, outs, ease)(t);

// ── Light-theme palette ──────────────────────────────────────
const C = {
  stageBg: "#E8EDFB",                       // cream page background
  panel: "#FFFFFF",                         // card surfaces
  panelBorder: "rgba(15,18,28,0.06)",
  productBg: "#F1F4FD",                     // sub-cards inside white surfaces
  white: "rgb(15,18,28)",                   // text on white (formerly white on dark)
  white60: "rgba(15,18,28,0.62)",
  white50: "rgba(15,18,28,0.5)",
  white25: "rgba(15,18,28,0.18)",
  white15: "rgba(15,18,28,0.1)",
  lime: "rgb(31,138,91)",                   // selected accent — darker green for contrast
  glassBg: "rgba(255,255,255,0.92)",
  divider: "rgba(15,18,28,0.08)",
  customerOrderBlue: "rgb(110,138,232)",
  shadow: "0 18px 40px rgba(15,18,28,0.08), 0 2px 6px rgba(15,18,28,0.04)",
};

const SCALE = 2;
const FW = 755.34, FH = 503.89;
const STAGE_W = 1920, STAGE_H = 1080;
const OFFX = (STAGE_W - FW * SCALE) / 2;
const OFFY = (STAGE_H - FH * SCALE) / 2;
const SURF = { x: 152, y: 26, w: 451, h: 453 };

const fx = (x) => OFFX + x * SCALE;
const fy = (y) => OFFY + y * SCALE;

// ── Full-bleed light canvas + camera transform on inner content ─────────
function PageCard({ children, cameraTransform = "", overlay = null }) {
  return (
    <div style={{
      position: "absolute",
      inset: 0,
      backgroundColor: C.stageBg,
      overflow: "hidden",
    }}>
      <div style={{
        position: "absolute",
        left: OFFX, top: OFFY,
        width: FW * SCALE, height: FH * SCALE,
        transform: cameraTransform,
        transformOrigin: "0 0",
        willChange: "transform",
      }}>
        {children}
      </div>
      {overlay}
    </div>
  );
}

// ── Product order card (Letter4 from figma) ─────────────────
function ProductCard({ title, sub, opacity = 1, dy = 0 }) {
  return (
    <div style={{
      position: "absolute",
      left: 20 * SCALE, top: 0,
      width: 315 * SCALE, height: 96 * SCALE,
      borderRadius: 4 * SCALE,
      backgroundColor: C.productBg,
      padding: 20 * SCALE,
      boxSizing: "border-box",
      display: "flex",
      alignItems: "center",
      gap: 20 * SCALE,
      opacity,
      transform: `translateY(${dy}px)`,
    }}>
      <div style={{
        width: 56 * SCALE, height: 56 * SCALE,
        borderRadius: 3.6 * SCALE,
        background: `url(../shared-assets/product-pearl.png) center/cover no-repeat, rgb(232,232,232)`,
        flex: "none",
      }} />
      <div style={{
        display: "flex", flexDirection: "column", gap: 11 * SCALE,
        color: C.white,
        fontFamily: "'SF Pro', system-ui, sans-serif",
      }}>
        <div style={{ fontWeight: 500, fontSize: 22 * SCALE, lineHeight: 1, whiteSpace: "nowrap" }}>{title}</div>
        <div style={{ fontWeight: 300, fontSize: 16 * SCALE, lineHeight: 1, opacity: 0.6, whiteSpace: "nowrap" }}>{sub}</div>
      </div>
    </div>
  );
}

// ── Invoice document (F2 body) ──────────────────────────────
function InvoiceDocument() {
  const W = 357, H = 317;
  const lines = [
    { label: "Pearl Bouquet", qty: "Qty 1", amount: "SAR 24,000" },
    { label: "Color Kraft Paper", qty: "Qty 15", amount: "SAR 6,000" },
    { label: "Floral Tapes", qty: "Qty 20", amount: "SAR 4,000" },
  ];
  return (
    <div style={{
      width: W * SCALE, height: H * SCALE,
      borderRadius: 6 * SCALE,
      backgroundColor: "#EEF2FC",
      padding: 22 * SCALE,
      boxSizing: "border-box",
      fontFamily: "'SF Pro', system-ui, sans-serif",
      color: "#1a1a1a",
      display: "flex", flexDirection: "column",
      position: "relative",
      boxShadow: `0 ${4 * SCALE}px ${20 * SCALE}px rgba(0,0,0,0.25)`,
    }}>
      {/* header */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div>
          <div style={{ fontWeight: 600, fontSize: 22 * SCALE, lineHeight: 1, letterSpacing: -0.5 }}>Invoice</div>
          <div style={{ marginTop: 6 * SCALE, fontWeight: 400, fontSize: 11 * SCALE, opacity: 0.55 }}>#INV-2025-1042 · 21 Oct 2025</div>
        </div>
        <div style={{ textAlign: "right" }}>
          <div style={{ fontWeight: 500, fontSize: 11 * SCALE, opacity: 0.55 }}>Bill to</div>
          <div style={{ marginTop: 4 * SCALE, fontWeight: 500, fontSize: 12 * SCALE }}>Petal &amp; Co.</div>
        </div>
      </div>

      {/* divider */}
      <div style={{ marginTop: 18 * SCALE, height: 1, background: "rgba(0,0,0,0.08)" }} />

      {/* line items */}
      <div style={{ marginTop: 14 * SCALE, display: "flex", flexDirection: "column", gap: 12 * SCALE }}>
        {lines.map((l, i) => (
          <div key={i} style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
            <div>
              <div style={{ fontWeight: 500, fontSize: 13 * SCALE, lineHeight: 1.2 }}>{l.label}</div>
              <div style={{ marginTop: 3 * SCALE, fontWeight: 400, fontSize: 10.5 * SCALE, opacity: 0.5 }}>{l.qty}</div>
            </div>
            <div style={{ fontWeight: 500, fontSize: 12.5 * SCALE, fontVariantNumeric: "tabular-nums" }}>{l.amount}</div>
          </div>
        ))}
      </div>

      {/* dotted spacer */}
      <div style={{ marginTop: 16 * SCALE, height: 1, borderTop: `1px dashed rgba(0,0,0,0.18)` }} />

      {/* total */}
      <div style={{ marginTop: 14 * SCALE, display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
        <div style={{ fontWeight: 500, fontSize: 11 * SCALE, opacity: 0.55, textTransform: "uppercase", letterSpacing: 0.8 }}>Amount due</div>
        <div style={{ fontWeight: 700, fontSize: 24 * SCALE, lineHeight: 1, letterSpacing: -0.6, fontVariantNumeric: "tabular-nums" }}>SAR 34,000</div>
      </div>

      {/* footer note */}
      <div style={{ marginTop: "auto", paddingTop: 14 * SCALE, fontWeight: 400, fontSize: 10 * SCALE, opacity: 0.4, lineHeight: 1.4 }}>
        Net 60 · Thank you for your business
      </div>
    </div>
  );
}

// ── Term pill card ──────────────────────────────────────────
function TermCard({ x, y, label, state = "idle", showCheck = false }) {
  const border = state === "selected" ? `1px solid ${C.lime}` : `1px solid ${C.white25}`;
  const w = 105, h = 86;
  return (
    <div style={{
      position: "absolute",
      left: x * SCALE, top: y * SCALE,
      width: w * SCALE, height: h * SCALE,
      borderRadius: 4 * SCALE,
      border,
      padding: 16 * SCALE,
      boxSizing: "border-box",
      transition: "border-color 0.35s ease",
    }}>
      <div style={{
        fontFamily: "Inter, system-ui, sans-serif",
        fontWeight: 700, fontSize: 12 * SCALE,
        color: C.white, lineHeight: 1.3,
      }}>{label}</div>
      <div style={{
        marginTop: 12 * SCALE,
        display: "flex", alignItems: "center", justifyContent: "space-between",
      }}>
        <div style={{
          fontFamily: "Inter, system-ui, sans-serif",
          fontSize: 12 * SCALE,
          color: C.white, opacity: 0.4, lineHeight: 1.3,
        }}>No fees</div>
        {showCheck ? (
          <svg width={16 * SCALE} height={16 * SCALE} viewBox="0 0 16 16" fill="none">
            <path d="M13.6 4.6L6.2 13 2.4 9.3l1.1-1.1 2.7 2.7 6.5-7.3 0.9 1z" fill={C.lime} />
          </svg>
        ) : null}
      </div>
    </div>
  );
}

// ── Glass info pill (SAR 800, Orders Submitted) ──────────────
// Positioned in PageCard-local coords (no OFFX added).
function GlassPill({ left, top, label, icon, opacity = 1, dy = 0, width = 150 }) {
  return (
    <div style={{
      position: "absolute",
      left: left * SCALE, top: top * SCALE,
      width: width * SCALE, height: 48 * SCALE,
      borderRadius: 8 * SCALE,
      backgroundColor: C.glassBg,
      border: `1px solid ${C.white15}`,
      backdropFilter: "blur(10px)",
      padding: `${12 * SCALE}px`,
      boxSizing: "border-box",
      display: "flex",
      alignItems: "center",
      gap: 12 * SCALE,
      color: C.white,
      fontFamily: "'SF Pro', sans-serif",
      fontWeight: 500, fontSize: 18 * SCALE, lineHeight: 1,
      opacity,
      transform: `translateY(${dy}px)`,
    }}>
      <div style={{ width: 24 * SCALE, height: 24 * SCALE, flex: "none", display: "flex", alignItems: "center", justifyContent: "center" }}>
        {icon}
      </div>
      <span style={{ whiteSpace: "nowrap" }}>{label}</span>
    </div>
  );
}

// ── Sparkle ────────────────────────────────────────────────
function Sparkle({ x, y, size = 18, opacity = 1, rotate = 0 }) {
  return (
    <div style={{
      position: "absolute", left: x, top: y,
      width: size, height: size, opacity,
      transform: `rotate(${rotate}deg)`,
    }}>
      <svg viewBox="0 0 18 18" width={size} height={size}>
        <path d="M9 0 L11 7 L18 9 L11 11 L9 18 L7 11 L0 9 L7 7 Z" fill={C.lime} />
      </svg>
    </div>
  );
}

// ── Cloud-upload icon for the F1 dropzone ───────────────────
function CloudIcon({ size = 84 }) {
  return (
    <svg width={size} height={size * 0.85} viewBox="0 0 84 72" fill="none" stroke={C.white} strokeWidth={2.4} strokeLinecap="round" strokeLinejoin="round" style={{ opacity: 0.55 }}>
      <path d="M62 46c5 0 10-4 10-10 0-6-5-10-10-10-1-9-9-15-17-15-9 0-16 6-17 15h-1c-9 0-16 6-16 15s7 15 16 15h13" />
      <path d="M42 34v22M32 44l10-10 10 10" />
    </svg>
  );
}

// ╭───────────────────────────────────────────────────────────╮
// │ MAIN STORY                                                 │
// ╰───────────────────────────────────────────────────────────╯
function PayWithFinaStory() {
  const t = useTime(); // 0..22

  const T1 = 4.5;   // end of F1
  const T2 = 9.5;   // end of F2
  const T3 = 14.0;  // end of F3
  const T4 = 18.0;  // end of F4
  const T5 = 22.0;  // end of hold

  // ── Header content morph ────────────────────────────────
  let title = "Fina - standing by";
  let subtitle = "Pay with Fina";
  let photo = "../shared-assets/fina-icon.png";
  if (t >= T1 && t < T2) {
    title = "Paying supplier now...";
    subtitle = "1/1 Invoice Approved";
  } else if (t >= T2 && t < T3) {
    title = "Invoice Paid with Fina";
    subtitle = "Payment Complete - SAR 34,000";
  } else if (t >= T3 && t < T4) {
    title = "Goods ships to Merchant";
    subtitle = "Shipped on 21 Oct 2025";
    photo = "../shared-assets/avatar-supplier.png";
  } else if (t >= T4) {
    // F5: celebration moment — invoice paid, terms locked in
    title = "Paid with Fina";
    subtitle = "Repayment scheduled · 60 days";
    photo = "../shared-assets/fina-icon.png";
  }

  const headerOpacity = interpolate(t, [0, 0.4, T4 - 0.6, T4], [0, 1, 1, 1], easeInOut);

  // Top divider visible during F1 (when full surface)
  const dividerOp = interpolate(t, [0.6, 1.0, T1, T1 + 0.3], [0, 0.2, 0.2, 0], easeOut);

  // ── F1 dropzone ─────────────────────────────────────────
  const dzAppear = interpolate(t, [0.5, 1.1], [0, 1], easeOut);
  const dzExit = interpolate(t, [T1 - 0.5, T1], [1, 0], easeOut);
  const dropOpacity = dzAppear * dzExit;
  const dzScale = interpolate(t, [T1 - 0.4, T1], [1, 0.7], easeInOut);
  const dzY = interpolate(t, [T1 - 0.4, T1], [0, -120], easeInOut);
  // mock cart fly-in (descends mid-F1) — translate from above DOWN INTO the dropzone
  const cartFly = interpolate(t, [1.4, 2.4], [-80, 0], easeInOut);
  const cartOp = interpolate(t, [1.4, 1.8, T1 - 0.5, T1 - 0.2], [0, 1, 1, 0], easeInOut);

  // ── Surface heights ─────────────────────────────────────
  // F1 full=453, F2/F3/F4 collapse to 96
  let surf1H = 453;
  if (t >= T1 - 0.4 && t < T1) {
    surf1H = interpolate(t, [T1 - 0.4, T1], [453, 96], easeInOut);
  } else if (t >= T1) {
    surf1H = 96;
  }

  // Body (surf2) only F2/F3 (F4 keeps body too — it's the terms card)
  // We'll have body always present from T1+0.05 onward.
  const surf2Visible = t >= T1 - 0.05;
  // F2 body height matches 3 product cards stack: ~336 (3 cards @ 96 + 24 gap)
  // F3 body morphs into 2 stacked: order-row (96) + terms card (212), stacked with gap → 308 (or 96+212=308 + 24 = 332)
  // We keep body height constant 332 so the smart-animate just swaps content within fixed frame.
  // F4 body height = just terms (212 + 24 padding)
  const BODY_H_F2 = 357;
  const BODY_H_F3 = 332;
  const BODY_H_F4 = 232;
  let surf2H;
  if (t < T1) surf2H = 0;
  else if (t < T2) surf2H = interpolate(t, [T1 - 0.05, T1 + 0.4], [0, BODY_H_F2], easeOut);
  else if (t < T2 + 0.4) surf2H = interpolate(t, [T2, T2 + 0.4], [BODY_H_F2, BODY_H_F3], easeInOut);
  else if (t < T3 - 0.4) surf2H = BODY_H_F3;
  else if (t < T3 + 0.1) surf2H = interpolate(t, [T3 - 0.4, T3 + 0.1], [BODY_H_F3, BODY_H_F4], easeInOut);
  else surf2H = BODY_H_F4;

  // ── F2 product cards ────────────────────────────────────
  // 3 cards stagger up
  const PRODUCT_OFFSETS = [0, 120, 240]; // top within body
  const cardOps = [
    interpolate(t, [T1 + 0.3, T1 + 0.8], [0, 1], easeOut),
    interpolate(t, [T1 + 0.5, T1 + 1.0], [0, 1], easeOut),
    interpolate(t, [T1 + 0.7, T1 + 1.2], [0, 1], easeOut),
  ];
  const cardYs = [
    interpolate(t, [T1 + 0.3, T1 + 0.8], [40, 0], easeOut),
    interpolate(t, [T1 + 0.5, T1 + 1.0], [40, 0], easeOut),
    interpolate(t, [T1 + 0.7, T1 + 1.2], [40, 0], easeOut),
  ];
  // ── F2 invoice document ─────────────────────────────────
  const invoiceY = interpolate(t, [T1 + 0.3, T1 + 1.0], [40 * SCALE, 0], easeOut);
  // Cards FADE OUT at T2 transition
  const productsExit = interpolate(t, [T2 - 0.3, T2 + 0.2], [1, 0], easeInOut);

  // ── Glass info pills (SAR 800, Orders Submitted) — F2 only ──
  const sarOp = interpolate(t, [T1 + 1.4, T1 + 1.9, T2 - 0.2, T2 + 0.2], [0, 1, 1, 0], easeOut);
  const sarY = interpolate(t, [T1 + 1.4, T1 + 1.9], [12, 0], easeOut);
  const ordersOp = interpolate(t, [T1 + 1.7, T1 + 2.2, T2 - 0.2, T2 + 0.2], [0, 1, 1, 0], easeOut);
  const ordersY = interpolate(t, [T1 + 1.7, T1 + 2.2], [12, 0], easeOut);

  // ── F3 body content (Goods ships row + Customer repays terms) ──
  const f3Op = interpolate(t, [T2 + 0.2, T2 + 0.7], [0, 1], easeOut);
  // Ship row collapses as F3 → F4 transitions (it's about to be promoted to header)
  const shipRowH = interpolate(t, [T3 - 0.4, T3 + 0.1], [86 * SCALE, 0], easeInOut);
  const shipRowOp = interpolate(t, [T3 - 0.5, T3 - 0.1], [1, 0], easeOut);
  const shipExitOp = 1;
  // Terms section top: in F3 sits below ship row (~116); in F4 slides up to top (~0)
  const termsTop = interpolate(t, [T3 - 0.4, T3 + 0.1], [116 * SCALE, 20 * SCALE], easeInOut);
  // pills cascade
  const pill0 = interpolate(t, [T2 + 0.6, T2 + 1.0], [40, 0], easeOut);
  const pill1 = interpolate(t, [T2 + 0.75, T2 + 1.15], [40, 0], easeOut);
  const pill2 = interpolate(t, [T2 + 0.9, T2 + 1.3], [40, 0], easeOut);
  const pill0op = interpolate(t, [T2 + 0.6, T2 + 1.0], [0, 1], easeOut);
  const pill1op = interpolate(t, [T2 + 0.75, T2 + 1.15], [0, 1], easeOut);
  const pill2op = interpolate(t, [T2 + 0.9, T2 + 1.3], [0, 1], easeOut);
  // 60-day pill is the selected one (merchant pays later)
  const selectMoment = T3 - 0.8;
  const sixtyState = t >= selectMoment ? "selected" : "idle";
  const sixtyCheck = t >= selectMoment + 0.2;

  // Cursor glides to "Pay in 60 days" pill (middle pill at x=113)
  const pillCenterX = 152 + 20 + 76 + 113 + 52; // surf.x + body padding + pill row offset + middle pill x + center
  const pillCenterY = 146 + 20 + 116 + 86 + 43; // body top + body padding + termsTop(F3) + pill row offset + center
  const cursorVisible = t >= T2 + 1.1 && t <= selectMoment + 0.6;
  const cursorX = interpolate(t, [T2 + 1.1, selectMoment - 0.1], [560, pillCenterX], easeInOut);
  const cursorY = interpolate(t, [T2 + 1.1, selectMoment - 0.1], [380, pillCenterY], easeInOut);
  const cursorOp = interpolate(t, [T2 + 1.1, T2 + 1.3, selectMoment + 0.4, selectMoment + 0.6], [0, 1, 1, 0], easeOut);
  const cursorClickScale = (t >= selectMoment - 0.05 && t <= selectMoment + 0.15) ? 0.85 : 1;

  // ── F4 footer card (Merchant Pay in 60 days) ───────────
  const footerVisible = t >= T3 - 0.1;
  const footerOp = interpolate(t, [T3 - 0.1, T3 + 0.5], [0, 1], easeOut);
  const footerY = interpolate(t, [T3 - 0.1, T3 + 0.5], [40, 0], easeOut);

  // ── Final hold sparkles (F5 only) ──────────────────────
  const sparkleOp = interpolate(t, [T4 - 0.2, T4 + 0.4], [0, 1], easeOut);

  // ── Camera: closeup that follows the action (cursor / focus region) ──
  // Focus point in FIGMA coords (FW × FH). Z = zoom level.
  // We interpolate (FX, FY, Z) across phase boundaries so the camera glides smoothly.
  // Phase focus points:
  //   F1: dropzone center  (226, 274)  Z=1.55
  //   F2: invoice doc center (≈ 200, ≈ 310)  Z=1.55
  //   F3: pills + body (cursor target)  (≈ 365, ≈ 305)  Z=1.7
  //   F4: terms + footer band (≈ 380, ≈ 380)  Z=1.55
  //   F5: zoom out to whole composition  (FW/2, FH/2)  Z=1.0
  const FXkeys = [0,   T1,  T2,  T3,  T4,  T4 + 1.2];
  const FXvals = [226, 226, 250, 365, 380, FW / 2];
  const FYkeys = [0,   T1,  T2,  T3,  T4,  T4 + 1.2];
  const FYvals = [274, 274, 310, 305, 380, FH / 2];
  const Zkeys  = [0,   T1,  T2,  T3,  T4,  T4 + 1.2];
  const Zvals  = [1.55,1.55,1.55,1.7, 1.55,1.0];
  const camFX = interpolate(t, FXkeys, FXvals, easeInOut);
  const camFY = interpolate(t, FYkeys, FYvals, easeInOut);
  const camZ  = interpolate(t, Zkeys,  Zvals,  easeInOut);
  // Map focus point to wrapper-local pre-transform coords, compute translate to center it.
  const _tx = (FW * SCALE) / (2 * camZ) - camFX * SCALE;
  const _ty = (FH * SCALE) / (2 * camZ) - camFY * SCALE;
  const cameraTransform = `scale(${camZ}) translate(${_tx}px, ${_ty}px)`;

  // ── Caption strip — describes the current action ────────
  const captions = [
    { start: 0.6,  end: T1 - 0.2,   text: "Buyer drops the invoice into Fina." },
    { start: T1 + 0.4, end: T2 - 0.2, text: "Fina pays the seller today. Invoice approved." },
    { start: T2 + 0.4, end: T3 - 0.2, text: "Invoice settled by Fina. Goods on the way." },
    { start: T3 + 0.4, end: T4 - 0.2, text: "Buyer picks repayment terms — pay later, no fees." },
    { start: T4 + 0.2, end: T5,       text: "Buyer repays Fina. Pay with Fina." },
  ];
  const activeCaption = captions.find(c => t >= c.start && t <= c.end);
  const captionOverlay = (
    <div style={{
      position: "absolute",
      left: 64, top: "50%",
      transform: "translateY(-50%)",
      pointerEvents: "none",
      maxWidth: 460,
    }}>
      <div key={activeCaption?.text || "empty"} style={{
        padding: "22px 34px",
        borderRadius: 999,
        backgroundColor: "#FFFFFF",
        boxShadow: "0 22px 50px rgba(15,18,28,0.12), 0 2px 6px rgba(15,18,28,0.05)",
        border: "1px solid rgba(15,18,28,0.06)",
        fontFamily: "'SF Pro', 'Inter', system-ui, sans-serif",
        fontWeight: 600, fontSize: 34,
        lineHeight: 1.15,
        color: C.white,
        letterSpacing: "-0.01em",
        display: "inline-flex", alignItems: "center", gap: 16,
        opacity: activeCaption ? 1 : 0,
        transform: activeCaption ? "translateY(0)" : "translateY(6px)",
        transition: "opacity 280ms ease-out, transform 280ms ease-out",
      }}>
        <svg width="28" height="28" viewBox="0 0 14 14" fill="none" style={{ flexShrink: 0 }}>
          <path d="M7 0.5 L7.9 5.1 L12.5 6 L7.9 6.9 L7 11.5 L6.1 6.9 L1.5 6 L6.1 5.1 Z" fill={C.lime} />
        </svg>
        <span>{activeCaption?.text || "\u00A0"}</span>
      </div>
    </div>
  );

  return (
    <PageCard cameraTransform={cameraTransform} overlay={captionOverlay}>
      {/* TOP DARK SURFACE */}
      <div style={{
        position: "absolute",
        left: SURF.x * SCALE, top: SURF.y * SCALE,
        width: SURF.w * SCALE, height: surf1H * SCALE,
        borderRadius: 8 * SCALE,
        backgroundColor: C.panel,
        boxShadow: C.shadow,
        overflow: "hidden",
      }}>
        {/* F1 divider beneath header */}
        <div style={{
          position: "absolute",
          left: 24 * SCALE, top: 96 * SCALE,
          width: 403 * SCALE, height: 1,
          background: C.divider, opacity: dividerOp,
        }} />

        {/* F1 dropzone */}
        {t < T1 + 0.05 && (
          <div style={{
            position: "absolute",
            left: 106 * SCALE, top: 120 * SCALE,
            width: 240 * SCALE, height: 309 * SCALE,
            borderRadius: 2 * SCALE,
            backgroundColor: "rgba(15,18,28,0.025)",
            border: `${1 * SCALE}px dashed ${C.white25}`,
            opacity: dropOpacity,
            transform: `translateY(${dzY * SCALE}px) scale(${dzScale})`,
            transformOrigin: "center center",
            display: "flex", flexDirection: "column",
            alignItems: "center", justifyContent: "center",
            gap: 23 * SCALE,
          }}>
            <div style={{ transform: `translateY(${cartFly * SCALE}px)`, opacity: cartOp }}>
              <CloudIcon size={42 * SCALE} />
            </div>
            <div style={{
              opacity: 0.5, color: C.white,
              fontFamily: "'SF Pro', sans-serif",
              fontWeight: 500, fontSize: 15.6 * SCALE,
              textAlign: "center",
            }}>Drop your invoice</div>
          </div>
        )}

        {/* HEADER ROW (avatar + title/subtitle) */}
        <div style={{ opacity: headerOpacity }}>
          <div style={{
            position: "absolute",
            left: (172 - SURF.x) * SCALE, top: (46 - SURF.y) * SCALE,
            width: 56 * SCALE, height: 56 * SCALE,
            borderRadius: 7 * SCALE,
            background: `url(${photo}) center/cover no-repeat, ${C.panel}`,
          }} />
          <div style={{
            position: "absolute",
            left: (172 - SURF.x + 76) * SCALE, top: (46 - SURF.y) * SCALE,
            height: 56 * SCALE,
            display: "flex", flexDirection: "column", justifyContent: "center", gap: 8 * SCALE,
            color: C.white,
            fontFamily: "'SF Pro', system-ui, sans-serif",
            whiteSpace: "nowrap",
          }}>
            <div style={{ fontWeight: 500, fontSize: 22 * SCALE, lineHeight: 1 }}>{title}</div>
            <div style={{ fontWeight: 300, fontSize: 16 * SCALE, lineHeight: 1, opacity: 0.6 }}>{subtitle}</div>
          </div>
        </div>
      </div>

      {/* BODY CARD */}
      {surf2Visible && surf2H > 1 && (
        <div style={{
          position: "absolute",
          left: SURF.x * SCALE, top: 146 * SCALE,
          width: SURF.w * SCALE, height: surf2H * SCALE,
          borderRadius: 8 * SCALE,
          backgroundColor: C.panel,
          boxShadow: C.shadow,
          overflow: "hidden",
          padding: 20 * SCALE,
          boxSizing: "border-box",
        }}>
          {/* F2: invoice document card */}
          {t < T2 + 0.2 && t >= T1 + 0.1 && (
            <div style={{
              position: "absolute",
              left: 20 * SCALE, top: 20 * SCALE,
              right: 20 * SCALE, bottom: 20 * SCALE,
              opacity: productsExit,
              transform: `translateY(${invoiceY}px)`,
            }}>
              <InvoiceDocument />
            </div>
          )}

          {/* F3: shipped row + merchant repays terms */}
          {t >= T2 - 0.05 && t < T3 + 0.6 && (
            <div style={{ opacity: f3Op * shipExitOp }}>
              {/* "Goods ships to Merchant" row — hides as F3 transitions to F4 */}
              <div style={{
                display: "flex", alignItems: "center", gap: 20 * SCALE,
                paddingBottom: 30 * SCALE,
                opacity: shipRowOp,
                height: shipRowH,
                overflow: "hidden",
              }}>
                <div style={{
                  width: 56 * SCALE, height: 56 * SCALE,
                  borderRadius: 7 * SCALE,
                  background: `url(../shared-assets/avatar-supplier.png) center/cover no-repeat, #ddd`,
                  flex: "none",
                }} />
                <div style={{
                  color: C.white,
                  fontFamily: "'SF Pro', sans-serif",
                  display: "flex", flexDirection: "column", gap: 11 * SCALE,
                }}>
                  <div style={{ fontWeight: 500, fontSize: 22 * SCALE, lineHeight: 1 }}>Goods ships to Merchant</div>
                  <div style={{ fontWeight: 300, fontSize: 16 * SCALE, lineHeight: 1, opacity: 0.6 }}>Shipped on 21 Oct 2025</div>
                </div>
              </div>
            </div>
          )}

          {/* F3/F4: merchant repays terms — persistent through both */}
          {t >= T2 - 0.05 && (
            <div style={{
              position: "absolute",
              left: 20 * SCALE,
              top: termsTop,
              right: 20 * SCALE,
              opacity: f3Op,
            }}>
              {/* terms section: avatar + "Merchant repays on their terms" */}
              <div style={{
                display: "flex", alignItems: "center", gap: 20 * SCALE,
              }}>
                <div style={{
                  width: 56 * SCALE, height: 56 * SCALE,
                  borderRadius: 7 * SCALE,
                  background: `url(../shared-assets/avatar-merchant.png) center/cover no-repeat, #ddd`,
                  flex: "none",
                }} />
                <div style={{
                  color: C.white,
                  fontFamily: "'SF Pro', sans-serif",
                  display: "flex", flexDirection: "column", gap: 11 * SCALE,
                }}>
                  <div style={{ fontWeight: 500, fontSize: 22 * SCALE, lineHeight: 1 }}>Merchant repays on their terms</div>
                  <div style={{ fontWeight: 300, fontSize: 16 * SCALE, lineHeight: 1, opacity: 0.6 }}>Select repayment terms</div>
                </div>
              </div>

              {/* pills row */}
              <div style={{
                position: "absolute",
                left: 76 * SCALE, top: 86 * SCALE,
                width: 331 * SCALE, height: 86 * SCALE,
              }}>
                <div style={{ position: "absolute", left: 0, top: 0, opacity: pill0op, transform: `translateY(${pill0}px)` }}>
                  <TermCard x={0} y={0} label="Pay in 30 days" />
                </div>
                <div style={{ position: "absolute", left: 0, top: 0, opacity: pill1op, transform: `translateY(${pill1}px)` }}>
                  <TermCard x={113} y={0} label="Pay in 60 days" state={sixtyState} showCheck={sixtyCheck} />
                </div>
                <div style={{ position: "absolute", left: 0, top: 0, opacity: pill2op, transform: `translateY(${pill2}px)` }}>
                  <TermCard x={226} y={0} label="Pay in 90 days" />
                </div>
              </div>
            </div>
          )}
        </div>
      )}

      {/* GLASS PILLS — F2 only, in right gutter outside the body */}
      {t >= T1 + 1.0 && t < T2 + 0.3 && (
        <>
          <GlassPill
            left={596} top={206}
            width={150}
            label="Approved"
            opacity={sarOp} dy={sarY}
            icon={
              <svg width={20 * SCALE} height={20 * SCALE} viewBox="0 0 20 20" fill={C.lime}>
                <path d="M 10 0 C 4.477 0 0 4.477 0 10 C 0 15.523 4.477 20 10 20 C 15.523 20 20 15.523 20 10 C 20 4.477 15.523 0 10 0 Z M 14.055 7.394 L 12.894 6.445 L 8.444 11.884 L 6.5 9.939 L 5.439 11 L 8.556 14.116 L 14.055 7.394 Z" fillRule="evenodd" />
              </svg>
            }
          />
          <GlassPill
            left={596} top={270}
            width={150}
            label="Net 60"
            opacity={ordersOp} dy={ordersY}
            icon={
              <svg width={20 * SCALE} height={20 * SCALE} viewBox="0 0 20 20" fill="none" stroke={C.lime} strokeWidth="2">
                <circle cx="10" cy="10" r="8" />
                <path d="M10 6v4l2.5 2.5" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            }
          />
        </>
      )}

      {/* F4 footer card */}
      {footerVisible && (
        <div style={{
          position: "absolute",
          left: SURF.x * SCALE, top: 382 * SCALE,
          width: SURF.w * SCALE, height: 96 * SCALE,
          borderRadius: 8 * SCALE,
          backgroundColor: C.panel,
          boxShadow: C.shadow,
          overflow: "hidden",
          opacity: footerOp,
          transform: `translateY(${footerY}px)`,
        }}>
          <div style={{
            position: "absolute",
            left: 20 * SCALE, top: 20 * SCALE,
            width: 56 * SCALE, height: 56 * SCALE,
            borderRadius: 7 * SCALE,
            background: `url(../shared-assets/fina-icon.png) center/cover no-repeat, ${C.panel}`,
          }} />
          <div style={{
            position: "absolute",
            left: 96 * SCALE, top: 20 * SCALE,
            height: 56 * SCALE,
            display: "flex", flexDirection: "column", justifyContent: "center", gap: 8 * SCALE,
            color: C.white,
            fontFamily: "'SF Pro', sans-serif",
            whiteSpace: "nowrap",
          }}>
            <div style={{ fontWeight: 500, fontSize: 22 * SCALE, lineHeight: 1 }}>Merchant pays in 60 days</div>
            <div style={{ fontWeight: 300, fontSize: 16 * SCALE, lineHeight: 1, opacity: 0.6 }}>Awaiting repayment on terms</div>
          </div>
        </div>
      )}

      {/* CURSOR */}
      {cursorVisible && (
        <svg
          width={48 * SCALE / 2} height={48 * SCALE / 2}
          viewBox="0 0 24 24"
          style={{
            position: "absolute",
            left: cursorX * SCALE - 6, top: cursorY * SCALE - 6,
            opacity: cursorOp,
            transform: `scale(${cursorClickScale})`,
            transformOrigin: "0 0",
            filter: "drop-shadow(0 6px 12px rgba(0,0,0,0.35))",
            pointerEvents: "none",
          }}
        >
          <path d="M3 2 L21 11 L13 13 L11 21 Z" fill="white" stroke="#1B1E2C" strokeWidth="1.4" strokeLinejoin="round" />
        </svg>
      )}

      {/* Final-hold sparkles */}
      {t >= T3 + 1.6 && (
        <div style={{ position: "absolute", inset: 0, opacity: sparkleOp, pointerEvents: "none" }}>
          <Sparkle x={120 * SCALE} y={60 * SCALE} size={28 * SCALE} opacity={1} rotate={(t - T3) * 30} />
          <Sparkle x={640 * SCALE} y={440 * SCALE} size={20 * SCALE} opacity={0.9} rotate={-(t - T3) * 25} />
        </div>
      )}
    </PageCard>
  );
}

Object.assign(window, { PayWithFinaStory });
