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

const { useState: useStateA, useEffect: useEffectA } = React;

/* Animated terminal: reveals request lines, then streams a margin-safe offer */
function ApiTerminal() {
  const [ref, inView] = useInView({ threshold: 0.4 });
  const [n, setN] = useStateA(window.REDUCED ? 99 : 0);

  const lines = [
    <span><span className="prompt">$</span> <span className="c-out">curl -X POST https://api.dealagent.ai/v1/offers \</span></span>,
    <span className="c-out">  -H "Authorization: Bearer sk_live_••••" \</span>,
    <span className="c-out">  -d '{`{`}</span>,
    <span><span className="c-punc">    </span><span className="c-key">"cart_total"</span><span className="c-punc">: </span><span className="c-num">248.00</span><span className="c-punc">,</span></span>,
    <span><span className="c-punc">    </span><span className="c-key">"agent"</span><span className="c-punc">: </span><span className="c-str">"shopagent.ai"</span><span className="c-punc">,</span></span>,
    <span><span className="c-punc">    </span><span className="c-key">"intent"</span><span className="c-punc">: </span><span className="c-str">"checkout"</span></span>,
    <span className="c-out">  {`}'`}</span>,
  ];

  const resp = [
    <span><span className="c-cmt"># 200 OK · 84ms</span></span>,
    <span><span className="c-punc">{`{`}</span></span>,
    <span><span className="c-punc">  </span><span className="c-key">"decision"</span><span className="c-punc">: </span><span className="c-str">"approved"</span><span className="c-punc">,</span></span>,
    <span><span className="c-punc">  </span><span className="c-key">"offer"</span><span className="c-punc">: </span><span className="c-str">"12% bundle + free shipping"</span><span className="c-punc">,</span></span>,
    <span><span className="c-punc">  </span><span className="c-key">"protected_margin"</span><span className="c-punc">: </span><span className="c-str">"42%"</span><span className="c-punc">,</span></span>,
    <span><span className="c-punc">  </span><span className="c-key">"status"</span><span className="c-punc">: </span><span className="c-str">"margin_safe"</span><span className="c-punc">,</span></span>,
    <span><span className="c-punc">  </span><span className="c-key">"expires_in"</span><span className="c-punc">: </span><span className="c-num">900</span></span>,
    <span><span className="c-punc">{`}`}</span></span>,
  ];

  const total = lines.length + resp.length;

  useEffectA(() => {
    if (!inView || window.REDUCED) return;
    let i = 0;
    const timers = [];
    const schedule = () => {
      if (i >= total) return;
      // request lines type faster, response streams a touch slower
      const delay = i < lines.length ? 230 : 150;
      timers.push(setTimeout(() => { i++; setN(i); schedule(); }, delay));
    };
    timers.push(setTimeout(schedule, 500));
    return () => timers.forEach(clearTimeout);
  }, [inView, total]);

  const showResp = n > lines.length;

  return (
    <div className="term" ref={ref}>
      <div className="term-bar">
        <span className="dot r"></span><span className="dot y"></span><span className="dot g"></span>
        <span className="ttl">agentic-offer-api · request</span>
        <span className="pill">v1</span>
      </div>
      <div className="term-body">
        {lines.map((l, i) => (
          n > i ? <div className="term-line" key={`q${i}`}>{l}</div> : null
        ))}
        {showResp && (
          <div className="term-resp">
            {resp.map((l, i) => (
              n > lines.length + i ? <div className="term-line c-out" key={`r${i}`}>{l}</div> : null
            ))}
            {n < total && <span className="tcaret"></span>}
          </div>
        )}
        {!showResp && n > 0 && n < lines.length && <span className="tcaret"></span>}
      </div>
    </div>
  );
}

