/* global React */
function HowTheAgentWorks() {
  const [active, setActive] = React.useState(0);
  const stepsRef = React.useRef([]);

  React.useEffect(() => {
    let raf = 0;

    const updateActiveStep = () => {
      raf = 0;
      const readingLine = window.innerHeight * 0.45;
      let nextActive = 0;
      let closest = Infinity;

      stepsRef.current.forEach((el, i) => {
        if (!el) return;
        const rect = el.getBoundingClientRect();
        const containsLine = rect.top <= readingLine && rect.bottom >= readingLine;
        const distance = containsLine
          ? 0
          : Math.min(Math.abs(rect.top - readingLine), Math.abs(rect.bottom - readingLine));

        if (distance < closest) {
          closest = distance;
          nextActive = i;
        }
      });

      setActive(nextActive);
    };

    const requestUpdate = () => {
      if (raf) return;
      raf = window.requestAnimationFrame(updateActiveStep);
    };

    updateActiveStep();
    window.addEventListener('scroll', requestUpdate, { passive: true });
    window.addEventListener('resize', requestUpdate);

    return () => {
      if (raf) window.cancelAnimationFrame(raf);
      window.removeEventListener('scroll', requestUpdate);
      window.removeEventListener('resize', requestUpdate);
    };
  }, []);

  const steps = [
    {
      no: "01", kicker: "INBOUND", ts: "T+0.0s",
      title: <>The customer <em>opens a thread.</em></>,
      what: "Rachel is on the webchat at 14:02. She's been a customer for 18 months. The agent has her identity before she's even finished typing.",
      annot: <>The conversation isn't a blank slate. The agent loads her <strong>three-tier living profile</strong> — narrative, structured fields, freeform memory — from your database the moment the session opens.</>,
      annotRef: "N. 01 · IDENTITY",
      card: (
        <div className="wt-card message user">
          <span className="who">Rachel · 14:02</span>
          I was charged twice for my last order. Can you check?
        </div>
      ),
    },
    {
      no: "02", kicker: "RECALL", ts: "T+0.4s",
      title: <>Look up <em>who she is.</em></>,
      what: "Before composing a single token of reply, the agent reads from your stack. Identity, recency, language preference, last-known mood. None of this is invented.",
      annot: <>Memory lives in <strong>your DB</strong>, not ours. The agent reads it. The agent writes back to it. If you fire us, the profile keeps existing.</>,
      annotRef: "N. 02 · MEMORY",
      card: (
        <div className="wt-card">
          <div className="lookup-head">
            <span>TOOL</span>
            <span className="src">customer.fetch_profile</span>
            <span className="ms">38 ms</span>
          </div>
          <div className="kv">
            <span className="k">customer_id</span><span className="v">cus_8K2J4N</span>
            <span className="k">name</span><span className="v">Rachel Mendez</span>
            <span className="k">tenure</span><span className="v">18 months</span>
            <span className="k">tier</span><span className="v">core</span>
            <span className="k">language</span><span className="v">en-US</span>
            <span className="k">last_seen</span><span className="v">whatsapp · 6d ago</span>
            <span className="k">narrative</span><span className="v"><em>"polite, prefers concise replies, has had one prior billing question (resolved positively)"</em></span>
          </div>
        </div>
      ),
    },
    {
      no: "03", kicker: "RETRIEVE", ts: "T+0.7s",
      title: <>Pull her order from <em>Stripe.</em></>,
      what: "She said 'last order' — the agent resolves what that means, calls Stripe directly, and finds the duplicate authorization without asking for an order number.",
      annot: <>This is one of <strong>1,000+ native integrations</strong> in your retainer. Stripe, your CRM, your helpdesk. No surcharge per call.</>,
      annotRef: "N. 03 · TOOLS",
      card: (
        <div className="wt-card">
          <div className="lookup-head">
            <span>TOOL</span>
            <span className="src">stripe.charges.list</span>
            <span className="ms">112 ms</span>
          </div>
          <div className="kv">
            <span className="k">params</span><span className="v">{`{ customer: "cus_8K2J4N", limit: 5 }`}</span>
            <span className="k">→ ch_3NQp...4l</span><span className="v">$34.99 · order #8472 · 09:14:02</span>
            <span className="k">→ ch_3NQp...8m</span><span className="v warn">$34.99 · order #8472 · 09:14:09 ⚠ duplicate</span>
            <span className="k">→ ch_3NRb...2k</span><span className="v">$24.50 · order #8390 · 6d ago</span>
          </div>
        </div>
      ),
    },
    {
      no: "04", kicker: "DECIDE", ts: "T+0.9s",
      title: <>Confirm the <em>duplicate.</em></>,
      what: "Two charges, same amount, seven seconds apart, same order. The procedure is clear: refund the duplicate, no human needed. The reasoning is logged for the audit trail.",
      annot: <>The procedure that fires here is <strong>readable, version-controlled, and editable</strong> by your team. No vendor ticket. No black box.</>,
      annotRef: "N. 04 · PROCEDURE",
      card: (
        <div className="wt-card">
          <div className="lookup-head">
            <span>PROCEDURE</span>
            <span className="src">billing/duplicate_charge_refund.md</span>
            <span className="ms">v.4</span>
          </div>
          <div className="kv">
            <span className="k">match</span><span className="v found">same order_id · same amount · &lt; 60s apart</span>
            <span className="k">authority</span><span className="v">refund up to $500 without human review</span>
            <span className="k">action</span><span className="v"><em>refund ch_3NQp...8m</em></span>
            <span className="k">log</span><span className="v">audit_trail.write(...)</span>
          </div>
        </div>
      ),
    },
    {
      no: "05", kicker: "EXECUTE", ts: "T+1.3s",
      title: <>Issue the refund — <em>inside the conversation.</em></>,
      what: "Not a ticket. Not a callback. The refund is committed to Stripe before the agent has even finished its reply.",
      annot: <>No human paged. No ticket opened. The thread <strong>is</strong> the resolution surface.</>,
      annotRef: "N. 05 · NO HAND-OFF",
      card: (
        <div className="wt-card success">
          <div className="lookup-head">
            <span>TOOL</span>
            <span className="src">stripe.refunds.create</span>
            <span className="ms">204 ms</span>
          </div>
          <div className="kv">
            <span className="k">charge</span><span className="v">ch_3NQp...8m</span>
            <span className="k">amount</span><span className="v">$34.99</span>
            <span className="k">reason</span><span className="v">duplicate</span>
            <span className="k">status</span><span className="v found">refunded · re_1Pq...zX</span>
          </div>
        </div>
      ),
    },
    {
      no: "06", kicker: "REPLY", ts: "T+1.6s",
      title: <>Tell her, <em>in her voice.</em></>,
      what: "The reply is brief, because her profile says she prefers concise. It cites the order, the amount, and the timeline — no filler.",
      annot: <>The brand voice is <strong>configured, not prompted</strong>. It lives in your account. You edit it without asking us.</>,
      annotRef: "N. 06 · BRAND VOICE",
      card: (
        <div className="wt-card message">
          <span className="pill">CX · Agent</span>
          <span className="who">CX · Agent · 14:02</span>
          Found it — duplicate $34.99 charge on order #8472. Refund is already processing; you'll see it back in 1–2 business days.
        </div>
      ),
    },
  ];
  const activeStep = steps[active] || steps[0];

  return (
    <section className="spread walkthrough" id="how">
      <div className="section-folio">
        <span className="num">§ 02</span><span>How the agent works</span><hr/><span>Annotated, step by step</span>
      </div>
      <h2 className="spread-title reveal">A real conversation. <em>Read out in the open.</em></h2>
      <p className="spread-dek reveal">
        Most AI demos hide the work. This is the work — every lookup, every decision, every tool call the agent made to resolve a $34.99 duplicate charge. <em>Inside the conversation. Without paging a human, opening a ticket, or losing the thread.</em>
      </p>

      <div className="walkthrough-grid">
        <aside className="wt-rail">
          {steps.map((s, i) => (
            <div
              key={s.no}
              className={`wt-rail-item ${active === i ? 'active' : ''}`}
              onClick={() => stepsRef.current[i]?.scrollIntoView({behavior:'smooth', block:'center'})}
            >
              <span className="num">{s.no}</span>
              {s.kicker}
            </div>
          ))}
        </aside>

        <div className="wt-flow">
          {steps.map((s, i) => (
            <article
              className="wt-step reveal"
              key={s.no}
              ref={(el) => stepsRef.current[i] = el}
            >
              <div className="meta">
                <span className="step-no">STEP {s.no}</span>
                <span>·</span>
                <span>{s.kicker}</span>
                <span className="ts">{s.ts}</span>
              </div>
              <h3>{s.title}</h3>
              <div className="what">{s.what}</div>
              {s.card}
            </article>
          ))}
        </div>

        <aside className="wt-annot-panel" aria-live="polite">
          <div className="wt-annot wt-annot-active" key={activeStep.no}>
            <span className="ref">{activeStep.annotRef}</span>
            <span className="wt-annot-copy">{activeStep.annot}</span>
          </div>
          <div className="wt-annot-progress" aria-hidden="true">
            {steps.map((s, i) => (
              <span
                key={s.no}
                className={`wt-annot-dot ${active === i ? 'active' : ''}`}
              />
            ))}
          </div>
        </aside>
      </div>

      {/* Closing — "the next day" */}
      <div className="wt-close reveal">
        <p className="pull-q">
          The next day she comes back — <em>on WhatsApp this time</em> — and asks about her shipping. The agent already knows about yesterday's refund.
        </p>
        <div className="epilogue">
          <div className="epi-msg user">
            <span className="who">Rachel · WhatsApp · next day, 09:41</span>
            Hey — any update on when my order ships?
          </div>
          <div className="epi-msg">
            <span className="who">CX · Agent · 09:41</span>
            Hi Rachel — the refunded charge cleared overnight. Your original order #8472 is on the truck for delivery tomorrow between 2–6 PM.
          </div>
        </div>
      </div>
    </section>
  );
}

window.HowTheAgentWorks = HowTheAgentWorks;
