/* global React, Sparkle, CountUp, Magnetic, useInView, useParallax, REDUCED */

const { useState: useStateH, useEffect: useEffectH, useRef: useRefH } = React;

/* sidebar icons */
function NavIcon({ d }) {
  return (
    <svg className="ic" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">{d}</svg>
  );
}
const SBI = {
  dashboard: <><rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/></>,
  scroll: <><path d="M8 21h12a2 2 0 0 0 2-2v-2H10v2a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v3h4"/><path d="M19 17V5a2 2 0 0 0-2-2H4"/></>,
  sparkles: <><path d="m12 3-1.9 5.8a2 2 0 0 1-1.3 1.3L3 12l5.8 1.9a2 2 0 0 1 1.3 1.3L12 21l1.9-5.8a2 2 0 0 1 1.3-1.3L21 12l-5.8-1.9a2 2 0 0 1-1.3-1.3z"/></>,
  flask: <><path d="M9 3h6v3l5 11a3 3 0 0 1-2.7 4.2H6.7A3 3 0 0 1 4 17l5-11V3z"/><path d="M9 6h6"/></>,
  radio: <><circle cx="12" cy="12" r="2.5"/><path d="M16.2 7.8a6 6 0 0 1 0 8.5"/><path d="M7.8 16.2a6 6 0 0 1 0-8.5"/><path d="M19 5a10 10 0 0 1 0 14"/><path d="M5 19a10 10 0 0 1 0-14"/></>,
  lock: <><rect x="4" y="11" width="16" height="10" rx="2"/><path d="M8 11V7a4 4 0 1 1 8 0v4"/></>,
  package: <><path d="M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></>,
  chart: <><path d="M3 3v18h18"/><path d="M7 16V9"/><path d="M11 16v-5"/><path d="M15 16v-9"/><path d="M19 16v-3"/></>,
  terminal: <><path d="m7 11 2-2-2-2"/><path d="M11 13h4"/><rect x="3" y="3" width="18" height="18" rx="2"/></>,
};

/* self-drawing sparkline */
function MiniSparkline({ play }) {
  const d = "M2 34 L18 30 L32 32 L46 24 L60 26 L74 18 L90 20 L104 12 L120 14 L138 6";
  const area = d + " L138 44 L2 44 Z";
  return (
    <svg className="spark" viewBox="0 0 140 44" fill="none" preserveAspectRatio="none">
      <defs>
        <linearGradient id="sparkFill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#116DFF" stopOpacity="0.28"/>
          <stop offset="100%" stopColor="#116DFF" stopOpacity="0"/>
        </linearGradient>
      </defs>
      <path d={area} fill="url(#sparkFill)" style={{ opacity: play || REDUCED ? 1 : 0, transition: "opacity 0.6s ease 0.6s" }}/>
      <path d={d} stroke="#116DFF" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" fill="none"
        pathLength="1"
        style={{
          strokeDasharray: 1,
          strokeDashoffset: REDUCED ? 0 : (play ? 0 : 1),
          transition: "stroke-dashoffset 1.4s var(--ease-out)",
        }}/>
      <circle cx="138" cy="6" r="2.5" fill="#116DFF" style={{ opacity: play || REDUCED ? 1 : 0, transition: "opacity 0.3s ease 1.2s" }}/>
    </svg>
  );
}

/* typewriter for the copilot recommendation */
function useTypewriter(text, start, speed = 26) {
  const [out, setOut] = useStateH(REDUCED ? text : "");
  const [done, setDone] = useStateH(REDUCED);
  useEffectH(() => {
    if (!start || REDUCED) { if (REDUCED) setDone(true); return; }
    let i = 0; let t;
    const tick = () => {
      i++;
      setOut(text.slice(0, i));
      if (i < text.length) t = setTimeout(tick, speed);
      else setDone(true);
    };
    t = setTimeout(tick, speed);
    return () => clearTimeout(t);
  }, [start, text, speed]);
  return [out, done];
}