function AgenticApi() {
  const points = [
    { ic: "bolt", h: "Real time decisions", p: "Approve, counter, or decline an agent's request in milliseconds, under the same margin rules as your storefront." },
    { ic: "shield", h: "Margin safe by default", p: "AI agents never see a price your guardrails wouldn't allow. No public code, no leak, no race to the bottom." },
    { ic: "braces", h: "One clean endpoint", p: "A single POST returns the decision, the offer, the protected margin, and an auditable reason." },
  ];
  return (
    <section id="api" className="api wrap grain">
      <div className="container">
        <div className="api-grid">
          <div>
            <Reveal><div className="eyebrow"><Sparkle size={12} color="#7AB0FF"/>The future channel</div></Reveal>
            <Reveal delay={60}><h2 className="h2">Sell to AI shopping agents, <span className="agent">on your terms.</span></h2></Reveal>
            <Reveal delay={120}><p className="lead">Agentic commerce is coming fast. When an AI agent checks out on a shopper's behalf, DealAgent answers with a private, margin safe offer through the Agentic Offer API, the same engine that powers your storefront.</p></Reveal>
            <div className="api-points">
              {points.map((p, i) => (
                <Reveal delay={i * 80} key={p.h}>
                  <div className="api-point">
                    <div className="ic"><SiteIcon name={p.ic}/></div>
                    <div><h4>{p.h}</h4><p>{p.p}</p></div>
                  </div>
                </Reveal>
              ))}
            </div>
            <Reveal delay={120}>
              <div className="api-cta">
                <a className="btn btn-primary btn-lg" href="#">Read the API docs</a>
              </div>
            </Reveal>
          </div>
          <Reveal delay={140}><ApiTerminal/></Reveal>
        </div>
      </div>
    </section>
  );
}

/* ---------- Integrations ---------- */
function ShopifyMark({ size = 22, color = "#fff" }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={color} aria-hidden="true">
      <path d="M15.337 23.979l7.216-1.561s-2.604-17.613-2.625-17.73c-.018-.116-.114-.192-.211-.192l-1.929-.136s-1.275-1.274-1.439-1.411c-.045-.037-.075-.057-.121-.074l-.914 21.104h.023zM11.71 11.305s-.81-.424-1.774-.424c-1.447 0-1.504.906-1.504 1.141 0 1.232 3.24 1.715 3.24 4.629 0 2.295-1.44 3.769-3.394 3.769-2.348 0-3.531-1.464-3.531-1.464l.625-2.083s1.232 1.058 2.273 1.058c.679 0 .954-.534.954-.924 0-1.619-2.658-1.694-2.658-4.359 0-2.244 1.612-4.414 4.853-4.414 1.25 0 1.869.358 1.869.358l-.927 2.74-.493-.026v-.001zM11.17.85c.136 0 .272.048.4.135-.94.442-1.961 1.563-2.384 3.801l-1.926.595C7.732 3.534 8.847.85 11.17.85zm1.273 3.064v.135l-2.328.72c.448-1.726 1.285-2.563 2.017-2.879.184.473.311 1.146.311 2.024zm.562-2.083c.674.074 1.11.84 1.391 1.711l-1.192.366v-.256c0-.776-.108-1.4-.28-1.896l.081.075z"/>
    </svg>
  );
}

/* Two-tone Shopify bag (official logo): configurable bag / fold / S colors */
function ShopifyBag({ size = 30, bag = "#95BF47", fold = "#5E8E3E", s = "#fff" }) {
  return (
    <svg width={size} height={Math.round(size * 292 / 256)} viewBox="0 0 256 292" aria-hidden="true">
      <path fill={bag} d="M223.774 57.34c-.201-1.46-1.48-2.268-2.537-2.357-1.055-.088-23.383-1.743-23.383-1.743s-15.507-15.395-17.209-17.099c-1.703-1.703-5.029-1.185-6.32-.805-.19.056-3.388 1.043-8.678 2.68-5.18-14.906-14.322-28.604-30.405-28.604-.444 0-.901.018-1.358.044C129.31 3.407 123.644.834 118.75.834c-37.465 0-55.364 46.835-60.976 70.635-14.558 4.511-24.9 7.718-26.221 8.133-8.126 2.549-8.383 2.805-9.45 10.462C21.3 95.806.831 254.022.831 254.022l159.49 29.886 86.388-18.69S223.973 58.8 223.774 57.34zM156.93 40.95c-4.115 1.273-8.79 2.72-13.86 4.29 0-1.097.014-2.18.014-3.36 0-10.302-1.43-18.6-3.728-25.18 9.23 1.159 15.382 11.66 17.574 24.25zm-27.318-22.45c2.564 6.43 4.231 15.663 4.231 28.124 0 .637 0 1.218-.005 1.806-9.024 2.794-18.832 5.826-28.674 8.864 5.526-21.327 15.886-31.626 24.448-38.794zm-11.018-10.44c1.515 0 3.04.514 4.5 1.519-11.258 5.295-23.323 18.633-28.418 45.272-7.873 2.435-15.572 4.819-22.689 7.014C77.524 39.34 92.704 8.06 118.594 8.06z"/>
      <path fill={fold} d="M221.237 54.983c-1.055-.088-23.383-1.743-23.383-1.743s-15.507-15.395-17.209-17.099c-.637-.634-1.496-.959-2.394-1.099l-12.527 256.233 86.388-18.69S223.973 58.8 223.774 57.34c-.201-1.46-1.48-2.268-2.537-2.357z"/>
      <path fill={s} d="M135.242 105.578l-10.567 31.46s-9.262-4.948-20.265-4.948c-16.13 0-16.94 10.121-16.94 12.674 0 13.93 36.327 19.272 36.327 51.917 0 25.69-16.296 42.225-38.28 42.225-26.376 0-39.864-16.41-39.864-16.41l7.06-23.335s13.86 11.908 25.557 11.908c7.642 0 10.756-6.018 10.756-10.414 0-18.174-29.8-18.986-29.8-48.86 0-25.146 18.052-49.48 54.476-49.48 14.048 0 20.97 4.027 20.97 4.027z"/>
    </svg>
  );
}

