// Klombic — post-checkout delivery / live "the engine is running" experience
// Designed as a theatrical waiting page: the customer sees the sieve work,
// candidates tumble through, stats rack up. Timing is approximate; real PDF
// arrives via email when fulfill.py finishes (3–5 min).

const TOTAL_DURATION = 240; // seconds the animation plays before final reveal

// Fictitious-but-plausible candidate names for the rolodex theater.
// (Real names come from the engine; these are just to fill the marquee.)
const ROLODEX = [
  "Volari","Trindex","Corvex","Brunkalo","Pjenta","Maltreva","Norvath","Tuldano",
  "Quibran","Verridge","Frenzal","Hovrant","Kuldera","Astrelle","Oremi","Vexora",
  "Plurra","Stindel","Jorvic","Nubrant","Crivell","Drovak","Senthi","Liomar",
  "Karvex","Olympus","Brindra","Tessari","Klovan","Pyrith","Amberek","Soltrix",
];

const STAGES = [
  { key:'generate', lbl:'Generating candidates from your brief',  startPct:0,   endPct:6,   color:'#1F4E3D' },
  { key:'uspto',    lbl:'USPTO TESS · scanning live + pending marks · class 9 / 35 / 42', startPct:6, endPct:48, color:'#1F4E3D' },
  { key:'tld',      lbl:'Multi-TLD domain availability · 6 zones', startPct:48, endPct:62,  color:'#1F4E3D' },
  { key:'shopify',  lbl:'Shopify slug collision check',           startPct:62,  endPct:68,  color:'#1F4E3D' },
  { key:'phon',     lbl:'Sound-symbolism + memorability scoring', startPct:68,  endPct:78,  color:'#1F4E3D' },
  { key:'xlang',    lbl:'Cross-language scan · 15 languages',     startPct:78,  endPct:90,  color:'#1F4E3D' },
  { key:'rank',     lbl:'Aggregating per-axis weights · ranking', startPct:90,  endPct:96,  color:'#1F4E3D' },
  { key:'pdf',      lbl:'Rendering PDF · sending to your inbox',  startPct:96,  endPct:100, color:'#1F4E3D' },
];

// Fake-but-honest counter targets that map to real engine work
const TARGETS = {
  uspto:    { lbl:'USPTO marks compared',    target: 4280,  startPct:6,  endPct:48 },
  tld:      { lbl:'TLDs probed',             target: 60,    startPct:48, endPct:62 },
  shopify:  { lbl:'Shopify slugs checked',   target: 10,    startPct:62, endPct:68 },
  phonemes: { lbl:'Phonemes analyzed',       target: 312,   startPct:68, endPct:78 },
  langs:    { lbl:'Languages scanned',       target: 15,    startPct:78, endPct:90 },
  cands:    { lbl:'Candidates ranked',       target: 10,    startPct:90, endPct:96 },
};

const Sieve = ({ pct }) => {
  // Three bars (the brand mark) with "candidates" falling through
  // pct drives how fast the candidates drop and how lit-up the bars are
  const intensity = Math.min(1, pct / 100);
  return (
    <div className="sieve-stage" aria-hidden="true">
      <div className="sieve-light" style={{opacity: 0.3 + 0.7*intensity}}/>
      <div className="sieve-mark">
        {/* top dark bar */}
        <div className="sieve-bar sieve-bar-top"/>
        {/* bottom forest bars (3 segments) */}
        <div className="sieve-bar-row">
          <div className="sieve-bar sieve-bar-bot" style={{flex:'0 0 41%'}}/>
          <div className="sieve-bar-gap" style={{flex:'0 0 5%'}}/>
          <div className="sieve-bar sieve-bar-bot" style={{flex:'0 0 22%'}}/>
          <div className="sieve-bar-gap" style={{flex:'0 0 5%'}}/>
          <div className="sieve-bar sieve-bar-bot" style={{flex:'0 0 7%'}}/>
        </div>
      </div>
      {/* falling candidates (visual only) */}
      <div className="sieve-falls">
        {Array.from({length: 12}).map((_,i) => (
          <span key={i} className="sieve-fall" style={{
            left: (5 + (i*8) % 90) + '%',
            animationDelay: (-(i * 0.43) % 3) + 's',
            animationDuration: (2.2 + (i % 3)*0.4) + 's',
          }}/>
        ))}
      </div>
    </div>
  );
};

const Counter = ({ value }) => <span className="counter-num">{value.toLocaleString()}</span>;

