/* global React */
const { useState, useEffect, useMemo } = React;

const H = window.HEXA || {};

/* ============================================================
   HEXA-V — shared bits
   ============================================================ */

// Wordmark — uses two hex glyphs as the "V" mark (placeholder until final logo)
const Wordmark = ({ size = 22 }) =>
<div style={{ display: "flex", alignItems: "center", gap: 10 }}>
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" style={{ display: "block" }}>
      <path d="M12 1.5L22 7v10L12 22.5 2 17V7L12 1.5z" stroke="currentColor" strokeWidth="1.2" />
      <path d="M12 6.5L17 9.5v5L12 17.5 7 14.5v-5L12 6.5z" fill="var(--accent)" stroke="var(--accent)" strokeWidth="0.5" style={{ fill: "#2563eb" }} />
    </svg>
    <span className="display" style={{ fontWeight: 700, letterSpacing: "0.04em", fontSize: size * 0.78 }}>
      HEXA<span style={{ color: "#2563eb" }}>·</span>V
    </span>
  </div>;


// Customer descriptors — anonymised, no fake names.
const CustomerLogos = () => {
  const logos = [
  "8-figure kitchen brand",
  "Top-500 outdoor seller",
  "7-figure beauty brand",
  "6-figure pet supplies",
  "8-figure home goods",
  "Top-100 sporting goods",
  "7-figure supplements",
  "Multi-brand aggregator",
  "6-figure baby brand",
  "Top-500 apparel seller"];

  return (
    <div style={{ display: "flex", gap: 56, alignItems: "center", whiteSpace: "nowrap" }}>
      {logos.map((l, i) =>
      <div key={i} style={{
        display: "inline-flex", alignItems: "center", gap: 12, opacity: 0.85,
        border: "1px solid var(--line)", padding: "10px 18px",
        fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-1)",
        letterSpacing: "0.06em"
      }}>
          <span style={{ width: 4, height: 4, background: "var(--accent)", display: "inline-block" }}></span>
          {l}
        </div>
      )}
    </div>);

};

// Sparkline path util
const sparkPath = (values, w, h, pad = 4) => {
  const min = Math.min(...values);
  const max = Math.max(...values);
  const r = max - min || 1;
  const step = (w - pad * 2) / (values.length - 1);
  return values.map((v, i) => {
    const x = pad + i * step;
    const y = h - pad - (v - min) / r * (h - pad * 2);
    return `${i === 0 ? "M" : "L"}${x.toFixed(1)},${y.toFixed(1)}`;
  }).join(" ");
};

const Sparkline = ({ values, w = 120, h = 36, color = "var(--accent)" }) =>
<svg width={w} height={h} viewBox={`0 0 ${w} ${h}`} className="spark" style={{ display: "block" }}>
    <path d={sparkPath(values, w, h)} stroke={color} strokeWidth="1.4" fill="none" />
  </svg>;


const useTicker = (base, jitter = 0.02, interval = 1200) => {
  const [v, setV] = useState(base);
  useEffect(() => {
    const id = setInterval(() => {
      const delta = (Math.random() - 0.4) * base * jitter;
      setV((prev) => Math.max(0, prev + delta));
    }, interval);
    return () => clearInterval(id);
  }, [base, jitter, interval]);
  return v;
};

const fmt = (n, d = 0) => n.toLocaleString("en-US", { minimumFractionDigits: d, maximumFractionDigits: d });
const usd = (n) => "$" + fmt(n, 0);

// Integration icon grid (placeholders, mono)
const Integrations = () => {
  const items = [
  "Seller Console", "Seller Central", "Marketplace Ads", "Vendor Portal",
  "Shopify", "QuickBooks", "Xero", "Slack",
  "ShipStation", "Klaviyo", "Helium 10", "Zapier",
  "Google Sheets", "Notion", "Webhooks", "Data Export"];

  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", border: "1px solid var(--line)" }} className="hexa-integrations-grid">
      {items.map((name, i) =>
      <div key={i} style={{
        padding: "28px 22px", borderRight: i % 4 !== 3 ? "1px solid var(--line)" : "none",
        borderBottom: i < 12 ? "1px solid var(--line)" : "none",
        display: "flex", alignItems: "center", gap: 14, minHeight: 88
      }}>
          <div style={{ width: 36, height: 36, border: "1px solid var(--line-2)", display: "grid", placeItems: "center", color: "var(--fg-1)" }}>
            <span className="mono" style={{ fontSize: 11 }}>{name.slice(0, 2).toUpperCase()}</span>
          </div>
          <div>
            <div style={{ fontSize: 14, fontWeight: 500 }}>{name}</div>
            <div className="mono" style={{ fontSize: 10, color: "var(--fg-3)", letterSpacing: "0.12em", textTransform: "uppercase", marginTop: 2 }}>
              {i % 3 === 0 ? "Native" : i % 3 === 1 ? "Connected" : "OAuth"}
            </div>
          </div>
        </div>
      )}
    </div>);

};