function Integrations() {
  const Check = () => <SiteIcon name="check" size={18} stroke={2.5}/>;
  const logoMarkDark = (window.__resources && window.__resources.logoMarkDark) || "assets/logo-mark-dark.png";
  return (
    <section id="integrations" className="integrations wrap">
      <div className="container">
        <Reveal><div className="eyebrow">Integrations</div></Reveal>
        <Reveal delay={60}><h2 className="h2">Live on your Shopify store <span className="agent">in 5 minutes.</span></h2></Reveal>

        <div className="int-grid">
          <Reveal delay={80}>
            <div className="int-copy">
              <p className="lead" style={{ marginTop: 0 }}>
                Install the DealAgent app, connect your products, costs, and inventory,
                and run your first deal policy the same day. No code, no replatforming.
              </p>
              <ul className="int-bullets">
                <li><Check/><span><b>One click install.</b> Read only by default, DealAgent never touches your storefront without your approval.</span></li>
                <li><Check/><span><b>Auto sync products, costs, inventory, and customer segments</b> from Shopify in under 5 minutes.</span></li>
                <li><Check/><span><b>Storefront cart widget</b> drops in as a Shopify section, no theme edits, no custom code.</span></li>
                <li><Check/><span><b>Compatible with Shopify Plus, Shopify Markets, and Shop Pay.</b></span></li>
              </ul>
              <div className="int-cta">
                <a className="shopify-badge" href="https://apps.shopify.com/dealagent-ai" target="_blank" rel="noopener" aria-label="Available on the Shopify App Store">
                  <ShopifyBag size={26} bag="#fff" fold="#d4d4d4" s="#000"/>
                  <span className="sb-txt">
                    <span className="sb-sm">Available on</span>
                    <span className="sb-lg">Shopify App Store</span>
                  </span>
                </a>
                <span className="footnote">14 day free trial · No credit card</span>
              </div>
            </div>
          </Reveal>

          <Reveal delay={160}>
            <div className="int-mock">
              <div className="int-mock-head">
                <div className="int-mock-shop-logo"><ShopifyBag size={26} bag="#95BF47" fold="#5E8E3E" s="#fff"/></div>
                <div className="int-mock-connect">
                  <span style={{ fontSize: 13, fontWeight: 600, color: "var(--fg-1)" }}>Lumen Store</span>
                  <span className="arrow">→</span>
                  <span style={{ fontSize: 13, fontWeight: 600, color: "var(--fg-1)" }}>DealAgent</span>
                </div>
                <div className="int-mock-da-logo"><img src={logoMarkDark} alt="DealAgent"/></div>
              </div>
              <div className="int-mock-perms">
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 4 }}>
                  <span style={{ fontSize: 11, fontWeight: 600, color: "var(--fg-muted)", letterSpacing: "0.06em", textTransform: "uppercase" }}>App permissions</span>
                  <div className="int-mock-status">Verified by Shopify</div>
                </div>
                <div className="int-mock-perm"><Check/><div>Read products, variants, and inventory <span>· for margin calculations</span></div></div>
                <div className="int-mock-perm"><Check/><div>Read orders and customers <span>· for offer history &amp; segmentation</span></div></div>
                <div className="int-mock-perm"><Check/><div>Write private discount codes <span>· only when approved by your policies</span></div></div>
                <div className="int-mock-perm"><Check/><div>Theme app extension <span>· for the cart widget</span></div></div>
              </div>
              <div className="int-mock-actions">
                <a className="btn btn-secondary" href="#">Cancel</a>
                <a className="btn btn-shopify" href="https://apps.shopify.com/dealagent-ai" target="_blank" rel="noopener">Install app</a>
              </div>
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

window.AgenticApi = AgenticApi;
window.Integrations = Integrations;
window.ApiTerminal = ApiTerminal;
window.ShopifyBag = ShopifyBag;
window.ShopifyMark = ShopifyMark;
