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

/* ---- Storefront scene: recreates the live store + cart + Jordan widget ---- */
function StorefrontScene() {
  const StoreWidget = window.StoreWidget;
  return (
    <div className="ss-frame hopt-fade">
      <div className="ss-bar">
        <span className="dot"></span><span className="dot"></span><span className="dot"></span>
        <span className="url">lumen-store.myshopify.com/products/snowboard</span>
      </div>
      <div className="ss-scene">
        <div className="ss-store">
          <div className="ss-topnav">
            <span>Home</span><span>Catalog</span><span>Contact</span>
            <span className="brand">Deal Agent</span>
            <span className="sp"></span>
            <SiteIcon name="cart" size={17}/>
          </div>
          <div className="ss-prod">
            <div className="ss-board"><div className="b"></div><div className="b"></div></div>
            <div className="ss-pinfo">
              <div className="vendor">Multi managed Vendor</div>
              <h2>The Multi managed Snowboard</h2>
              <div className="price">$629.95</div>
              <span className="b-add">Add to cart</span>
              <span className="b-buy">Buy it now</span>
            </div>
          </div>
        </div>
        <div className="ss-scrim"></div>

        <div className="ss-cart">
          <div className="ct-h"><span className="t">Your cart</span><span className="x">✕</span></div>
          <div className="ct-cols"><span>Product</span><span>Total</span></div>
          <div className="ct-item">
            <div className="thumb"></div>
            <div><div className="nm">The Multi managed Snowboard</div><div style={{ fontSize: 12, color: "#888", marginTop: 2 }}>$629.95</div></div>
            <div className="pr">$629.95</div>
          </div>
          <div className="ct-foot">
            <div className="ct-sub"><span className="l">Subtotal</span><span className="v">$629.95 USD</span></div>
            <div className="ct-note">Taxes and shipping calculated at checkout</div>
            <span className="ct-private"><Sparkle size={13} color="#fff"/>Check Private Offer</span>
            <span className="ct-checkout">Check out</span>
          </div>
        </div>

        <div className="ss-widget">
          {StoreWidget ? <StoreWidget loop={true}/> : null}
        </div>
      </div>
    </div>
  );
}

/* ---- AI-to-AI hero negotiation ---- */
function AIChatHero() {
  const [ref, inView] = useInView({ threshold: 0.35 });
  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;
  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), 400 + i * 850));
    return () => timers.forEach(clearTimeout);
  }, [inView, total]);

  return (
    <div className="achero hopt-fade" ref={ref}>
      <div className="achero-head">
        <div className="achero-agent bot">
          <div className="av"><SiteIcon name="cart" size={19}/></div>
          <div><div className="nm">ShopBot</div><div className="rl">Shopper's AI agent</div></div>
        </div>
        <div className="vs"><span className="dot"></span>Live negotiation</div>
        <div className="achero-agent da">
          <div className="av"><Sparkle size={17} color="#fff"/></div>
          <div><div className="nm">DealAgent</div><div className="rl">Your AI agent</div></div>
        </div>
      </div>
      <div className="achero-body">
        <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>
    </div>
  );
}

/* ---- Hero shell with switchable centerpiece ---- */
function HeroOptions() {
  const [mode, setMode] = React.useState("store");
  return (
    <section className="hero" id="top">
      <div className="hero-grid-floor"></div>
      <div className="container">
        <div className="eyebrow"><span className="pip"></span>Your own AI agent that negotiates deals for you</div>
        <h1 className="h1" style={{ color: "#070B1F", fontSize: 64, lineHeight: 1.04, letterSpacing: "-0.03em", fontWeight: 700, maxWidth: 880, margin: "20px auto 18px", textWrap: "balance" }}>
          Your AI <span className="agent">deal desk</span> for ecommerce.
        </h1>
        <p className="lead">
          Set your margin rules or max discounts. DealAgent negotiates private, profitable offers
          with shoppers and <b style={{ color: "var(--fg-1)", fontWeight: 600 }}>AI shopping agents</b>, without ever leaking a public discount.
        </p>

        <div className="hopt-toggle">
          <button className={mode === "store" ? "on" : ""} onClick={() => setMode("store")}>
            <SiteIcon name="cart" size={15}/>Storefront widget
          </button>
          <button className={mode === "ai" ? "on" : ""} onClick={() => setMode("ai")}>
            <Sparkle size={13} color={mode === "ai" ? "#fff" : "#116DFF"}/>AI to AI negotiation
          </button>
        </div>

        <div className="hopt-stage">
          {mode === "store" ? <StorefrontScene key="store"/> : <AIChatHero key="ai"/>}
        </div>
      </div>
    </section>
  );
}