// Pricing — Advisor / Co-Pilot / Autopilot with real CTA URLs
const PricingGrid = ({ accentMiddle = true }) => {
  const tiers = [
  {
    level: "L1", name: "ADVISOR", tag: "Suggests only",
    price: 19, priceNote: "first month", priceAfter: "$39 / mo after",
    blurb: "Bids stay where you put them. We tell you which six moves would have made the most money this week.",
    bullets: [
    "Weekly PPC move shortlist",
    "Keyword harvest opportunities",
    "Profit-per-SKU dashboard",
    "Featured Offer & supply alerts",
    "1 user seat · email + Slack"],

    cta: "Start at $19", href: H.SIGNUP_URL || "#"
  },
  {
    level: "L2", name: "CO-PILOT", tag: "Queues for approval",
    price: 79, priceNote: "per month",
    blurb: "Agent drafts the bid changes; you tap approve in Slack or in-app. Bulk approve in one click.",
    bullets: [
    "Everything in Advisor",
    "Bid + budget action queue",
    "One-click approvals (web + Slack)",
    "Auto-pause guardrails (you set the rules)",
    "3 user seats · role-based"],

    cta: "Try Co-Pilot →", href: H.SIGNUP_URL || "#", featured: true
  },
  {
    level: "L3", name: "AUTOPILOT", tag: "Acts inside your rails",
    price: 199, priceNote: "per month",
    blurb: "Agent moves bids inside your floor/cap/daypart rules. You set rails once; it ships hourly.",
    bullets: [
    "Everything in Co-Pilot",
    "Autonomous bidding inside your guardrails",
    "Auto-negation + dayparting",
    "Weekly written debrief",
    "Unlimited seats · priority support"],

    cta: "Try Autopilot →", href: H.SIGNUP_URL || "#"
  }];

  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 0, border: "1px solid var(--line)" }} className="pricing-grid">
      {tiers.map((t, i) => {
        const featured = accentMiddle && t.featured;
        return (
          <div key={i} style={{
            padding: "36px 32px",
            borderRight: i < 2 ? "1px solid var(--line)" : "none",
            background: featured ? "var(--bg-1)" : "transparent",
            position: "relative"
          }}>
            {featured && <div style={{ position: "absolute", top: 0, left: 0, right: 0, height: 3, background: "var(--accent)", backgroundColor: "#2563eb" }} />}
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
              <div style={{ display: "flex", alignItems: "baseline", gap: 10 }}>
                <span className="mono" style={{ ...{ fontSize: 11, color: featured ? "var(--accent)" : "var(--fg-3)", letterSpacing: "0.18em" }, color: "#2563eb" }}>{t.level}</span>
                <div className="mono" style={{ ...{ fontSize: 11, letterSpacing: "0.18em", color: featured ? "var(--accent)" : "var(--fg-2)" }, color: "#2563eb" }}>{t.name}</div>
              </div>
              {featured && <span className="tag" style={{ color: "#2563eb", borderColor: "#2563eb" }}>MOST PICKED</span>}
            </div>
            <div className="display" style={{ marginTop: 12, color: "var(--fg)", fontSize: 22, fontWeight: 500, letterSpacing: "-0.01em", fontStyle: "italic" }}>
              “{t.tag}”
            </div>
            <div style={{ marginTop: 28, display: "flex", alignItems: "baseline", gap: 8 }}>
              <div className="display" style={{ fontSize: 56, fontWeight: 700, lineHeight: 1 }}>${t.price}</div>
              <div className="mono" style={{ fontSize: 12, color: "var(--fg-2)" }}>/{t.priceNote === "first month" ? "FIRST MO" : "MO"}</div>
            </div>
            {t.priceAfter &&
            <div className="mono" style={{ fontSize: 11, color: "var(--fg-2)", marginTop: 6, letterSpacing: "0.06em" }}>
                then {t.priceAfter}
              </div>
            }
            <div style={{ marginTop: 18, color: "var(--fg-1)", fontSize: 14, lineHeight: 1.5 }}>{t.blurb}</div>
            <div className="divider" style={{ margin: "28px 0" }} />
            <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 12 }}>
              {t.bullets.map((b, j) =>
              <li key={j} style={{ display: "flex", gap: 10, fontSize: 14, color: "var(--fg-1)" }}>
                  <span style={{ color: "var(--accent)", fontFamily: "var(--font-mono)" }}>▸</span>{b}
                </li>
              )}
            </ul>
            <a href={t.href} className={`btn ${featured ? "btn-primary" : ""}`} style={{ marginTop: 32, width: "100%", justifyContent: "center", textDecoration: "none", ...(featured ? { backgroundColor: "#2563eb", color: "#fff" } : {}) }}>
              {t.cta}
            </a>
          </div>);

      })}
    </div>);

};

