// scenes-3.jsx — Act III: cost formula, worked example, model comparison + outro

// illustrative pricing, USD per 1,000,000 tokens
const PRICE = { input: 3.00, cached: 0.30, output: 15.00 };

function PriceCard({ o, highlight = null }) {
  if (o <= 0.01) return null;
  const rows = [
    { k: 'input',  v: PRICE.input,  c: COLORS.blue },
    { k: 'cached', v: PRICE.cached, c: COLORS.green },
    { k: 'output', v: PRICE.output, c: COLORS.yellow },
  ];
  return (
    <div style={{
      position:'absolute', right: 84, top: 150, width: 360, opacity: o,
      background: COLORS.bgPanel, border:`1.5px solid ${COLORS.inkFaint}`, borderRadius: 16,
      padding:'18px 22px', boxShadow:'0 14px 40px rgba(0,0,0,0.45)',
    }}>
      <div style={{ fontFamily: FONTS.sans, fontSize: 18, color: COLORS.inkDim, letterSpacing:'0.1em', textTransform:'uppercase', marginBottom: 14 }}>
        Price · per 1M tokens
      </div>
      {rows.map(r => (
        <div key={r.k} style={{
          display:'flex', alignItems:'center', justifyContent:'space-between', padding:'8px 12px', marginBottom:7,
          borderRadius: 9, background: highlight===r.k ? r.c+'22' : 'transparent',
          border:`1px solid ${highlight===r.k ? r.c : 'transparent'}`,
        }}>
          <span style={{ display:'flex', alignItems:'center', gap:10, fontFamily: FONTS.mono, fontSize: 21, color: COLORS.ink }}>
            <span style={{ width:10, height:10, borderRadius:'50%', background:r.c }} />{r.k}
          </span>
          <span style={{ fontFamily: FONTS.math, fontSize: 26, color: r.c, fontVariantNumeric:'tabular-nums' }}>${r.v.toFixed(2)}</span>
        </div>
      ))}
      <div style={{ fontFamily: FONTS.math, fontStyle:'italic', fontSize: 16, color: COLORS.inkFaint, marginTop: 6, textAlign:'center' }}>illustrative numbers</div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════════════
// SCENE 6 — THE COST FORMULA  (length 20s)
// ════════════════════════════════════════════════════════════════════════════
function SceneFormula() {
  const { localTime: lt } = useSprite();

  const o1 = pulse(lt, 1.0, 20, 0.4);     // cost = tokens × price
  const split = ramp(lt, 5.2, 6.2);       // morph into input/output rows
  const o2 = pulse(lt, 5.6, 20, 0.4);
  const oOut = pulse(lt, 9.0, 20, 0.4);   // output emphasis
  const oCache = pulse(lt, 13.2, 20, 0.4);// cache row
  const priceHi = lt > 9.0 && lt < 13.0 ? 'output' : (lt > 13.2 ? 'cached' : (lt>2 ? 'input' : null));

  const cy = 470;
  const Mono = ({ children, c=COLORS.ink, s=54 }) => <span style={{ fontFamily: FONTS.math, fontSize: s, color: c, fontVariantNumeric:'tabular-nums' }}>{children}</span>;

  return (
    <>
      <Bg accent={COLORS.coral} />
      <Eyebrow lt={lt} a={0.4} b={20} n="08" label="What you pay for" color={COLORS.coral} />
      <PriceCard o={pulse(lt, 2.4, 20, 0.5)} highlight={priceHi} />

      {/* simple form (fades when split happens) */}
      {o1 > 0.01 && split < 0.5 && (
        <div style={{ position:'absolute', left: 700, top: cy, transform:'translate(-50%,-50%)', opacity: o1*(1-split*2>0?1-split*2:0) }}>
          <Mono c={COLORS.coral} s={60}>cost</Mono>
          <Mono s={60}>{'  =  '}</Mono>
          <Mono c={COLORS.ink} s={60}>tokens</Mono>
          <Mono s={60}>{'  ×  '}</Mono>
          <Mono c={COLORS.inkDim} s={60}>price</Mono>
        </div>
      )}

      {/* expanded form */}
      {o2 > 0.01 && (
        <div style={{ position:'absolute', left: 110, top: 360, opacity: o2 }}>
          <div style={{ display:'flex', alignItems:'baseline', gap: 4, marginBottom: 26 }}>
            <Mono c={COLORS.coral} s={56}>cost</Mono>
            <Mono s={56}>{'   =   '}</Mono>
            <Mono c={COLORS.blue} s={56}>input</Mono>
            <Mono s={40} c={COLORS.inkDim}>{' tokens '}</Mono>
            <Mono s={56}>{' × '}</Mono>
            <Mono c={COLORS.blue} s={56}>$3</Mono>
          </div>
          <div style={{ display:'flex', alignItems:'baseline', gap: 4, opacity: oOut, transform:`translateX(${(1-oOut)*30}px)` }}>
            <Mono s={56}>{'              +   '}</Mono>
            <Mono c={COLORS.yellow} s={56}>output</Mono>
            <Mono s={40} c={COLORS.inkDim}>{' tokens '}</Mono>
            <Mono s={56}>{' × '}</Mono>
            <Mono c={COLORS.yellow} s={56}>$15</Mono>
          </div>

          {/* cache refinement */}
          {oCache > 0.01 && (
            <div style={{ marginTop: 60, opacity: oCache, transform:`translateY(${(1-oCache)*20}px)`, borderTop:`1px solid ${COLORS.inkFaint}55`, paddingTop: 30 }}>
              <div style={{ fontFamily: FONTS.sans, fontSize: 24, color: COLORS.green, marginBottom: 18, fontWeight:600 }}>…and input splits again:</div>
              <div style={{ display:'flex', alignItems:'baseline', gap: 4 }}>
                <Mono c={COLORS.blue} s={48}>input</Mono>
                <Mono s={48}>{'  =  '}</Mono>
                <Mono c={COLORS.green} s={48}>cached</Mono>
                <Mono s={48}>{' × '}</Mono>
                <Mono c={COLORS.green} s={48}>$0.30</Mono>
                <Mono s={48}>{'   +   '}</Mono>
                <Mono c={COLORS.blue} s={48}>fresh</Mono>
                <Mono s={48}>{' × '}</Mono>
                <Mono c={COLORS.blue} s={48}>$3</Mono>
              </div>
            </div>
          )}
        </div>
      )}

      <Caption lt={lt} a={1.2} b={5.0}>
        At heart, the bill is simple: <b style={{color:COLORS.coral}}>tokens × price</b>.
      </Caption>
      <Caption lt={lt} a={5.4} b={8.8}>
        But <b style={{color:COLORS.blue}}>input</b> and <b style={{color:COLORS.yellow}}>output</b> are priced separately.
      </Caption>
      <Caption lt={lt} a={9.2} b={13.0} color={COLORS.yellow}>
        Output is usually <b>~5× pricier</b> — every generated token counts.
      </Caption>
      <Caption lt={lt} a={13.4} b={20} color={COLORS.green}>
        Re-reading <b>cached</b> context can be ~10× cheaper than fresh tokens.
      </Caption>
    </>
  );
}

// ════════════════════════════════════════════════════════════════════════════
// SCENE 7 — WORKED EXAMPLE  (length 21s)
// ════════════════════════════════════════════════════════════════════════════
const RUN = [
  { turn: 1, in: 1000, out: 100 },
  { turn: 2, in: 1800, out: 120 },
  { turn: 3, in: 3100, out: 260 },
  { turn: 4, in: 4500, out: 180 },
  { turn: 5, in: 6200, out: 320 },
];
function SceneWorked() {
  const { localTime: lt } = useSprite();
  const setup = ramp(lt, 0.2, 1.0);

  // reveal rows one by one starting at 1.4, every 0.85s
  const rowAt = (i) => 1.4 + i * 0.85;
  let inTot = 0, outTot = 0;
  RUN.forEach((r, i) => {
    const p = clamp((lt - rowAt(i)) / 0.55, 0, 1);
    inTot += r.in * p; outTot += r.out * p;
  });
  const inCost = inTot / 1e6 * PRICE.input;
  const outCost = outTot / 1e6 * PRICE.output;
  const total = inCost + outCost;

  const showCalc = pulse(lt, 7.6, 21, 0.4);
  const showTotal = pulse(lt, 11.4, 21, 0.4);
  // cached-optimised comparison
  const showCache = pulse(lt, 14.6, 21, 0.45);
  const cachedFrac = 0.8;
  const optInCost = (inTot*(1-cachedFrac)/1e6*PRICE.input) + (inTot*cachedFrac/1e6*PRICE.cached);
  const optTotal = optInCost + outCost;
  const cacheReveal = ramp(lt, 15.0, 16.2);

  return (
    <>
      <Bg accent={COLORS.blue} />
      <Eyebrow lt={lt} a={0.4} b={21} n="15" label="A real agent run" color={COLORS.blue} />

      {/* table on the left */}
      <div style={{ position:'absolute', left: 110, top: 250, opacity: setup, width: 660 }}>
        <div style={{ display:'grid', gridTemplateColumns:'1.4fr 1fr 1fr', gap: 0, fontFamily: FONTS.sans }}>
          <Cell head>turn</Cell><Cell head c={COLORS.blue}>input</Cell><Cell head c={COLORS.yellow}>output</Cell>
          {RUN.map((r,i) => {
            const o = pulse(lt, rowAt(i), 21, 0.3);
            return (
              <React.Fragment key={i}>
                <Cell o={o}>tool call #{r.turn}</Cell>
                <Cell o={o} c={COLORS.blue} mono>{fmtNum(r.in)}</Cell>
                <Cell o={o} c={COLORS.yellow} mono>{r.out}</Cell>
              </React.Fragment>
            );
          })}
          <Cell total>Σ totals</Cell>
          <Cell total c={COLORS.blue} mono>{fmtNum(Math.round(inTot))}</Cell>
          <Cell total c={COLORS.yellow} mono>{fmtNum(Math.round(outTot))}</Cell>
        </div>
      </div>

      <PriceCard o={pulse(lt, 0.6, 21, 0.5)} highlight={null} />

      {/* calculation + total on the right */}
      {showCalc > 0.01 && (
        <div style={{ position:'absolute', left: 870, top: 470, opacity: showCalc, width: 640 }}>
          <Line c={COLORS.blue}>
            {fmtNum(Math.round(inTot))} <S>×</S> $3/M <S>=</S> <b>{fmtUSD(inCost)}</b>
          </Line>
          <Line c={COLORS.yellow}>
            {fmtNum(Math.round(outTot))} <S>×</S> $15/M <S>=</S> <b>{fmtUSD(outCost)}</b>
          </Line>
        </div>
      )}

      {showTotal > 0.01 && (
        <div style={{ position:'absolute', left: 1620, top: 540, transform:'translate(-50%,0)', opacity: showTotal, textAlign:'center' }}>
          <div style={{ fontFamily: FONTS.sans, fontSize: 22, color: COLORS.inkDim, letterSpacing:'0.08em', textTransform:'uppercase' }}>run cost</div>
          <div style={{ fontFamily: FONTS.math, fontSize: 104, fontWeight:700, lineHeight:1,
            color: showCache>0.3 ? COLORS.inkDim : COLORS.coral,
            textDecoration: showCache>0.5 ? 'line-through' : 'none',
            transition:'none', fontVariantNumeric:'tabular-nums' }}>
            {fmtUSD(total)}
          </div>
          {showCache > 0.01 && (
            <div style={{ opacity: cacheReveal, marginTop: 14 }}>
              <div style={{ fontFamily: FONTS.sans, fontSize: 20, color: COLORS.green, marginBottom: 4 }}>with 80% context cached ↓</div>
              <div style={{ fontFamily: FONTS.math, fontSize: 88, fontWeight:700, color: COLORS.green, lineHeight:1, fontVariantNumeric:'tabular-nums' }}>
                {fmtUSD(optTotal)}
              </div>
            </div>
          )}
        </div>
      )}

      <Caption lt={lt} a={1.0} b={5.2}>
        Five tool-calling turns. Watch the <b style={{color:COLORS.blue}}>input</b> tokens pile up.
      </Caption>
      <Caption lt={lt} a={5.6} b={7.4}>
        Notice: input dwarfs output — that re-sent history again.
      </Caption>
      <Caption lt={lt} a={7.8} b={11.2}>
        Multiply each column by its price…
      </Caption>
      <Caption lt={lt} a={11.6} b={14.4} color={COLORS.coral}>
        …a few cents for this little run.
      </Caption>
      <Caption lt={lt} a={14.8} b={21} color={COLORS.green}>
        Cache the stable context and the same run costs <b>less than half</b>.
      </Caption>
    </>
  );
}

function Cell({ children, head, total, c = COLORS.ink, mono, o = 1 }) {
  return (
    <div style={{
      padding:'13px 16px', opacity: o,
      borderBottom: total ? `2px solid ${COLORS.inkFaint}` : `1px solid ${COLORS.inkFaint}33`,
      borderTop: total ? `2px solid ${COLORS.inkFaint}` : 'none',
      fontFamily: mono ? FONTS.math : FONTS.sans,
      fontSize: head ? 22 : (total ? 30 : 26),
      fontWeight: head ? 700 : (total ? 700 : 500),
      color: head ? (c==COLORS.ink?COLORS.inkDim:c) : c,
      textTransform: head ? 'uppercase' : 'none',
      letterSpacing: head ? '0.08em' : '0',
      textAlign: mono ? 'right' : 'left',
      fontVariantNumeric:'tabular-nums',
    }}>{children}</div>
  );
}
function Line({ children, c }) {
  return <div style={{ fontFamily: FONTS.math, fontSize: 40, color: c, marginBottom: 14, fontVariantNumeric:'tabular-nums' }}>{children}</div>;
}
function S({ children }) { return <span style={{ color: COLORS.inkFaint, margin:'0 6px' }}>{children}</span>; }

Object.assign(window, { SceneFormula, SceneWorked, PriceCard, PRICE, RUN, Cell, Line, S });