window.HeroOptions = HeroOptions;
window.StorefrontScene = StorefrontScene;
window.AIChatHero = AIChatHero;

/* Animated headline for the homepage hero */
function HHTitle() {
  const [inn, setInn] = React.useState(false);
  React.useEffect(() => {
    const t = setTimeout(() => setInn(true), 60);
    return () => clearTimeout(t);
  }, []);
  return (
    <h1 className={`h1 hero-title ${inn ? "in" : ""}`}>
      <span className="h1-line l1">Your AI <span className="agent">deal desk</span></span>
      <span className="h1-line l2">for ecommerce.</span>
    </h1>
  );
}

/* Homepage hero: header + the storefront / AI-to-AI toggle centerpiece */
/* OpenAI / ChatGPT logomark */
function OpenAILogo({ size = 16 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
      <path d="M22.28 9.82a5.98 5.98 0 0 0-.52-4.91 6.05 6.05 0 0 0-6.51-2.9A6.07 6.07 0 0 0 4.98 4.18a5.98 5.98 0 0 0-3.99 2.9 6.05 6.05 0 0 0 .74 7.1 5.98 5.98 0 0 0 .51 4.91 6.05 6.05 0 0 0 6.51 2.9A5.98 5.98 0 0 0 13.26 24a6.06 6.06 0 0 0 5.77-4.21 5.99 5.99 0 0 0 4-2.9 6.05 6.05 0 0 0-.75-7.07zM13.26 22.43a4.48 4.48 0 0 1-2.88-1.04l.14-.08 4.78-2.76a.8.8 0 0 0 .39-.68v-6.74l2.02 1.17a.07.07 0 0 1 .04.05v5.58a4.5 4.5 0 0 1-4.49 4.5zM3.6 18.3a4.47 4.47 0 0 1-.54-3.01l.14.08 4.79 2.76a.77.77 0 0 0 .78 0l5.84-3.37v2.33a.08.08 0 0 1-.03.06L9.74 19.95a4.5 4.5 0 0 1-6.14-1.65zM2.34 7.9a4.49 4.49 0 0 1 2.37-1.98v5.69a.77.77 0 0 0 .39.68l5.81 3.35-2.02 1.17a.08.08 0 0 1-.07 0l-4.83-2.78A4.5 4.5 0 0 1 2.34 7.9zm16.6 3.86l-5.84-3.39 2.02-1.16a.08.08 0 0 1 .07 0l4.83 2.79a4.49 4.49 0 0 1-.68 8.1v-5.68a.79.79 0 0 0-.4-.66zm2-3.02l-.14-.09-4.77-2.78a.78.78 0 0 0-.79 0L9.41 9.23V6.9a.07.07 0 0 1 .03-.06l4.83-2.79a4.5 4.5 0 0 1 6.68 4.66zM8.31 12.86l-2.02-1.16a.08.08 0 0 1-.04-.06V6.07a4.5 4.5 0 0 1 7.38-3.45l-.14.08-4.78 2.76a.8.8 0 0 0-.39.68zm1.1-2.36l2.6-1.5 2.6 1.5v3l-2.6 1.5-2.6-1.5z"/>
    </svg>
  );
}