/* ============================================================
   New homepage sections for Direction A
   ============================================================ */

// "Our customers do more, with less, faster"
const MoreLessFaster = () =>
<div style={{ padding: "128px 32px 112px", borderTop: "1px solid var(--line)", textAlign: "left", position: "relative", background: "var(--bg)" }} className="snap-in">
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 56, alignItems: "end", maxWidth: 1400, margin: "0 auto 72px" }} className="sub-two-col">
      <div>
        <span className="mono" style={{ fontSize: 11, letterSpacing: "0.2em", color: "var(--fg-2)" }}>
          // RESULTS · MEDIAN · TRAILING 60 DAYS
        </span>
        <h2 className="display mlf-h2 slide-up" style={{ fontSize: 72, lineHeight: 0.95, letterSpacing: "-0.035em", margin: "20px 0 0", fontWeight: 700, textWrap: "balance" }}>
          Our customers do <span style={{ color: "#2563eb" }}>more</span>, with <span style={{ color: "var(--good)" }}>less</span>, <span style={{ color: "#2563eb" }}>faster</span>.
        </h2>
      </div>
      <p style={{ fontSize: 17, lineHeight: 1.6, justifySelf: "end", maxWidth: 440, color: "#2563eb" }}>
        Numbers below are the median across active tenants in their first sixty days on HEXA-V. Not the highlight reel; we don't quote outliers and we don't claim recoveries over 40%.
      </p>
    </div>
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1fr", gap: 0, borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)", maxWidth: 1400, margin: "0 auto" }} className="mlf-grid">
      {[
    { v: "−18%", l: "median ACoS reduction", c: "good" },
    { v: "+8%",  l: "unit margin recovered", c: "good" },
    { v: "≈6 min", l: "median deploy time", c: "fg" },
    { v: "47s", l: "data refresh interval", c: "fg" }].
    map((s, i) =>
    <div key={i} style={{
      padding: "48px 28px",
      borderRight: i < 3 ? "1px solid var(--line)" : "none"
    }}>
          <div className="display" style={{ ...{
          fontSize: 64, fontWeight: 700, letterSpacing: "-0.03em", lineHeight: 1,
          color: s.c === "good" ? "var(--good)" : "var(--fg)"
        }, color: "#2563eb" }}>{s.v}</div>
          <div className="mono" style={{ fontSize: 11, color: "var(--fg-2)", letterSpacing: "0.14em", textTransform: "uppercase", marginTop: 14 }}>
            {s.l}
          </div>
        </div>
    )}
    </div>

    {/* Quote strip */}
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 0, marginTop: 0, borderBottom: "1px solid var(--line)", maxWidth: 1400, margin: "0 auto" }} className="mlf-quotes">
      {[
    { q: "Co-Pilot showed us the bid math we were missing. Cut wasted spend in the first week.", who: "Operator · 8-figure kitchen brand" },
    { q: "Profit OS caught a $0.43 fulfilment fee creep we had been eating for two months.", who: "Founder · 7-figure beauty brand" },
    { q: "Started on Advisor at $19. Upgraded inside ten days.", who: "Head of marketplace · top-500 outdoor seller" }].
    map((t, i) =>
    <div key={i} style={{
      padding: "44px 28px",
      borderRight: i < 2 ? "1px solid var(--line)" : "none"
    }}>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 24, lineHeight: 1, color: "#2563eb" }}>“</span>
          <p style={{ fontSize: 16, color: "var(--fg-1)", lineHeight: 1.5, marginTop: 8, fontWeight: 400 }}>
            {t.q}
          </p>
          <div className="mono" style={{ fontSize: 11, color: "var(--fg-2)", letterSpacing: "0.14em", marginTop: 18, textTransform: "uppercase" }}>
            — {t.who}
          </div>
        </div>
    )}
    </div>
  </div>;


