/* global React, SiteIcon, Sparkle, Reveal, useInView, CountUp */

function Grip() {
  return (
    <svg className="grip" width="10" height="14" viewBox="0 0 10 14" fill="currentColor" aria-hidden="true">
      <circle cx="2.5" cy="2.5" r="1.3"/><circle cx="7.5" cy="2.5" r="1.3"/>
      <circle cx="2.5" cy="7" r="1.3"/><circle cx="7.5" cy="7" r="1.3"/>
      <circle cx="2.5" cy="11.5" r="1.3"/><circle cx="7.5" cy="11.5" r="1.3"/>
    </svg>
  );
}

/* Storefront "Check private offer" widget, live timer, then a negotiation
   where the shopper pushes back and the offer bumps 9% → 12%. */
function StoreWidget(props) {
  const loop = props && props.loop;
  const [ref, inView] = useInView({ threshold: 0.35, once: !loop });
  const startSecs = 19 * 60 + 46; // 19:46
  const [secs, setSecs] = React.useState(startSecs);
  const [phase, setPhase] = React.useState(0); // 0 initial · 1 shopper asked (typing) · 2 bumped offer

  React.useEffect(() => {
    if (window.REDUCED) return;
    const id = setInterval(() => setSecs((s) => (s > 0 ? s - 1 : 0)), 1000);
    return () => clearInterval(id);
  }, []);

  React.useEffect(() => {
    if (!inView || window.REDUCED) return;
    let timers = [];
    const run = () => {
      setPhase(0);
      const a = setTimeout(() => setPhase(1), 3800);
      const b = setTimeout(() => setPhase(2), 7200);
      const cycle = loop ? [a, b, setTimeout(run, 13000)] : [a, b];
      timers = cycle;
    };
    run();
    return () => timers.forEach(clearTimeout);
  }, [inView, loop]);

  const mm = String(Math.floor(secs / 60)).padStart(2, "0");
  const ss = String(secs % 60).padStart(2, "0");

  const renderOffer = (p, isBump) => (
    <div className={`sf-offer ${isBump ? "bumped" : ""}`}>
      <div className="sf-offer-h"><SiteIcon name="lock" size={13}/>{isBump ? "Your new private offer" : "Private offer, just for you"}</div>
      <div className="sf-pct">{p.pct}% off</div>
      <div className="sf-row"><span className="lab">Original</span><span className="amt">$629.95</span></div>
      <div className="sf-row save"><span className="lab">You save</span><span className="amt">−${p.save}</span></div>
      <div className="sf-div"></div>
      <div className="sf-row total"><span className="lab">New total</span><span className="amt">${p.total}</span></div>
      <div className="sf-timer"><SiteIcon name="clock" size={13}/>Offer expires in <b>{mm}:{ss}</b></div>
      <button className="sf-apply">Apply offer &amp; checkout <SiteIcon name="arrowRight" size={15}/></button>
      <div className="sf-note">This offer is private and expires when the timer runs out</div>
    </div>
  );

  return (
    <div className="sf-widget" ref={ref}>
      <div className="sf-head">
        <div className="sf-avatar"><Sparkle size={16} color="#fff"/></div>
        <div className="sf-who">
          <div className="n">Jordan</div>
          <div className="r">Deal specialist</div>
        </div>
        <div className="sf-x">×</div>
      </div>
      <div className="sf-body">
        <div className="sf-from">Jordan</div>
        <div className="sf-msg">Good eye on the Multi managed Snowboard. I can offer you a private discount on this cart, just for you, never a public code.</div>
        {renderOffer({ pct: 9, save: "56.70", total: "573.25" }, false)}
        {phase >= 1 && <div className="sf-bubble user">Is there any chance of a better price? This is a gift for my son.</div>}
        {phase === 1 && <div className="sf-typing"><i></i><i></i><i></i></div>}
        {phase >= 2 && <div className="sf-bubble jordan">A gift for your son deserves a little extra, I've bumped you to 12% off. Hope he loves it.</div>}
        {phase >= 2 && renderOffer({ pct: 12, save: "75.59", total: "554.36" }, true)}
      </div>
      <div className="sf-input">
        <span className="ph">Type a message…</span>
        <span className="send"><SiteIcon name="arrowRight" size={15}/></span>
      </div>
      <div className="sf-powered">Powered by <b>DealAgent AI</b></div>
    </div>
  );
}

/* AI ↔ AI negotiation simulation, streams in when scrolled into view */
function AIChat() {
  const [ref, inView] = useInView({ threshold: 0.4 });
  const msgs = [
    { side: "bot", who: "ShopBot · for shopper", text: <>Buying the Multi managed Snowboard for my user. Cart is <b>$629.95</b>, what's your best price?</> },
    { side: "da", who: "DealAgent · for merchant", text: <>This cart qualifies for a private offer. Let me find a good deal for your shopper.</> },
    { side: "bot", who: "ShopBot · for shopper", text: <>My user wants <b>20% off</b>.</> },
    { side: "da", who: "DealAgent · for merchant", text: <>20% isn't available on this cart. Best I can do is <b>9% off + free shipping</b>, private, just for your shopper.</> },
    { side: "bot", who: "ShopBot · for shopper", text: <>Accepted on the shopper's behalf.</> },
  ];
  const total = msgs.length + 1; // + outcome
  const [n, setN] = React.useState(window.REDUCED ? total : 0);

  React.useEffect(() => {
    if (!inView || window.REDUCED) return;
    const timers = [];
    for (let i = 1; i <= total; i++) {
      timers.push(setTimeout(() => setN(i), 500 + i * 850));
    }
    return () => timers.forEach(clearTimeout);
  }, [inView, total]);

  return (
    <div className="ac-panel" ref={ref}>
      <div className="ac-head"><span className="dot"></span>Agentic Offer API · live</div>
      <div className="ac-thread">
        {msgs.map((m, i) => (
          n > i ? (
            <div className={`ac-msg ${m.side}`} key={i}>
              <div className="ac-who">{m.side === "da" ? <><Sparkle size={9} color="#116DFF"/>{m.who}</> : m.who}</div>
              {m.text}
            </div>
          ) : null
        ))}
        {n > msgs.length && (
          <div className="ac-outcome">
            <SiteIcon name="check" size={14} stroke={3}/>
            Checkout completed · $573.25 · <span className="ok">margin protected</span>
          </div>
        )}
      </div>
    </div>
  );
}

function FlowArrow() {
  return (
    <div className="arrow">
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
    </div>
  );
}

function HowItWorksPage() {
  const Check = () => <SiteIcon name="check" size={17} stroke={2.5}/>;

  return (
    <>
      {/* Header */}
      <header className="hiw-hero">
        <div className="container">
          <Reveal><div className="eyebrow"><Sparkle size={12} color="#116DFF"/>How it works</div></Reveal>
          <Reveal delay={60}><h1>From your rules to a <span className="agent">closed, profitable deal</span> automatically.</h1></Reveal>
          <Reveal delay={120}><p className="lead">DealAgent sits on your side of the checkout. You set the guardrails once; it negotiates every private offer against them for human shoppers and AI shopping agents alike.</p></Reveal>

          <Reveal delay={180}>
            <div className="hiw-flow">
              <div className="node">
                <div className="ic"><SiteIcon name="scroll" size={18}/></div>
                <div className="t">Your rules</div>
                <div className="d">Margin floors, max discounts, levers, and protected products.</div>
              </div>
              <FlowArrow/>
              <div className="node">
                <div className="ic"><SiteIcon name="handshake" size={18}/></div>
                <div className="t">DealAgent negotiates</div>
                <div className="d">A private offer is proposed, countered, or declined in real time.</div>
              </div>
              <FlowArrow/>
              <div className="node">
                <div className="ic"><SiteIcon name="shield" size={18}/></div>
                <div className="t">Margin safe sale</div>
                <div className="d">The cart converts at a price that protects your contribution margin.</div>
              </div>
            </div>
          </Reveal>
        </div>
      </header>

      {/* Step 1, Guardrails */}
      <section className="hiw-step">
        <div className="container">
          <div className="inner">
            <Reveal className="copy">
              <div>
                <div className="step-n">STEP 01</div>
                <h2>Set your guardrails once.</h2>
                <p>Tell DealAgent what a good deal looks like for your business. Define a contribution margin floor or a maximum discount, choose how much autonomy to grant, and pick which levers it's allowed to pull. Everything else follows these rules.</p>
                <div className="hiw-points">
                  <div className="p"><Check/><span><b>Margin floors or max discounts</b>, per category, product, or campaign. Offers below the floor are auto declined.</span></div>
                  <div className="p"><Check/><span><b>Autonomy you control</b>, auto negotiate, medium, or manual approval, switchable per policy.</span></div>
                  <div className="p"><Check/><span><b>Preferred levers</b>, bundles, free shipping, or private discounts, in the order you prefer.</span></div>
                  <div className="p"><Check/><span><b>Protected products</b>, lock launches and hero SKUs out of any discount.</span></div>
                </div>
              </div>
            </Reveal>
            <Reveal delay={120}>
              <div className="hiw-mock">
                <div className="mh">
                  <span className="mt"><SiteIcon name="scroll" size={15}/>Deal policy · Bundle First</span>
                  <span className="badge">Active</span>
                </div>
                <div className="hpol">
                  <div className="field">
                    <div className="lab"><span>Margin rules</span></div>
                    <div className="pol-opts">
                      <div className="opt on"><div className="ot">Max discount</div><div className="od">No cost data needed</div></div>
                      <div className="opt"><div className="ot">Margin floor</div><div className="od">Requires product costs</div></div>
                    </div>
                  </div>
                  <div className="field">
                    <div className="lab"><span>Maximum discount</span><span className="val">15%</span></div>
                    <div className="track"><div className="fill"></div><div className="knob"></div></div>
                  </div>
                  <div className="field">
                    <div className="lab"><span>Offer preferences</span></div>
                    <div className="pol-toggles">
                      <div className="tg"><Grip/>Bundle offer<span className="pill-state on">On</span></div>
                      <div className="tg"><Grip/>Free shipping<span className="pill-state on">On</span></div>
                      <div className="tg"><Grip/>Private discount<span className="pill-state on">On</span></div>
                      <div className="tg"><Grip/>Gift with purchase<span className="pill-state off">Off</span></div>
                    </div>
                  </div>
                  <div className="field">
                    <div className="lab"><span>Autonomy</span></div>
                    <div className="pol-toggles">
                      <div className="tg">Auto negotiate<span className="sw on"></span></div>
                      <div className="tg">Enable AI agent API<span className="sw on"></span></div>
                    </div>
                  </div>
                </div>
              </div>
            </Reveal>
          </div>
        </div>
      </section>

      {/* Step 2, Negotiate */}
      <section className="hiw-step flip">
        <div className="container">
          <div className="inner">
            <Reveal className="copy">
              <div>
                <div className="step-n">STEP 02</div>
                <h2>DealAgent negotiates the offer.</h2>
                <p>When a shopper clicks “Check private offer”, or an AI shopping agent calls the Agentic Offer API, DealAgent evaluates the cart against your rules and responds in milliseconds. It approves, counters, or declines, always with a reason.</p>
                <div className="hiw-points">
                  <div className="p"><Check/><span><b>Reads the full context</b>, cart value, margin, inventory age, and customer segment.</span></div>
                  <div className="p"><Check/><span><b>Picks the right lever</b>, a bundle or free shipping before ever touching unit price.</span></div>
                  <div className="p"><Check/><span><b>Counters out of bounds asks</b>, never just says no; proposes a profitable alternative.</span></div>
                </div>
              </div>
            </Reveal>
            <Reveal delay={120}>
              <div className="hiw-mock">
                <div className="mh">
                  <span className="mt"><span className="dot"></span>Negotiation · #C41200</span>
                  <span className="badge">Live</span>
                </div>
                <div className="hneg">
                  <div className="ev in">
                    <div className="who">AI agent · openshop</div>
                    Requests <b>20% off</b> on a $1,184.00 cart.
                  </div>
                  <div className="ev da">
                    <div className="who"><Sparkle size={11} color="#116DFF"/>DealAgent</div>
                    20% would break your 40% margin floor. Countering with an <b>8% private discount + bundle</b> that holds margin.
                  </div>
                  <div className="offer">
                    <span className="l">Counter offer sent</span>
                    <span className="r">8% + bundle · <span className="ok">41% margin</span></span>
                  </div>
                </div>
              </div>
            </Reveal>
          </div>
        </div>
      </section>

      {/* Step 3, Convert */}
      <section className="hiw-step">
        <div className="container">
          <div className="inner">
            <Reveal className="copy">
              <div>
                <div className="step-n">STEP 03</div>
                <h2>Convert safely, and see why.</h2>
                <p>The shopper or agent accepts a private offer that never appears as a public code. Every decision is logged with the cart context, the lever chosen, and the margin it protected, fully auditable, anytime.</p>
                <div className="hiw-points">
                  <div className="p"><Check/><span><b>No public discount leak</b>, private offers never reach coupon sites.</span></div>
                  <div className="p"><Check/><span><b>Margin protected on every sale</b>, the floor you set is the floor that holds.</span></div>
                  <div className="p"><Check/><span><b>Auditable decisions</b>, a structured reason behind every approve, counter, or decline.</span></div>
                </div>
              </div>
            </Reveal>
            <Reveal delay={120}>
              <div className="hiw-mock">
                <div className="mh">
                  <span className="mt"><SiteIcon name="shield" size={15}/>Decision</span>
                  <span className="badge">Margin safe</span>
                </div>
                <div className="hdec">
                  <div className="seal"><SiteIcon name="check" size={26} stroke={3}/></div>
                  <div className="v">Approved</div>
                  <div className="s">8% private discount + bundle · free shipping</div>
                  <div className="reasons">
                    <div className="r"><SiteIcon name="check" size={15} stroke={2.5}/>Contribution margin holds at 41%</div>
                    <div className="r"><SiteIcon name="check" size={15} stroke={2.5}/>Within medium autonomy band</div>
                    <div className="r"><SiteIcon name="check" size={15} stroke={2.5}/>No protected product affected</div>
                  </div>
                  <div className="outcome">
                    <span className="k">Cart converted</span>
                    <span className="vv">$1,089.00 · margin protected</span>
                  </div>
                </div>
              </div>
            </Reveal>
          </div>
        </div>
      </section>

      {/* Two audiences */}
      <section className="hiw-aud wrap">
        <div className="container">
          <Reveal><div className="eyebrow">One engine, two audiences</div></Reveal>
          <Reveal delay={60}><h2 className="h2">The same rules serve <span className="agent">humans and AI shoppers.</span></h2></Reveal>
          <div className="hiw-aud-grid">
            <Reveal delay={80}>
              <div className="aud-card human">
                <div className="ic"><SiteIcon name="cart" size={22}/></div>
                <h3>Human shoppers</h3>
                <p className="card-cap">A “Check private offer” widget lives in your cart. Here's exactly what a shopper sees:</p>
                <StoreWidget/>
              </div>
            </Reveal>
            <Reveal delay={160}>
              <div className="aud-card ai">
                <div className="ic"><SiteIcon name="terminal" size={22}/></div>
                <h3>AI shopping agents</h3>
                <p className="card-cap">When an AI agent checks out on a shopper's behalf, it negotiates with DealAgent through the Agentic Offer API, in milliseconds, under the same guardrails:</p>
                <AIChat/>
              </div>
            </Reveal>
          </div>
        </div>
      </section>

      {/* Reuse: live guardrails check */}
      {window.Guardrails ? <window.Guardrails/> : null}

      {/* Reuse: final CTA + footer */}
      {window.FinalCTA ? <window.FinalCTA/> : null}
      {window.Footer ? <window.Footer/> : null}
    </>
  );
}

window.HowItWorksPage = HowItWorksPage;
window.StoreWidget = StoreWidget;
window.AIChat = AIChat;
