/* Mesh website — "From month-end marathon to a script that just runs":
   the usemesh.com scroll-driven flow. A pinned section advances an active
   step 0→3; the left rail highlights/expands the active step while the right
   panel cross-fades to the matching product mockup. */

const FLOW = [
  {
    title: 'Centralize your vendor context',
    desc: 'We analyze vendor invoicing patterns across data in procurement systems, shared AP inboxes, contracts, and journal entries.',
  },
  {
    title: 'Encode your accounting judgment',
    desc: 'Define how accruals and prepaids should work once. Mesh applies that logic consistently, month after month.',
  },
  {
    title: 'Review flagged exceptions',
    desc: 'We cut review time by surfacing only what needs attention: missing assumptions, material period-over-period changes, and items requiring human judgment.',
  },
  {
    title: 'Maintain a bullet-proof audit trail',
    desc: 'Every number carries a complete, time-stamped lineage, sources, assumptions, and approvals, so audits become a query, not a fire drill.',
  },
];

/* ----- per-step panel mockups ----- */

function CFPanelCentralize() {
  const logos = ['proc_coupa', 'email_gmail', 'db_snowflake', 'msg_slack'];
  return (
    <div className="cf-pad">
      <div className="cf-row-label">Invoice</div>
      <div className="cf-drop">
        <span className="cf-drop-ic"><Icon name="upload-cloud" className="ic" /></span>
        <div className="cf-drop-tx">Click to upload document<br />or drag your CSV file here</div>
        <span className="cf-drop-file"><Icon name="file-spreadsheet" className="ic" /> Notion_May_usage.csv</span>
      </div>
      <div className="cf-src">
        <div className="cf-src-logos">
          {logos.map((l, i) => (
            <span className="cf-src-logo" key={l} style={{ zIndex: logos.length - i }}><img src={window.__assets("brands/" + l + ".png")} alt="" /></span>
          ))}
        </div>
        <span className="cf-src-cap">Procurement · AP inbox · Contracts · Journal Entries</span>
      </div>
      <div className="cf-foot"><span className="btn btn-primary cf-submit">Submit</span></div>
    </div>
  );
}

function CFPanelEncode() {
  return (
    <div className="cf-pad">
      <div className="cf-rulehd">
        <span className="cf-back"><Icon name="chevron-left" className="ic" /></span>
        <div>
          <div className="cf-rule-title">Customer Rule Set v10</div>
          <div className="cf-rule-sub">PO Received</div>
        </div>
        <span className="cf-pill-muted">Inactive</span>
      </div>
      <div className="cf-meta">
        <div><span className="cf-meta-k">Created Date</span><span className="cf-meta-v">Oct 29, 2025 · 10:15 AM</span></div>
        <div><span className="cf-meta-k">Created By</span><span className="cf-meta-v">Alice Smith</span></div>
      </div>
      <div className="cf-tabs">
        <span className="cf-tab on"><Icon name="file-text" className="ic" /> Description</span>
        <span className="cf-tab"><Icon name="settings" className="ic" /> Configure</span>
      </div>
      <div className="cf-rule">
        <div className="cf-rule-r1"><span>1. Missing PO Dates</span><Icon name="more-horizontal" className="ic" /></div>
        <p>Return $0 with escalation because PO Start Date and/or End Date is missing or malformed.</p>
      </div>
    </div>
  );
}

function CFPanelReview() {
  const flags = [
    { ic: 'alert-triangle', tone: 'warn', t: 'Missing assumption', s: 'Notion · May usage statement not provided', pill: 'Needs input' },
    { ic: 'trending-up', tone: 'info', t: 'Material change', s: 'AWS accrual +38% vs. April', pill: 'Review' },
    { ic: 'scale', tone: 'judge', t: 'Needs judgment', s: 'Legal retainer, accrual vs. prepaid', pill: 'Confirm' },
  ];
  return (
    <div className="cf-pad">
      {flags.map((f, i) => (
        <div className="cf-flag" key={i}>
          <span className={'cf-flag-ic ' + f.tone}><Icon name={f.ic} className="ic" /></span>
          <div className="cf-flag-tx">
            <div className="cf-flag-t">{f.t}</div>
            <div className="cf-flag-s">{f.s}</div>
          </div>
          <span className={'cf-flag-pill ' + f.tone}>{f.pill}</span>
        </div>
      ))}
      <div className="cf-flag-foot"><Icon name="check-circle-2" className="ic" /> 3 of 142 entries flagged · 139 auto-cleared</div>
    </div>
  );
}