// Founder section — honest, personal
const FounderNote = () =>
<div style={{ padding: "120px 32px", borderTop: "1px solid var(--line)", background: "var(--bg-1)" }} className="snap-in">
    <div style={{ display: "grid", gridTemplateColumns: "320px 1fr", gap: 72, alignItems: "start", maxWidth: 1200, margin: "0 auto" }} className="founder-row">
      <div>
        {/* avatar placeholder — geometric, not a fake face */}
        <div style={{
        width: 220, height: 280, border: "1px solid var(--line-2)", background: "var(--bg-2)",
        position: "relative", overflow: "hidden"
      }}>
          <div className="hexpattern" style={{ position: "absolute", inset: 0, opacity: 0.4 }} />
          <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", color: "var(--fg-3)" }}>
            <span className="mono" style={{ fontSize: 11, letterSpacing: "0.2em" }}></span>
          </div>
          <div className="card-corner tl"></div><div className="card-corner tr"></div>
          <div className="card-corner bl"></div><div className="card-corner br"></div>
        </div>
        <div className="mono" style={{ fontSize: 11, letterSpacing: "0.18em", color: "var(--fg-2)", marginTop: 18 }}>
          FOUNDER · HEXA-V
        </div>
        <div className="display" style={{ fontSize: 22, fontWeight: 600, marginTop: 4, letterSpacing: "-0.01em" }}>Hanora Labiba Nismara

      </div>
      </div>

      <div style={{ paddingTop: 8 }}>
        <span className="tag"><span className="dot" style={{ backgroundColor: "#2563eb", color: "#fff" }}></span>NOTE FROM THE BUILDER</span>
        <h2 className="display" style={{ fontSize: 44, lineHeight: 1.05, letterSpacing: "-0.025em", margin: "20px 0 24px", fontWeight: 700, textWrap: "balance" }}>
          I built this after watching sellers lose thousands<br />
          to bad PPC data.
        </h2>
        <div style={{ fontSize: 17, color: "var(--fg-1)", lineHeight: 1.65, maxWidth: 640, display: "flex", flexDirection: "column", gap: 16 }}>
          <p style={{ margin: 0 }}>
            HEXA-V is what I wish existed when I was running a brand. The dashboards I paid for showed me yesterday's numbers in a chart and called it insight. They didn't tell me which bid to move, which keyword was bleeding, or what my real margin per unit was after fees, returns and FX.
          </p>
          <p style={{ margin: 0 }}>
            So I built the thing I needed: a console that does the math, queues the action, and lets me approve or autopilot — depending on how much I trust it that week. Three altitudes. No drama.
          </p>
          <p style={{ margin: 0 }}>
            We're small, we're independent, and we don't sell your data. If something in here is wrong, my inbox is at the bottom of every page.
          </p>
        </div>
        <div style={{ display: "flex", gap: 12, marginTop: 28 }}>
          <a href={H.SIGNUP_URL || "#"} className="btn btn-primary" style={{ backgroundColor: "#2563eb", color: "#fff", textDecoration: "none" }}>Try Advisor for $19 →</a>
          <a href={H.WATCH_URL || "#watch-demo"} className="btn" style={{ textDecoration: "none" }}>▶ Watch Demo</a>
        </div>
      </div>
    </div>
  </div>;


/* IntersectionObserver — fires .is-visible on .snap-in elements when they enter viewport */
function initSnapIn() {
  const io = new IntersectionObserver((entries) => {
    entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add("is-visible"); io.unobserve(e.target); } });
  }, { threshold: 0.12 });
  document.querySelectorAll(".snap-in").forEach(el => io.observe(el));
}
/* Run after React paints */
if (typeof window !== "undefined") {
  const _orig = window.requestAnimationFrame || ((fn) => setTimeout(fn, 16));
  _orig(() => _orig(() => initSnapIn()));
  document.addEventListener("DOMContentLoaded", initSnapIn);
}

Object.assign(window, {
  Wordmark, CustomerLogos, Sparkline, useTicker, fmt, usd, sparkPath,
  Integrations, PricingGrid,
  MoreLessFaster, FounderNote,
  initSnapIn
});