/* Mesh website — signals band, feature row, feature cards */

function Signals() {
  // source categories Mesh listens to — scrolled as a right-to-left marquee
  const cats = [
    { label: 'PROCUREMENT', icons: ['proc_coupa', 'proc_zip'] },
    { label: 'EMAILS', icons: ['email_gmail', 'email_outlook'] },
    { label: 'DATABASE', icons: ['db_snowflake', 'db_bigquery', 'db_dots'] },
    { label: 'MESSAGES', icons: ['msg_slack', 'msg_teams'] },
  ];
  // repeat enough times that one half of the track already overflows the viewport,
  // so the translateX(-50%) reset is seamless (no gap / jump)
  const loop = [...cats, ...cats, ...cats, ...cats, ...cats, ...cats];

  return (
    <section className="signals">
      <div className="wrap">
        <div className="signals-hub signals-hub-center">
          Aggregates real-time signals from the tools your team already uses
        </div>
      </div>
      <div className="marquee" aria-hidden="true">
        <div className="marquee-track">
          {loop.map((cat, i) => (
            <div className="cat-card" key={i}>
              <div className="cat-label">{cat.label}</div>
              <div className="cat-icons">
                {cat.icons.map((ic, j) => (
                  <span className="cat-icon" key={j} style={{ marginLeft: j ? -10 : 0, zIndex: cat.icons.length - j }}>
                    <img src={window.__assets("brands/" + ic + ".png")} alt="" />
                  </span>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* Scroll-driven: highlight steps 1→3 and swap the matching panel */
const STEPS = [
  {
    lead: 'Centralize',
    rest: 'scattered vendor & stakeholder context',
    title: 'vendor context · unified',
    icon: 'layers',
  },
  {
    lead: 'Collect',
    rest: 'missing data from connected sources',
    title: 'outreach · auto-collected',
    icon: 'inbox',
  },
  {
    lead: 'Estimate',
    rest: 'accurate incurred spend per vendor',
    title: 'estimated incurred spend',
    icon: 'sparkles',
  },
];

/* Source categories Mesh aggregates — the integration tiles used on the site */
const VC_CATS = [
  { label: 'Procurement', logos: ['proc_coupa', 'proc_zip'] },
  { label: 'Emails', logos: ['email_gmail', 'email_outlook'] },
  { label: 'Database', logos: ['db_snowflake', 'db_bigquery'] },
  { label: 'Messages', logos: ['msg_slack', 'msg_teams'] },
];

/* Panel body that matches each step */
function StepPanel({ step }) {
  if (step === 0) {
    // Centralize — the Mesh integration cluster: every source tile, grouped
    return (
      <div className="sp-body">
        <div className="vc-grid">
          {VC_CATS.map(cat => (
            <div className="vc-cat" key={cat.label}>
              <span className="vc-cat-label">{cat.label}</span>
              <div className="vc-logos">
                {cat.logos.map(l => (
                  <span className="vc-logo" key={l}><img src={window.__assets("brands/" + l + ".png")} alt="" /></span>
                ))}
              </div>
            </div>
          ))}
        </div>
        <div className="vc-foot"><span className="vc-check"><Icon name="check" className="ic" /></span> Consolidated into one vendor view</div>
      </div>
    );
  }
  if (step === 1) {
    // Collect — automated outreach for the gaps
    return (
      <div className="sp-body">
        {[
          { ic: 'email_gmail', who: 'Notion', msg: 'Requesting May usage statement…', st: 'Sent', ok: false },
          { ic: 'msg_slack', who: '#finance', msg: 'Confirm AWS commit accrual?', st: 'Replied', ok: true },
          { ic: 'email_outlook', who: 'Gusto', msg: 'Headcount × rate for May', st: 'Replied', ok: true },
        ].map((r, i) => (
          <div className="sp-msg" key={i}>
            <span className="sp-msg-ic"><img src={window.__assets("brands/" + r.ic + ".png")} alt="" /></span>
            <div className="sp-msg-tx"><div className="sp-msg-who">{r.who}</div><div className="sp-msg-body">{r.msg}</div></div>
            <span className={'sp-stat ' + (r.ok ? 'ok' : '')}>{r.st}</span>
          </div>
        ))}
      </div>
    );
  }
  // Estimate — per-vendor incurred spend with confidence + total
  return (
    <div className="sp-body">
      {[['Ramp', '$24,500', 98], ['AWS', '$88,240', 95], ['Gusto', '$16,080', 99], ['Notion', '$4,200', 88]].map(([v, a, conf]) => (
        <div className="sp-est" key={v}>
          <span className="sp-est-v">{v}</span>
          <span className="sp-est-bar"><span className="sp-est-fill" style={{ width: conf + '%' }}></span></span>
          <span className="sp-num">{a}</span>
        </div>
      ))}
      <div className="sp-total"><span>Total incurred · May</span><span className="sp-num">$132,820</span></div>
    </div>
  );
}

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

  React.useEffect(() => {
    const section = sectionRef.current;
    if (!section) return;
    let raf = 0;
    const apply = () => {
      raf = 0;
      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;
      // 3 equal bands → active step 0,1,2
      const idx = Math.min(2, Math.floor(p * 3 + 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);
    return () => { window.removeEventListener('scroll', onScroll); window.removeEventListener('resize', onScroll); cancelAnimationFrame(raf); };
  }, []);

  return (
    <section className="tg" id="product" ref={sectionRef}>
      <div className="tg-stage">
        <div className="wrap frow tg-grid">
          <div className="ftext">
            <h2 className="tg-title">
              The trust and governance layer for your agentic close
            </h2>
            <p className="streamline-lead">
              We streamline the <span className="ul-sketch">accruals process</span> in 3 ways:
            </p>
            <ol className="steps3">
              {STEPS.map((s, i) => (
                <li className={'step3' + (i === active ? ' active' : '') + (i < active ? ' done' : '')} key={s.lead}>
                  <span className="step3-num">{i + 1}</span>
                  <span className="step3-text"><strong>{s.lead}</strong> {s.rest}</span>
                </li>
              ))}
            </ol>
          </div>

          <div className="tg-panelwrap">
            <div className="panel tg-panel">
              <div className="panel-bar">
                <Icon name={STEPS[active].icon} className="ic" style={{ width: 15, height: 15, color: 'var(--brand)' }} />
                <span className="panel-title">{STEPS[active].title}</span>
                <span className="tg-step-pill">Step {active + 1} / 3</span>
              </div>
              <div className="panel-body tg-panel-body">
                {STEPS.map((s, i) => (
                  <div className={'tg-slide' + (i === active ? ' show' : '')} key={i} aria-hidden={i !== active}>
                    <StepPanel step={i} />
                  </div>
                ))}
              </div>
            </div>
            <div className="tg-dots">
              {STEPS.map((s, i) => (
                <span className={'tg-dot' + (i === active ? ' on' : '')} key={i}></span>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Signals, ScriptFeature });