/* headline: simple, reliable reveal via CSS class toggled on mount */
function HeroTitle() {
  const [inn, setInn] = useStateH(false);
  useEffectH(() => {
    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>
  );
}

function Hero() {
  const [mockRef, mockIn] = useInView({ threshold: 0.25 });
  const parallaxRef = useParallax(0.06, 26);
  const frameRef = useRefH(null);

  // copilot typing
  const [typeStart, setTypeStart] = useStateH(false);
  useEffectH(() => {
    if (!mockIn) return;
    const t = setTimeout(() => setTypeStart(true), 650);
    return () => clearTimeout(t);
  }, [mockIn]);
  const [typed, typedDone] = useTypewriter("I found one margin safe offer for this cart. Recommended: ", typeStart, 18);

  // live negotiation row resolves
  const [resolved, setResolved] = useStateH(REDUCED);
  const [flash, setFlash] = useStateH(false);
  useEffectH(() => {
    if (!mockIn || REDUCED) return;
    const t1 = setTimeout(() => { setResolved(true); setFlash(true); }, 2600);
    const t2 = setTimeout(() => setFlash(false), 3400);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, [mockIn]);

  const logoLight = (window.__resources && window.__resources.logoHorizontal) || "assets/logo-horizontal.png";

  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>

        <HeroTitle/>

        <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">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 className="hero-mock" ref={mockRef}>
          <div className="hero-mock-frame" ref={(n) => { frameRef.current = n; parallaxRef.current = n; }}>
            <div className="hero-mock-bar">
              <span className="dot"></span><span className="dot"></span><span className="dot"></span>
              <span className="url">app.dealagent.ai/dashboard</span>
            </div>
            <div className="hero-mock-grid">
              <div className="hero-mock-sb">
                <img src={logoLight} alt="DealAgent"/>
                <div className="sect">Workspace</div>
                <div className="it active"><NavIcon d={SBI.dashboard}/>Dashboard</div>
                <div className="sect">Deal Engine</div>
                <div className="it"><NavIcon d={SBI.scroll}/>Deal Policies</div>
                <div className="it"><NavIcon d={SBI.sparkles}/>AI Deal Copilot</div>
                <div className="it"><NavIcon d={SBI.flask}/>Offer Simulator</div>
                <div className="it"><NavIcon d={SBI.radio}/>Live Negotiations</div>
                <div className="it"><NavIcon d={SBI.lock}/>Private Offers</div>
                <div className="it"><NavIcon d={SBI.package}/>Bundles</div>
                <div className="sect">Insights</div>
                <div className="it"><NavIcon d={SBI.chart}/>Analytics</div>
                <div className="it"><NavIcon d={SBI.terminal}/>Agent API</div>
              </div>

              <div className="hero-mock-body">
                <div className="hero-mock-top">
                  <div className="crumb">Lumen Store<span className="sep">/</span><b>Dashboard</b></div>
                  <div className="search">
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="7"/><path d="m20 20-3-3"/></svg>
                    Search policies, offers…
                  </div>
                  <div className="btn-sm"><Sparkle size={10} color="white"/>New deal policy</div>
                </div>

                <div className="hero-mock-content">
                  <div className="hero-mock-pagehead">
                    <div>
                      <h2>Dashboard</h2>
                      <div className="sub">Tuesday · 12 active negotiations · 7 deal policies live</div>
                    </div>
                  </div>

                  <div className="hero-mock-hero-metric">
                    <div>
                      <div className="l">Revenue recovered · last 30 days</div>
                      <div className="v"><CountUp value={42380} prefix="$" duration={1800}/></div>
                      <div className="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>
                        +18.4% vs. previous period
                      </div>
                    </div>
                    <MiniSparkline play={mockIn}/>
                  </div>

                  <div className="hero-mock-cards">
                    <div className="hero-mock-card"><div className="l">Margin protected</div><div className="v"><CountUp value={18940} prefix="$"/></div><div className="delta">+12.1%</div></div>
                    <div className="hero-mock-card"><div className="l">Offers accepted</div><div className="v"><CountUp value={312}/></div><div className="delta">+24 today</div></div>
                    <div className="hero-mock-card"><div className="l">Public discounts avoided</div><div className="v"><CountUp value={84}/></div><div className="delta">+9 this wk</div></div>
                    <div className="hero-mock-card"><div className="l">AOV lift</div><div className="v"><CountUp value={28.4} decimals={2} prefix="+$"/></div><div className="delta">+6.2%</div></div>
                    <div className="hero-mock-card"><div className="l">Bundle conversion</div><div className="v"><CountUp value={38} suffix="%"/></div><div className="delta">+3.4 pts</div></div>
                    <div className="hero-mock-card"><div className="l">AI agent requests</div><div className="v"><CountUp value={1204}/></div><div className="delta">+182%</div></div>
                  </div>

                  <div className="hero-mock-bottom">
                    <div className="dc-wrap">
                      <div className="dc-head">
                        <span className="t">Live negotiations</span>
                        <a className="open" href="#">View all</a>
                      </div>
                      <div className="lneg">
                      <table>
                        <thead>
                          <tr>
                            <th>Session</th><th>Buyer</th><th>Channel</th>
                            <th>Cart value</th><th>Offer</th><th>Status</th><th>Time</th><th></th>
                          </tr>
                        </thead>
                        <tbody>
                          <tr>
                            <td><span className="sesh">fieez8</span></td>
                            <td className="buyer">Human shopper</td>
                            <td><span className="pill chan-widget">Cart widget</span></td>
                            <td className="val">$749.95</td>
                            <td className="offer">9% off</td>
                            <td><span className="pill st-pending">Pending checkout</span></td>
                            <td className="time">24m ago</td>
                            <td><span className="viewbtn">View</span></td>
                          </tr>
                          <tr>
                            <td><span className="sesh">934870</span></td>
                            <td className="buyer">AI agent</td>
                            <td><span className="pill chan-api">Agentic API</span></td>
                            <td className="val">$749.95</td>
                            <td className="offer">9% off</td>
                            <td><span className="pill st-purchased">Purchased</span></td>
                            <td className="time">32m ago</td>
                            <td><span className="viewbtn">View</span></td>
                          </tr>
                          <tr>
                            <td><span className="sesh">314036</span></td>
                            <td className="buyer">AI agent</td>
                            <td><span className="pill chan-api">Agentic API</span></td>
                            <td className="val">$749.95</td>
                            <td className="offer">12% off</td>
                            <td><span className="pill st-pending">Pending checkout</span></td>
                            <td className="time">2h ago</td>
                            <td><span className="viewbtn">View</span></td>
                          </tr>
                        </tbody>
                      </table>
                      </div>
                    </div>

                    <div className="dc-wrap">
                      <div className="dc-head">
                        <span className="t">DealAgent recommendation</span>
                        <a className="open" href="#">Open Copilot</a>
                      </div>
                      <div className="dc-panel">
                        <div className="dc-top">
                          <div className="dc-eyebrow"><Sparkle size={11} color="#116DFF"/>DealAgent Copilot</div>
                          <span className="dc-aibadge">AI generated</span>
                        </div>

                        <p className="dc-line">
                          {typed}
                          {typedDone
                            ? <b>12% bundle discount + free shipping</b>
                            : <span className="caret"></span>}
                          {typedDone && "."}
                        </p>

                        <div className="dc-block policy">
                          <div className="bk">Recommended deal policy</div>
                          <div className="dc-rows">
                            <div className="r"><span className="k">Category</span><span className="v">Home Decor</span></div>
                            <div className="r"><span className="k">Min margin</span><span className="v">40%</span></div>
                            <div className="r"><span className="k">Autonomy</span><span className="v">Medium</span></div>
                            <div className="r"><span className="k">Preferred levers</span><span className="v">Bundle · Free shipping · Private discount</span></div>
                            <div className="r"><span className="k">Products affected</span><span className="v">84</span></div>
                            <div className="r"><span className="k">Contribution margin (this offer)</span><span className="v safe">42% · safe</span></div>
                          </div>
                        </div>

                        <div className="dc-block why">
                          <div className="bk">Why this offer</div>
                          <ul className="dc-why">
                            <li>Cart includes two compatible products</li>
                            <li>Inventory age on lead SKU is 94 days</li>
                            <li>Bundle offers outperform direct discounts for this category</li>
                            <li>Contribution margin remains at 42% after offer</li>
                          </ul>
                        </div>

                        <div className="dc-actions">
                          <span className="dc-btn primary"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>Approve &amp; activate</span>
                          <span className="dc-btn secondary">Simulate</span>
                          <span className="dc-btn ghost">Edit rules</span>
                        </div>

                        <div className="dc-prompt">
                          <span className="ph"><Sparkle size={13} color="#116DFF"/>Ask DealAgent: create a deal strategy for Lighting, protect 40% margin…</span>
                          <span className="send"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg>Send</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

window.Hero = Hero;
