// spndly — top components: Nav, Hero, PaperFlow

// Reusable pipeline logo mark. Resting state is static (purple output node);
// the run animation plays on hover via CSS (.logo:hover .sp-*).
function SpndlyMark() {
  return (
    <svg className="spndly-mark" viewBox="4 10 34 20" aria-hidden="true">
      <line className="sp-wire" x1="9" y1="20" x2="31" y2="20" strokeLinecap="round" />
      <line className="sp-track" x1="9" y1="20" x2="31" y2="20" />
      <circle className="sp-ring" cx="31" cy="20" r="5.4" />
      <circle className="sp-node sp-n1" cx="9" cy="20" r="3.6" />
      <circle className="sp-node sp-n2" cx="20" cy="20" r="3.6" />
      <circle className="sp-out" cx="31" cy="20" r="5.4" />
      <circle className="sp-pulse" cx="9" cy="20" r="2.6" />
    </svg>
  );
}

function Nav({ dark, onToggle }) {
  return (
    <header className="nav">
      <div className="container nav-inner">
        <a href="#top" className="logo"><SpndlyMark /><span className="logo-word">spndly</span></a>
        <nav className="nav-links">
          <a href="#problem">the problem</a>
          <a href="#how">how it works</a>
          <a href="#cases">body of work</a>
          <a href="#faq">faq</a>
        </nav>
        <div className="nav-right">
          <div className="theme-toggle-wrap">
            <button className="theme-toggle" onClick={onToggle} aria-label="Toggle dark mode">
              <svg className="tt-sun" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><circle cx="12" cy="12" r="4.4" /><path d="M12 2.6v2.2M12 19.2v2.2M2.6 12h2.2M19.2 12h2.2M5.1 5.1l1.6 1.6M17.3 17.3l1.6 1.6M18.9 5.1l-1.6 1.6M6.7 17.3l-1.6 1.6" /></svg>
              <svg className="tt-moon" viewBox="0 0 24 24" fill="currentColor"><path d="M20.5 14.8A8.2 8.2 0 0 1 9.2 3.5 7.2 7.2 0 1 0 20.5 14.8z" /></svg>
            </button>
            <span className="theme-tip">Day or night — the work keeps running.</span>
          </div>
          <a href="#book" className="btn btn-primary btn-sm">start a workflow →</a>
        </div>
      </div>
    </header>
  );
}

// ─── Yellow-pad → clean data animation (replaces the terminal) ───────────────
const PF_NOTES = [
  { tone: 'yellow', txt: "INV-04821 — $2,431.80, who approves??", pos: { top: 2, left: '1%', width: '50%' }, rot: -5 },
  { tone: 'pink',   txt: "call Maria back re: claim PA-88", pos: { top: 0, left: '53%', width: '45%' }, rot: 4 },
  { tone: 'blue',   txt: "Dr. Lee — 3 intake forms waiting", pos: { top: 76, left: '6%', width: '48%' }, rot: -2 },
  { tone: 'green',  txt: "chase 4 unpaid — 14+ days late", pos: { top: 80, left: '55%', width: '43%' }, rot: 6 },
];

const PF_ROWS = [
  { k: 'invoices', v: '3 entered → QuickBooks' },
  { k: 'claims',   v: '2 filed → carrier portal' },
  { k: 'intake',   v: '3 logged → patient system' },
  { k: 'overdue',  v: '$2,431.80 flagged + chased' },
];

// phase timeline — each entry is the dwell before advancing
const PF_DELAYS = [420, 520, 520, 520, 560, 760, 620, 520, 380, 380, 380, 420, 2800];

function PaperFlow({ animate = true }) {
  const [step, setStep] = React.useState(animate ? 0 : 99);
  const [running, setRunning] = React.useState(animate);

  React.useEffect(() => {
    if (!running) return;
    if (step >= PF_DELAYS.length) {
      const t = setTimeout(() => setStep(0), 140);
      return () => clearTimeout(t);
    }
    const t = setTimeout(() => setStep(s => s + 1), PF_DELAYS[step]);
    return () => clearTimeout(t);
  }, [step, running]);

  const noteIn   = (i) => step >= i + 1;
  const scanning = step >= 5 && step < 7;
  const checked  = step >= 6;
  const collapsed = step >= 7;
  const rowIn    = (j) => step >= 8 + j;
  const summary  = step >= 12;

  return (
    <div className="paperflow" onClick={() => animate && setRunning(r => !r)}>
      <div className={'pf-pad' + (scanning ? ' scanning' : '')}>
        <div className="pf-pad-head">
          <span>the monday pile</span>
          <span className="pf-pad-count">{checked ? '✓ cleared' : '4 things on fire'}</span>
        </div>
        <div className="pf-notes">
          {PF_NOTES.map((n, i) => (
            <div
              key={i}
              className={'pf-note pf-' + n.tone + (noteIn(i) ? ' in' : '') + (checked ? ' done' : '') + (collapsed ? ' gone' : '')}
              style={{ top: n.pos.top, left: n.pos.left, width: n.pos.width, '--rot': n.rot + 'deg' }}
            >
              <span className="pf-note-txt">{n.txt}</span>
              <span className="pf-note-tick">✓</span>
            </div>
          ))}
        </div>
        <div className="pf-scan" />
      </div>

      <div className={'pf-link' + (collapsed ? ' on' : '')}>
        <span className="pf-link-mark">$ spndly</span>
        {collapsed ? ' read it all and filed everything →' : ' is reading the pile…'}
      </div>

      <div className="pf-out">
        <div className="pf-out-head">
          <span>today's work</span>
          <span className="pf-live">● auto</span>
        </div>
        {PF_ROWS.map((it, j) => (
          <div key={j} className={'pf-row' + (rowIn(j) ? ' in' : '')}>
            <span className="pf-k">{it.k}</span>
            <span className="pf-v">{it.v}</span>
            <span className="pf-ck">✓</span>
          </div>
        ))}
        <div className={'pf-summary' + (summary ? ' in' : '')}>
          ≈ <b>9 hrs/week</b> of paperwork — done before you got in.
        </div>
      </div>
    </div>
  );
}