/* ---- Floating product cards that frame the cover ---- */
function HeroFloaters() {
  const Spark = window.Sparkle;
  // mobile: the two chat cards become a shuffleable deck (Flow Fest-style).
  // the front card sails up-and-over to the back; the other slides forward to the front.
  const DECK = ["chat", "bots"];
  const [stack, setStack] = React.useState(DECK);
  const [flinging, setFlinging] = React.useState(null);
  const [spins, setSpins] = React.useState(0);
  const tRef = React.useRef([]);
  const shuffle = () => {
    if (flinging) return;                       // ignore taps mid-shuffle
    setFlinging(stack[0]);
    setSpins((n) => n + 1);
    // re-order partway through so the rest of the deck shifts up as the top card sails over
    tRef.current.push(setTimeout(() => setStack((s) => [...s.slice(1), s[0]]), 270));
    tRef.current.push(setTimeout(() => setFlinging(null), 590));
  };
  React.useEffect(() => () => tRef.current.forEach(clearTimeout), []);
  const sp = (id) => stack.indexOf(id);
  return (
    <div className="hero-floaters">
      {/* Shopper mix — top left */}
      <div className={"hf-wrap hf-policy" + (flinging === "policy" ? " flinging" : "")} style={{ "--d": 1 }} data-sp={sp("policy")} onClick={shuffle}>
        <div className="hf-inner"><div className="hf-card hf-fa">
          <div className="hf-ch">
            <span className="hf-ic blue"><SiteIcon name="gauge" size={15}/></span>
            <div className="hf-ct"><div className="hf-ct-t">Who's buying</div><div className="hf-ct-s">Last 30 days</div></div>
          </div>
          <div className="hf-mixbar"><span className="ai" style={{ width: "68%" }}></span><span className="hu" style={{ width: "32%" }}></span></div>
          <div className="hf-mixlegend">
            <div className="lg"><span className="dot ai"></span>AI shopping agents<b>68%</b></div>
            <div className="lg"><span className="dot hu"></span>Human shoppers<b>32%</b></div>
          </div>
          <div className="hf-mixfoot"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 14 12 8 18 14"/></svg>AI agents up 182% this quarter</div>
        </div></div>
      </div>

      {/* Jordan widget — bottom left (mirrors the real storefront widget) */}
      <div className={"hf-wrap hf-chat" + (flinging === "chat" ? " flinging" : "")} style={{ "--d": 1.6 }} data-sp={sp("chat")} onClick={shuffle}>
        <div className="hf-inner"><div className="hf-card hf-widget hf-fb">
          <div className="hfw-head">
            <span className="hfw-av">{Spark ? <Spark size={14} color="#fff"/> : null}</span>
            <div className="hfw-who"><div className="n">Jordan</div><div className="r">Deal specialist</div></div>
            <span className="hfw-x">×</span>
          </div>
          <div className="hfw-body">
            <div className="hfw-from">Jordan</div>
            <div className="hfw-msg">A gift for your son deserves a little extra — here's a private offer, just for you.</div>
            <div className="hfw-offer">
              <div className="hfw-offer-h"><SiteIcon name="lock" size={11}/>Private offer, just for you</div>
              <div className="hfw-pct">12% off</div>
              <div className="hfw-row total"><span className="lab">New total</span><span className="amt">$554.36</span></div>
              <button className="hfw-apply" tabIndex="-1">Apply offer &amp; checkout</button>
            </div>
          </div>
          <div className="hfw-powered">Powered by <b>DealAgent AI</b></div>
        </div></div>
      </div>

      {/* AI-to-AI with ChatGPT — top right */}
      <div className={"hf-wrap hf-bots" + (flinging === "bots" ? " flinging" : "")} style={{ "--d": 1.4 }} data-sp={sp("bots")} onClick={shuffle}>
        <div className="hf-inner"><div className="hf-card hf-fc">
          <div className="hf-ch double">
            <span className="hf-av-logo gpt"><OpenAILogo size={17}/></span>
            <span className="hf-vs"><span className="vsdot"></span>Agent negotiation</span>
            <span className="hf-av blue">{Spark ? <Spark size={14} color="#fff"/> : null}</span>
          </div>
          <div className="hf-msg shopper sm"><span className="who">ChatGPT · for shopper</span>Best price on this cart?</div>
          <div className="hf-msg agent sm"><span className="who">DealAgent</span>9% off + free shipping, private to your shopper.</div>
          <div className="hf-result"><SiteIcon name="check" size={13} stroke={3}/>Checkout $573.25 · <b>margin protected</b></div>
        </div></div>
      </div>

      {/* Sales through DealAgent — bottom right */}
      <div className={"hf-wrap hf-metric" + (flinging === "metric" ? " flinging" : "")} style={{ "--d": 1 }} data-sp={sp("metric")} onClick={shuffle}>
        <div className="hf-inner"><div className="hf-card hf-fd">
          <div className="hf-ch">
            <div className="hf-ct">
              <div className="hf-ct-s">Sales through DealAgent · total</div>
              <div className="hf-metric-big">$30,432</div>
            </div>
            <span className="hf-delta"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 14 12 8 18 14"/></svg>12.1%</span>
          </div>
          <div className="hf-bars">
            <span style={{ height: "38%" }}></span><span style={{ height: "52%" }}></span><span style={{ height: "44%" }}></span>
            <span style={{ height: "66%" }}></span><span style={{ height: "58%" }}></span><span style={{ height: "80%" }}></span>
            <span style={{ height: "72%" }}></span><span className="hot" style={{ height: "100%" }}></span>
          </div>
          <div className="hf-metric-foot">312 offers accepted this month</div>
        </div></div>
      </div>

      <button type="button" className="hf-shuffle" onClick={shuffle} aria-label="Shuffle cards">
        <span className="hf-shuffle-ic" style={{ transform: `rotate(${spins * -360}deg)` }}><SiteIcon name="refresh" size={16}/></span>
        Shuffle
      </button>
    </div>
  );
}