const Rolodex = ({ tick, finished }) => {
  // Show a stream of "names being tested" — every ~1.6s a new name takes the spotlight
  const idx = Math.floor(tick / 1.6) % ROLODEX.length;
  const items = [
    ROLODEX[(idx-2+ROLODEX.length) % ROLODEX.length],
    ROLODEX[(idx-1+ROLODEX.length) % ROLODEX.length],
    ROLODEX[idx],
    ROLODEX[(idx+1) % ROLODEX.length],
    ROLODEX[(idx+2) % ROLODEX.length],
  ];
  // Fake a verdict for the center one based on tick parity (just for theater)
  const verdict = (idx % 4 === 0) ? 'TM RISK' : 'CLEAR';
  return (
    <div className={`rolodex ${finished ? 'rolodex-done' : ''}`}>
      <div className="rolodex-rail">
        {items.map((name, i) => (
          <div key={i + '_' + name} className={`rolodex-item ${i === 2 ? 'rolodex-active' : ''}`}>
            <span className="rolodex-name">{name}</span>
            {i === 2 && <span className={`rolodex-verdict ${verdict === 'CLEAR' ? 'ok' : 'no'}`}>{verdict}</span>}
          </div>
        ))}
      </div>
      <div className="rolodex-caption">{finished ? 'Final ranking complete' : 'Testing each candidate…'}</div>
    </div>
  );
};

const Delivery = ({ go }) => {
  const params = new URLSearchParams(window.location.search);
  const session = params.get('session') || '';
  const sessionShort = session ? session.slice(0,8) + '…' + session.slice(-6) : '—';

  const [tick, setTick] = React.useState(0);

  React.useEffect(() => {
    const start = Date.now();
    const id = setInterval(() => setTick((Date.now() - start) / 1000), 200);
    return () => clearInterval(id);
  }, []);

  const pct = Math.min(100, (tick / TOTAL_DURATION) * 100);
  const finished = pct >= 100;

  // Find the active stage
  const activeStage = STAGES.find(s => pct >= s.startPct && pct < s.endPct) || STAGES[STAGES.length-1];

  // Compute live counters — interpolate from 0 → target between startPct and endPct
  const liveCounters = Object.entries(TARGETS).map(([k, t]) => {
    if (pct < t.startPct) return { key:k, ...t, value: 0 };
    if (pct >= t.endPct) return { key:k, ...t, value: t.target };
    const local = (pct - t.startPct) / (t.endPct - t.startPct);
    return { key:k, ...t, value: Math.floor(local * t.target) };
  });

  const totalChecks = liveCounters.reduce((s,c) => s + c.value, 0);

  return (
    <section className="delivery">
      <div className="page">

        <div className="dlv-eyebrow"><span className="dot"/>Order received · the engine is running</div>
        <h1 className="dlv-title">Your report is being built.</h1>
        <p className="dlv-lead">
          You can close this tab — the PDF lands in your inbox within ~4 hours, usually <b>3–5 minutes</b>.
          Or stick around and watch the machine work.
        </p>

        {/* The sieve theater */}
        <Sieve pct={pct}/>

        {/* Active stage caption */}
        <div className="dlv-now">
          <span className="dlv-now-eyebrow">{finished ? 'Complete' : 'Now'}</span>
          <span className="dlv-now-lbl">{finished ? 'Your PDF is en route to your inbox.' : activeStage.lbl}</span>
        </div>

        {/* Big live counters */}
        <div className="counters">
          {liveCounters.map(c => (
            <div key={c.key} className="counter-cell">
              <Counter value={c.value}/>
              <span className="counter-lbl">{c.lbl}</span>
            </div>
          ))}
        </div>

        {/* Candidate rolodex */}
        <Rolodex tick={tick} finished={finished}/>

        {/* Progress bar */}
        <div className="dlv-progress">
          <div className="dlv-progress-fill" style={{width: pct + '%'}}/>
        </div>

        <div className="dlv-meta">
          <span><b>SESSION</b>{sessionShort}</span>
          <span><b>ELAPSED</b>{Math.floor(tick/60)}:{Math.floor(tick%60).toString().padStart(2,'0')}</span>
          <span><b>TOTAL CHECKS</b>{totalChecks.toLocaleString()}</span>
        </div>

        {/* Final reveal */}
        {finished && (
          <div className="dlv-reveal">
            <div className="dlv-reveal-mark" aria-hidden="true">
              <svg width="44" height="44" viewBox="0 0 240 240">
                <rect x="24" y="84" width="192" height="24" fill="#1A1A1A"/>
                <rect x="24" y="132" width="100" height="24" fill="#1F4E3D"/>
                <rect x="136" y="132" width="52" height="24" fill="#1F4E3D"/>
                <rect x="200" y="132" width="16" height="24" fill="#1F4E3D"/>
              </svg>
            </div>
            <h3>Report delivered.</h3>
            <p>
              Check your inbox (and Spam, just in case — it'll be from <b>orders@klombic.com</b>).
              If it doesn't arrive within 10 min, email <a href="mailto:hello@klombic.com">hello@klombic.com</a> with your session ID.
            </p>
          </div>
        )}

        <div className="dlv-foot">
          This page is a live representation of the pipeline running on our worker.
          Stage timing is estimated — your real PDF lands when the engine finishes, not when the animation does.
        </div>
      </div>
    </section>
  );
};

window.Delivery = Delivery;