function CFPanelAudit() {
  const events = [
    { time: '10:15:02', t: 'Source ingested', s: 'Coupa PO #4821 · 3 line items', done: true },
    { time: '10:15:04', t: 'Rule applied', s: 'Customer Rule Set v10', done: true },
    { time: '10:16:11', t: 'Estimate posted', s: 'Notion accrual · $4,200', done: true },
    { time: '10:18:37', t: 'Approved', s: 'Alice Smith · Controller', done: false },
  ];
  return (
    <div className="cf-pad">
      <div className="cf-tl">
        {events.map((e, i) => (
          <div className={'cf-tl-row' + (e.done ? ' done' : '')} key={i}>
            <span className="cf-tl-time">{e.time}</span>
            <div className="cf-tl-main">
              <span className="cf-tl-dot"></span>
              <span className="cf-tl-line"></span>
              <div className="cf-tl-t">{e.t}</div>
              <div className="cf-tl-s">{e.s}</div>
            </div>
          </div>
        ))}
      </div>
      <div className="cf-flag-foot"><Icon name="shield-check" className="ic" /> Immutable, exportable lineage for every figure</div>
    </div>
  );
}

const CF_PANELS = [CFPanelCentralize, CFPanelEncode, CFPanelReview, CFPanelAudit];

/* One rail step + its stacked mobile panel. On phones (≤880px) the panels
   stack and fade in as they scroll into view; on desktop the class is inert. */
function CFStepPair({ step, index, active, onJump }) {
  const [ref, inView] = useReveal();
  const Panel = CF_PANELS[index];
  return (
    <div className={'cf-step-pair' + (inView ? ' m-in' : '')} ref={ref}>
      <button
        type="button"
        className={'cf-step' + (index === active ? ' active' : '')}
        onClick={() => onJump(index)}
        aria-expanded={index === active}
      >
        <h3>{step.title}</h3>
        <div className="cf-step-desc"><div><p>{step.desc}</p></div></div>
      </button>
      <div className="cf-mobile-panel">
        <div className="panel cf-panel">
          <Panel />
        </div>
      </div>
    </div>
  );
}

function CloseFlow() {
  const sectionRef = React.useRef(null);
  const [active, setActive] = React.useState(0);

  React.useEffect(() => {
    const section = sectionRef.current;
    if (!section) return;
    let raf = 0;
    // Phones show the stacked static layout (kit.css); skip the scroll math.
    const MOBILE_MQ = window.matchMedia('(max-width: 880px)');
    const apply = () => {
      raf = 0;
      if (MOBILE_MQ.matches) return;
      const vh = window.innerHeight || 800;
      const total = section.offsetHeight - vh;
      const top = section.getBoundingClientRect().top;
      const p = total > 0 ? Math.min(Math.max(-top / total, 0), 1) : 0;
      const idx = Math.min(FLOW.length - 1, Math.floor(p * FLOW.length + 0.0001));
      setActive(prev => (prev === idx ? prev : idx));
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(apply); };
    apply();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    if (MOBILE_MQ.addEventListener) MOBILE_MQ.addEventListener('change', onScroll);
    else if (MOBILE_MQ.addListener) MOBILE_MQ.addListener(onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      if (MOBILE_MQ.removeEventListener) MOBILE_MQ.removeEventListener('change', onScroll);
      else if (MOBILE_MQ.removeListener) MOBILE_MQ.removeListener(onScroll);
      cancelAnimationFrame(raf);
    };
  }, []);

  const jumpTo = (i) => {
    if (window.matchMedia('(max-width: 880px)').matches) return; // no scroll-jump on phones
    const section = sectionRef.current;
    if (!section) return;
    const vh = window.innerHeight || 800;
    const total = section.offsetHeight - vh;
    const railTop = section.getBoundingClientRect().top + window.scrollY;
    const target = railTop + ((i + 0.5) / FLOW.length) * total;
    window.scrollTo({ top: target, behavior: 'smooth' });
  };

  return (
    <section className="cf" id="features" ref={sectionRef}>
      <div className="cf-stage">
        <div className="wrap">
          <div className="section-head center cf-head">
            <h2>From month-end marathon<br />to a script that just runs.</h2>
          </div>
          <div className="cf-grid">
            <div className="cf-rail">
              {FLOW.map((s, i) => (
                <CFStepPair key={s.title} step={s} index={i} active={active} onJump={jumpTo} />
              ))}
            </div>

            <div className="cf-panelwrap">
              <div className="panel cf-panel">
                <div className="cf-pbody">
                  {CF_PANELS.map((Panel, i) => (
                    <div className={'cf-slide' + (i === active ? ' show' : '')} key={i} aria-hidden={i !== active}>
                      <Panel />
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { CloseFlow });