/* Homepage hero: full-height cover + scroll-revealed widget demo */
function HomeHero() {
  const [mode, setMode] = React.useState("store");
  const [cardsIn, setCardsIn] = React.useState(false);
  const coverRef = React.useRef(null);

  React.useEffect(() => {
    const t = setTimeout(() => setCardsIn(true), 220);
    return () => clearTimeout(t);
  }, []);

  // gentle mouse parallax on the floating cards (desktop, motion-allowed)
  React.useEffect(() => {
    if (window.REDUCED) return;
    const el = coverRef.current;
    if (!el || !window.matchMedia("(pointer:fine)").matches) return;
    let raf = null;
    const onMove = (e) => {
      if (raf) return;
      const r = el.getBoundingClientRect();
      const mx = ((e.clientX - r.left) / r.width - 0.5) * 2;
      const my = ((e.clientY - r.top) / r.height - 0.5) * 2;
      raf = requestAnimationFrame(() => {
        raf = null;
        el.style.setProperty("--mx", (mx * 9).toFixed(2));
        el.style.setProperty("--my", (my * 9).toFixed(2));
      });
    };
    el.addEventListener("mousemove", onMove);
    return () => el.removeEventListener("mousemove", onMove);
  }, []);

  return (
    <>
      <section className={`hero hero-cover ${cardsIn ? "cards-in" : ""}`} id="top" ref={coverRef}>
        <div className="hero-grid-floor"></div>
        <HeroFloaters/>
        <div className="container hero-cover-inner">
          <div className="eyebrow"><span className="pip"></span><span className="eb-full">Your own AI agent that negotiates deals for you</span><span className="eb-mobile">Your own AI deal agent</span></div>
          <HHTitle/>
          <p className="lead">
            Set your margin rules or max discounts. DealAgent negotiates private, profitable offers
            with shoppers and <b style={{ color: "var(--fg-1)", fontWeight: 600 }}>AI shopping agents</b>, without ever leaking a public discount.
          </p>
          <div className="hero-cta">
            <Magnetic strength={0.3}><a className="btn btn-primary btn-lg" href="https://apps.shopify.com/dealagent-ai" target="_blank" rel="noopener">Activate My AI Deal Agent</a></Magnetic>
            <a className="btn btn-ghost-dark btn-lg" href="how-it-works.html">See how it works →</a>
          </div>
          <div className="hero-meta">
            <span className="hero-meta-item"><span className="v"><CountUp value={312}/></span> brands running deal policies</span>
            <span className="hero-meta-item"><span className="v"><CountUp value={4.2} decimals={1} prefix="$" suffix="M"/></span> margin protected this month</span>
            <span className="hero-meta-item"><span className="v"><CountUp value={1.2} decimals={1} suffix="M"/></span> AI agent offer requests</span>
          </div>
        </div>
        <a className="hero-scrollcue" href="#demo" aria-label="Scroll to see DealAgent negotiate">
          <span className="hsc-label">See it negotiate</span>
          <span className="hsc-mouse"><span className="hsc-wheel"></span></span>
        </a>
      </section>

      <section className="hero-demo" id="demo">
        <div className="container">
          <div className="hero-demo-head">
            <div className="eyebrow" style={{ justifyContent: "center" }}><span className="pip"></span>Live demo</div>
            <h2 className="h2">Watch DealAgent negotiate <span className="agent">in real time.</span></h2>
            <p className="lead">The same engine handles human shoppers and the AI agents shopping for them. Toggle to see each.</p>
          </div>

          <div className="hopt-toggle">
            <button className={mode === "store" ? "on" : ""} onClick={() => setMode("store")}>
              <SiteIcon name="cart" size={15}/>For human shoppers
            </button>
            <button className={mode === "ai" ? "on" : ""} onClick={() => setMode("ai")}>
              <Sparkle size={13} color={mode === "ai" ? "#fff" : "#116DFF"}/>For AI shopping agents
            </button>
          </div>

          <div className="hopt-stage">
            {mode === "store" ? <StorefrontScene key="store"/> : <AIChatHero key="ai"/>}
          </div>
        </div>
      </section>
    </>
  );
}

window.HomeHero = HomeHero;
