/* Mesh website — hero right-side visual: an animated, self-running product UI.
   Replaces the abstract canvas with a real-looking Mesh app surface that bleeds
   off the right edge of the hero (à la a product screenshot). It plays one
   "close run" on a loop: gather vendor costs → reconcile → estimate the missing
   accrual → post to the ERP, with the checklist ticking and the ledger filling.
   prefers-reduced-motion → jumps straight to the finished, fully-closed state. */

(function () {
  const fmt = (n) => '$' + Math.round(n).toLocaleString('en-US');
  const reduced = () => typeof window.matchMedia === 'function'
    && window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  const NAV_TOP = [
    { ic: 'layout-grid', label: 'Home' },
    { ic: 'list-checks', label: 'Tasks', badge: '4' },
    { ic: 'inbox', label: 'Inbox' },
  ];
  const NAV_CLOSE = [
    { ic: 'calculator', label: 'Accruals', active: true },
    { ic: 'git-compare', label: 'Reconciliations' },
    { ic: 'book-open', label: 'Journal entries' },
    { ic: 'shield-check', label: 'Audit trail' },
  ];
  const NAV_CONN = [
    { ic: 'plug', label: 'Connected sources' },
    { ic: 'refresh-cw', label: 'ERP sync' },
    { ic: 'file-code-2', label: 'Policies' },
  ];

  const TASKS = [
    { ic: 'inbox', label: 'Collect vendor costs', sub: '5 sources · AP inbox' },
    { ic: 'git-compare', label: 'Reconcile to contracts', sub: 'PO ↔ invoice match' },
    { ic: 'wand-2', label: 'Estimate missing accruals', sub: 'policy v4' },
    { ic: 'arrow-up-from-line', label: 'Post journal entries', sub: '→ NetSuite' },
  ];

  const ROWS = [
    { v: 'Ramp', ic: 'credit-card', sub: 'card · ap-inbox', amt: 24500 },
    { v: 'AWS', ic: 'cloud', sub: 'usage · ap-inbox', amt: 88240 },
    { v: 'Gusto', ic: 'users', sub: 'payroll · ap-inbox', amt: 16080 },
    { v: 'Notion', ic: 'file-text', sub: 'saas · ap-inbox', amt: 4200 },
    { v: 'Salesforce', ic: 'wand-2', sub: 'estimated · policy v4', amt: 9600, est: true },
  ];

  function useCloseRun() {
    // rowN: ledger rows revealed (0..5) · taskN: tasks completed (0..4) · done
    const [s, setS] = React.useState({ rowN: 0, taskN: 0, done: false });
    React.useEffect(() => {
      if (reduced()) { setS({ rowN: ROWS.length, taskN: TASKS.length, done: true }); return; }
      const timers = [];
      const at = (ms, fn) => timers.push(setTimeout(fn, ms));
      function run() {
        setS({ rowN: 0, taskN: 0, done: false });
        let t = 560;
        // gather the 4 sourced rows
        for (let i = 1; i <= 4; i++) { const n = i; at(t, () => setS(p => ({ ...p, rowN: n }))); t += 440; }
        t += 260;
        at(t, () => setS(p => ({ ...p, taskN: 1 })));            // collected
        t += 720;
        at(t, () => setS(p => ({ ...p, taskN: 2 })));            // reconciled
        t += 720;
        at(t, () => setS(p => ({ ...p, rowN: 5 })));             // estimated row appears
        at(t + 240, () => setS(p => ({ ...p, taskN: 3 })));      // estimated
        t += 900;
        at(t, () => setS(p => ({ ...p, taskN: 4, done: true }))); // posted → closed
        at(t + 2800, run);                                       // hold, then loop
      }
      run();
      return () => timers.forEach(clearTimeout);
    }, []);
    return s;
  }

  function NavItem({ item, on }) {
    return (
      <div className={'pf-nav-item' + (item.active ? ' active' : '') + (on ? ' lit' : '')}>
        <span className="pf-nav-ic"><Icon name={item.ic} className="ic" /></span>
        <span className="pf-nav-label">{item.label}</span>
        {item.badge && <span className="pf-nav-badge">{item.badge}</span>}
      </div>
    );
  }

  function PlatformUI() {
    const { rowN, taskN, done } = useCloseRun();
    const shown = ROWS.slice(0, rowN);
    const total = shown.reduce((a, r) => a + r.amt, 0);

    return (
      <div className="pf" aria-hidden="true">
        {/* ---------- sidebar ---------- */}
        <aside className="pf-side">
          <div className="pf-brand">
            <img className="pf-brand-logo" src={window.__assets("mesh-logo-blue.png")} alt="Mesh" />
            <Icon name="panel-left-close" className="pf-brand-collapse" />
          </div>
          <div className="pf-search"><Icon name="search" className="ic" /><span>Search</span><span className="pf-kbd">⌘K</span></div>

          <nav className="pf-navgroup">
            {NAV_TOP.map((it) => <NavItem key={it.label} item={it} />)}
          </nav>
          <div className="pf-navhead">Close</div>
          <nav className="pf-navgroup">
            {NAV_CLOSE.map((it) => <NavItem key={it.label} item={it} />)}
          </nav>
          <div className="pf-navhead">Connected</div>
          <nav className="pf-navgroup">
            {NAV_CONN.map((it) => <NavItem key={it.label} item={it} />)}
          </nav>
          <div className="pf-side-foot">
            <span className="pf-ai-ic"><Icon name="sparkles" className="ic" /></span>
            <span>Mesh AI</span>
          </div>
        </aside>

        {/* ---------- main ---------- */}
        <main className="pf-main">
          <div className="pf-head">
            <div>
              <div className="pf-eyebrow">Month-end close</div>
              <h3 className="pf-title">Accruals</h3>
            </div>
            <div className="pf-head-right">
              <div className="pf-entity">
                <span className="pf-entity-av">AC</span>
                Acme Corp · May 2026
                <Icon name="chevrons-up-down" className="pf-entity-chev" />
              </div>
              <span className={'pf-status' + (done ? ' done' : '')}>
                <Icon name={done ? 'check' : 'loader'} className="ic" />
                {done ? 'Closed' : 'In progress'}
              </span>
            </div>
          </div>

          {/* close checklist */}
          <section className="pf-card">
            <div className="pf-card-head">
              <span className="pf-card-title">Close checklist</span>
              <span className="pf-card-meta">{taskN} / {TASKS.length}</span>
            </div>
            <div className="pf-tasks">
              {TASKS.map((t, i) => {
                const complete = i < taskN;
                const activeNow = i === taskN && !done;
                return (
                  <div className={'pf-task' + (complete ? ' done' : '') + (activeNow ? ' active' : '')} key={t.label}>
                    <span className={'pf-check' + (complete ? ' on' : '')}>
                      {complete
                        ? <Icon name="check" className="ic" />
                        : (activeNow ? <Icon name="loader" className="ic" /> : null)}
                    </span>
                    <span className="pf-task-ic"><Icon name={t.ic} className="ic" /></span>
                    <div className="pf-task-tx">
                      <div className="pf-task-label">{t.label}</div>
                      <div className="pf-task-sub">{t.sub}</div>
                    </div>
                    {complete && <span className="pf-task-flag">Done</span>}
                  </div>
                );
              })}
            </div>
          </section>

          {/* accruals ledger */}
          <section className="pf-card">
            <div className="pf-card-head">
              <div className="pf-tabs">
                <span className="pf-tab active">All accruals <span className="pf-tab-n">{rowN}</span></span>
                <span className="pf-tab">Posted</span>
              </div>
              <span className={'pf-erp' + (done ? ' on' : '')}>
                <span className="pf-erp-logo">NS</span>{done ? 'Posted to NetSuite' : 'NetSuite'}
              </span>
            </div>
            <div className="pf-ledger">
              {ROWS.map((r, i) => {
                const on = i < rowN;
                return (
                  <div className={'pf-row' + (on ? ' in' : '')} key={r.v} style={{ display: on ? 'flex' : 'none' }}>
                    <span className="pf-row-ic"><Icon name={r.ic} className="ic" /></span>
                    <div className="pf-row-tx">
                      <div className="pf-row-v">{r.v}{r.est && <span className="pf-est">EST</span>}</div>
                      <div className="pf-row-sub">{r.sub}</div>
                    </div>
                    <span className="pf-row-amt">{fmt(r.amt)}</span>
                    <span className={'pf-row-tick' + (done ? ' done' : '')}>
                      <Icon name={done ? 'check' : 'circle-dashed'} className="ic" />
                    </span>
                  </div>
                );
              })}
            </div>
            <div className="pf-total">
              <span>Total accrued</span>
              <span className="pf-total-amt">{fmt(total)}</span>
            </div>
          </section>
        </main>
      </div>
    );
  }

  window.PlatformUI = PlatformUI;
})();
