// ── Trim Demo: animated before/after with scrub control ──
const TRIM_SAMPLE = {
  before: [
    {t: "Hey ", strike: true},
    {t: "Toki, ", strike: false, keep: true},
    {t: "I was just sort of wondering if you could maybe possibly help me out and ", strike: true},
    {t: "summarize ", strike: false, keep: true},
    {t: "the following ", strike: true},
    {t: "article ", strike: false, keep: true},
    {t: "for me really quickly please, that would be amazing thanks ", strike: true},
    {t: "in 3 bullets", strike: false, keep: true},
    {t: ", ok? Thanks again so so much you're the best", strike: true},
    {t: ".", strike: false, keep: true},
  ],
  beforeTokens: 48,
  afterTokens: 7,
  beforeCost: 0.00096,
  afterCost: 0.00014,
};

function TrimDemo() {
  const [progress, setProgress] = React.useState(0);
  const [playing, setPlaying] = React.useState(true);

  React.useEffect(() => {
    if (!playing) return;
    let raf;
    let last = performance.now();
    const tick = (t) => {
      const dt = (t - last) / 1000; last = t;
      setProgress(p => {
        const n = p + dt * 0.22; // ~4.5s loop
        if (n >= 1.1) return 0; // pause at end then loop
        return n;
      });
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [playing]);

  const eff = Math.min(1, progress);
  const tokensNow = Math.round(TRIM_SAMPLE.beforeTokens - (TRIM_SAMPLE.beforeTokens - TRIM_SAMPLE.afterTokens) * eff);
  const savedTokens = TRIM_SAMPLE.beforeTokens - tokensNow;
  const savedPct = Math.round((savedTokens / TRIM_SAMPLE.beforeTokens) * 100);
  const costNow = TRIM_SAMPLE.beforeCost - (TRIM_SAMPLE.beforeCost - TRIM_SAMPLE.afterCost) * eff;

  // for the after pane we mark strikes as 'gone' progressively
  const totalStrikes = TRIM_SAMPLE.before.filter(s => s.strike).length;
  const goneCount = Math.floor(eff * totalStrikes + 0.001);

  let strikeIdx = -1;
  const afterContent = TRIM_SAMPLE.before.map((seg, i) => {
    let isGone = false;
    if (seg.strike) {
      strikeIdx++;
      isGone = strikeIdx < goneCount;
    }
    return (
      <span key={i} className={seg.strike ? `strike ${isGone ? 'gone' : ''}` : (seg.keep ? 'keep' : '')}>
        {seg.t}
      </span>
    );
  });

  return (
    <section className="trim" id="trim">
      <div className="wrap">
        <span className="eyebrow">PART THREE — The Trick</span>
        <h2 className="h-section" style={{marginTop:'24px', maxWidth:'20ch'}}>
          Watch me <em>trim</em> a real prompt in 200 milliseconds.
        </h2>

        <div className="trim-stage">
          <div className="trim-pane">
            <div className="trim-head">
              <span>BEFORE — RAW PROMPT</span>
              <span className="badge">48 TOK · $0.00096</span>
            </div>
            <div className="trim-text">
              {TRIM_SAMPLE.before.map((seg, i) => (
                <span key={i} className={seg.keep ? 'keep' : ''}>{seg.t}</span>
              ))}
            </div>
            <div className="trim-foot">
              <div className="trim-tokens">48 <span style={{fontSize:'0.4em', color:'var(--fg-3)', fontFamily:'var(--mono)', fontStyle:'normal'}}>tokens</span></div>
              <div className="trim-cost">PROJECTED · $0.350 / MO</div>
            </div>
          </div>

          <div className="trim-pane after">
            <div className="trim-head">
              <span>AFTER — TOKI TRIMMED</span>
              <span className="badge">{tokensNow} TOK · {formatUSD(costNow)}</span>
            </div>
            <div className="trim-text">
              {afterContent}
            </div>
            <div className="trim-foot">
              <div className="trim-tokens">{tokensNow}<span style={{fontSize:'0.4em', color:'var(--fg-3)', fontFamily:'var(--mono)', fontStyle:'normal', marginLeft:'8px'}}>tokens</span></div>
              <div className="trim-cost">PROJECTED · ${(0.350 * (1 - savedPct/100)).toFixed(3)} / MO</div>
            </div>
          </div>
        </div>

        <div className="trim-controls">
          <button
            onClick={() => setPlaying(p => !p)}
            style={{
              width: '36px', height: '36px', borderRadius: '50%',
              background: 'var(--cyan)', color: 'oklch(0.18 0.04 220)',
              display: 'grid', placeItems: 'center', fontSize: '14px',
              boxShadow: '0 0 16px var(--cyan-soft)'
            }}
            aria-label={playing ? 'Pause' : 'Play'}
          >
            {playing ? '❚❚' : '▶'}
          </button>
          <div className="trim-progress">
            <div className="trim-progress-fill" style={{width: `${eff * 100}%`}}></div>
          </div>
          <div className="trim-savings">
            <span>SAVED</span>
            <strong>{savedTokens} tok</strong>
            <span>· {savedPct}%</span>
          </div>
        </div>
      </div>
    </section>
  );
}

window.TrimDemo = TrimDemo;