function Hero({ showDemo = true } = {}) {
  return (
    <section className="hero" id="top" data-screen-label="01 hero">
      <div className="container hero-grid">
        <div>
          <div className="hero-eyebrow"><span className="dot" /> operations engineering · healthcare &amp; insurance</div>
          <h1 className="h1">
            the work is<br />
            <span className="strike">too manual</span> to scale.<br />
            <span className="green">we automate it.</span>
          </h1>
          <p className="lead">
            Spndly builds automation for document-heavy teams: intake, claims, reports, review queues, billing follow-up, and the operational workflows that slow everyone down.
          </p>
          <div className="cta-row">
            <a href="#book" className="btn btn-primary">map a workflow →</a>
            <a href="#cases" className="btn btn-secondary">→ see body of work</a>
          </div>
          <ProofBar />
        </div>
        <div>
          <PaperFlow animate={showDemo} />
          <div className="mono-xs" style={{ marginTop: 12, textAlign: 'center' }}>↑ an example monday pile → clean data · click to pause</div>
        </div>
      </div>
    </section>
  );
}

function ProofBar() {
  const items = [
    { k: 'Healthcare & insurance', v: 'document-heavy operations' },
    { k: 'Review-first', v: 'people stay where it counts' },
    { k: 'Performance-aligned', v: "you don't pay until it saves time" },
    { k: 'Your existing stack', v: 'nothing to rip out or migrate' },
  ];
  return (
    <div className="proof">
      {items.map((c, i) => (
        <div className="proof-item" key={i}>
          <div className="proof-k">{c.k}</div>
          <div className="proof-v">{c.v}</div>
        </div>
      ))}
    </div>
  );
}

// ── Refined hero visual: a calm "operations handled" panel ──
function OpsPanel({ animate = true }) {
  const ROWS = [
    { k: 'Invoices', v: <>3 reconciled in <b>QuickBooks</b></> },
    { k: 'Claims', v: <>2 filed to the carrier portal</> },
    { k: 'Patient intake', v: <>3 forms routed for review</> },
    { k: 'Overdue', v: <><b>$2,431.80</b> flagged &amp; chased</> },
  ];
  const [step, setStep] = React.useState(animate ? 0 : 99);

  React.useEffect(() => {
    if (!animate) return;
    const seq = [520, 700, 700, 700, 720]; // reveal 4 rows, then the summary — once
    if (step >= seq.length) return;          // hold the completed state (no loop)
    const t = setTimeout(() => setStep(s => s + 1), seq[step]);
    return () => clearTimeout(t);
  }, [step, animate]);

  const rowIn = (i) => step >= i + 1;
  const footIn = step >= 5;

  // Count the "9 hrs" stat up from 0 once the footer reveals.
  const reduceM = typeof window !== 'undefined' && window.matchMedia
    && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  const [hrs, setHrs] = React.useState((animate && !reduceM) ? 0 : 9);
  React.useEffect(() => {
    if (reduceM || !animate) { setHrs(9); return; }
    if (!footIn) return;                     // hold at 0 until the footer reveals
    let raf, start = null;
    const tick = (ts) => {
      if (start == null) start = ts;
      const p = Math.min(1, (ts - start) / 850);
      setHrs(Math.round((1 - Math.pow(1 - p, 3)) * 9));   // easeOutCubic → 9
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [footIn, reduceM, animate]);

  return (
    <div className="ops">
      <div className="ops-head">
        <div>
          <div className="ops-title">This week — handled</div>
          <div className="ops-sub">Back-office work, completed automatically</div>
        </div>
        <span className="ops-live"><span className="ops-pip" /> Live</span>
      </div>
      <div className="ops-rows">
        {ROWS.map((r, i) => (
          <div className={'ops-row' + (rowIn(i) ? ' in' : '')} key={i}>
            <span className="ops-k">{r.k}</span>
            <span className="ops-v">{r.v}</span>
            <span className="ops-check" aria-hidden="true">
              <svg viewBox="0 0 16 16" width="11" height="11" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M3.5 8.5 L6.5 11.5 L12.5 5" /></svg>
            </span>
          </div>
        ))}
      </div>
      <div className={'ops-foot' + (footIn ? ' in' : '')}>
        <div className="ops-foot-stat">
          <div className="ops-foot-label">Reclaimed this week</div>
          <div className="ops-foot-val">{hrs}<span className="ops-foot-unit">hrs</span></div>
          <div className="ops-foot-cap">≈ <b>a full workday</b>, handled before you clock in.</div>
        </div>
        <svg className="ops-foot-spark" viewBox="0 0 96 46" aria-hidden="true">
          <path className="ops-spark-area" d="M2 38 C 16 35, 24 31, 34 27 C 46 22, 54 16, 64 12 C 74 8, 82 6, 94 3 L94 44 L2 44 Z"></path>
          <path className="ops-spark-line" d="M2 38 C 16 35, 24 31, 34 27 C 46 22, 54 16, 64 12 C 74 8, 82 6, 94 3"></path>
          <circle className="ops-spark-dot" cx="94" cy="3" r="3.2"></circle>
        </svg>
      </div>
    </div>
  );
}

Object.assign(window, { Nav, Hero, PaperFlow, SpndlyMark, OpsPanel, ProofBar });
