// Pricing widgets — plan toggle, brand slider, bundle calculator
const { useState: usePState, useMemo: usePMemo } = React;

// ────────── plan grid w/ monthly/annual toggle ──────────
function PricingGrid({ display = "both" }) {
  // display: "monthly" | "annual" | "both"
  const [mode, setMode] = usePState(display === "annual" ? "annual" : "monthly");
  const showToggle = display === "both";

  return (
    <div className="pricing">
      {showToggle && (
        <div className="price-toggle">
          <button className={`pt-btn ${mode === "monthly" ? "on" : ""}`} onClick={() => setMode("monthly")}>
            Monthly · 12-mo commit
          </button>
          <button className={`pt-btn ${mode === "annual" ? "on" : ""}`} onClick={() => setMode("annual")}>
            Annual prepay <span className="save">save ~8%</span>
          </button>
        </div>
      )}

      <div className="price-grid">
        {PLAN_TIERS.map(p => {
          const price = mode === "annual" ? p.annual : p.monthly;
          const sub = mode === "annual" ? "/yr prepaid" : "/mo · 12-mo";
          const annualOnly = p.annualOnly && mode === "monthly";
          return (
            <div key={p.id} className={`price-card ${p.popular ? "popular" : ""}`}>
              {p.popular && <div className="price-pop mono">most popular</div>}
              <div className="price-name">{p.name}</div>
              <div className="price-amount">
                {annualOnly ? (
                  <>
                    <span className="amt">$5,000</span>
                    <span className="amt-sub">/mo · annual contract only</span>
                  </>
                ) : (
                  <>
                    <span className="amt">${price.toLocaleString()}</span>
                    <span className="amt-sub">{sub}</span>
                  </>
                )}
                {mode === "annual" && !annualOnly && (
                  <div className="amt-note mono">≈ ${Math.round(p.annual / 12).toLocaleString()}/mo equivalent</div>
                )}
              </div>
              <div className="price-brands mono">
                <span style={{ color: "var(--accent)" }}>{p.brands}{p.id === "enterprise" ? "+" : ""}</span> brands
              </div>
              <ul className="price-rows">
                {p.rows.map(([k, v], i) => (
                  <li key={i}>
                    <span>{k}</span>
                    <span className={`pr-val ${v === "—" ? "off" : ""} ${v === "✓" || (typeof v === "string" && v.startsWith("✓")) ? "yes" : ""}`}>{v}</span>
                  </li>
                ))}
              </ul>
              <div className="price-best mono">{p.best}</div>
              <a href="#" className={`btn ${p.popular ? "btn-primary" : ""} btn-arrow`} style={{ width: "100%", justifyContent: "center", marginTop: 16 }}>
                {p.id === "enterprise" ? "Talk to us" : "Start " + p.name}
              </a>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ────────── brand slider ──────────
function BrandSlider() {
  const [n, setN] = usePState(75);
  // tier the slider lands in
  const tier = n <= 30 ? PLAN_TIERS[0] : n <= 75 ? PLAN_TIERS[1] : n <= 250 ? PLAN_TIERS[2] : PLAN_TIERS[3];
  // build grid of brand chips
  const visible = BRANDS.slice(0, Math.min(n, BRANDS.length));
  const ghosted = BRANDS.length - visible.length;

  return (
    <div className="brand-slider">
      <div className="bs-head">
        <div>
          <div className="mono" style={{ color: "var(--fg-3)" }}>HOW MANY BRANDS DO YOU NEED?</div>
          <div className="bs-num">
            <span className="bs-num-big">{n}</span>
            <span className="bs-num-unit"> brands {n >= 450 && "(all available + new)"}</span>
          </div>
        </div>
        <div className="bs-tier">
          <div className="mono" style={{ color: "var(--fg-3)" }}>RECOMMENDED PLAN</div>
          <div className="bs-tier-name">{tier.name} <span style={{ color: "var(--accent)" }}>· ${tier.monthly.toLocaleString()}/mo</span></div>
        </div>
      </div>

      <input
        type="range"
        min="1" max="450" step="1"
        value={n}
        onChange={e => setN(parseInt(e.target.value))}
        className="bs-range"
      />
      <div className="bs-ticks mono">
        {[
          { v: 30,  l: "Starter" },
          { v: 75,  l: "Growth" },
          { v: 250, l: "Pro" },
          { v: 450, l: "Enterprise" },
        ].map(t => (
          <button key={t.v} className={`bs-tick ${tier.brands === t.v ? "on" : ""}`} onClick={() => setN(t.v)}>
            <div className="tick-line" />
            <div>{t.v}</div>
            <div style={{ color: "var(--fg-3)" }}>{t.l}</div>
          </button>
        ))}
      </div>

      <div className="bs-chips">
        {visible.map((b, i) => (
          <span key={i} className="brand-chip">{b}</span>
        ))}
        {ghosted > 0 && (
          <span className="brand-chip ghost">+{ghosted} not included</span>
        )}
      </div>
    </div>
  );
}

// ────────── bundle calculator ──────────
function BundleCalc() {
  const [data, setData] = usePState("growth");
  const [storefront, setStorefront] = usePState("pro");
  const [fitment, setFitment] = usePState(false);
  const [tracking, setTracking] = usePState(false);
  const [billing, setBilling] = usePState("monthly");

  const dataPlan = PLAN_TIERS.find(p => p.id === data);
  const sfMap = {
    none: { label: "None", flat: 0 },
    starter: { label: "Starter Storefront", flat: 5000 },
    pro: { label: "Pro Storefront", flat: 7500, includesTracking: true, requiresFitment: true },
    enterprise: { label: "Enterprise Storefront", flat: null, includesTracking: true },
  };
  const sf = sfMap[storefront];

  const bundleDiscount = storefront !== "none";
  const dataMonthly = dataPlan.monthly;
  const dataYearly = dataPlan.annual;

  const dataPrice = billing === "annual" ? dataYearly : dataMonthly * 12;
  const discountedDataPrice = bundleDiscount ? dataPrice * 0.8 : dataPrice;
  const dataSavings = dataPrice - discountedDataPrice;

  // Fitment forced on with Pro storefront
  const fitmentOn = fitment || (storefront === "pro" || storefront === "enterprise");
  const fitmentCost = fitmentOn ? (billing === "annual" ? 5000 : 6000) : 0;

  const trackingIncluded = sf.includesTracking;
  const trackingCost = !trackingIncluded && tracking ? 300 : 0;

  const sfCost = sf.flat || 0;

  const yr1Total = discountedDataPrice + sfCost + fitmentCost + trackingCost;

  return (
    <div className="bundle">
      <div className="bundle-grid">
        <div className="bundle-controls">
          <div className="bc-section">
            <div className="mono bc-label">Data subscription</div>
            <div className="bc-radios">
              {PLAN_TIERS.map(p => (
                <button key={p.id} className={`bc-pick ${data === p.id ? "on" : ""}`} onClick={() => setData(p.id)}>
                  <span>{p.name}</span>
                  <span className="mono" style={{ color: "var(--fg-3)" }}>${p.monthly.toLocaleString()}/mo</span>
                </button>
              ))}
            </div>
          </div>

          <div className="bc-section">
            <div className="mono bc-label">Storefront build</div>
            <div className="bc-radios">
              {[
                { id: "none", label: "None", note: "data only" },
                { id: "starter", label: "Starter", note: "$5,000 flat" },
                { id: "pro", label: "Pro", note: "$7,500 flat" },
                { id: "enterprise", label: "Enterprise", note: "scoped" },
              ].map(o => (
                <button key={o.id} className={`bc-pick ${storefront === o.id ? "on" : ""}`} onClick={() => setStorefront(o.id)}>
                  <span>{o.label}</span>
                  <span className="mono" style={{ color: "var(--fg-3)" }}>{o.note}</span>
                </button>
              ))}
            </div>
          </div>

          <div className="bc-section">
            <div className="mono bc-label">Add-ons</div>
            <div className="bc-toggle">
              <span>
                <strong>Fitment Engine</strong>
                <span className="mono" style={{ color: "var(--fg-3)", display: "block", marginTop: 2 }}>
                  $500/mo · {storefront === "pro" || storefront === "enterprise" ? "required for Pro Storefront" : "optional"}
                </span>
              </span>
              <input type="checkbox" checked={fitmentOn} disabled={storefront === "pro" || storefront === "enterprise"} onChange={e => setFitment(e.target.checked)} />
            </div>
            <div className="bc-toggle">
              <span>
                <strong>Tracking Setup</strong>
                <span className="mono" style={{ color: "var(--fg-3)", display: "block", marginTop: 2 }}>
                  {trackingIncluded ? "included with this storefront" : "$300 one-time"}
                </span>
              </span>
              <input type="checkbox" checked={trackingIncluded || tracking} disabled={trackingIncluded} onChange={e => setTracking(e.target.checked)} />
            </div>
            <div className="bc-toggle">
              <span>
                <strong>Billing</strong>
                <span className="mono" style={{ color: "var(--fg-3)", display: "block", marginTop: 2 }}>
                  Annual prepay = ~8% off the data sub
                </span>
              </span>
              <div className="seg" style={{ alignSelf: "center" }}>
                <button className={`seg-btn ${billing === "monthly" ? "on" : ""}`} onClick={() => setBilling("monthly")}>monthly</button>
                <button className={`seg-btn ${billing === "annual" ? "on" : ""}`} onClick={() => setBilling("annual")}>annual</button>
              </div>
            </div>
          </div>
        </div>

        <aside className="bundle-receipt">
          <div className="mono" style={{ color: "var(--fg-3)" }}>YEAR-1 ESTIMATE</div>
          <div className="bundle-total">
            ${storefront === "enterprise" ? "—" : Math.round(yr1Total).toLocaleString()}
            {storefront === "enterprise" && <span className="mono" style={{ fontSize: 14, marginLeft: 8, color: "var(--fg-3)" }}>contact for quote</span>}
          </div>

          <div className="bundle-lines">
            <div className="bundle-line">
              <span>Data · {dataPlan.name}</span>
              <span className="mono">
                {bundleDiscount && <span className="strike">${dataPrice.toLocaleString()}</span>}
                ${Math.round(discountedDataPrice).toLocaleString()}
              </span>
            </div>
            {bundleDiscount && (
              <div className="bundle-line discount">
                <span>↳ Bundle bonus (20% off data, lifetime)</span>
                <span className="mono">−${Math.round(dataSavings).toLocaleString()}</span>
              </div>
            )}
            {storefront !== "none" && (
              <div className="bundle-line">
                <span>Storefront · {sf.label}</span>
                <span className="mono">{sf.flat ? `$${sf.flat.toLocaleString()}` : "scoped"}</span>
              </div>
            )}
            {fitmentOn && (
              <div className="bundle-line">
                <span>Fitment Engine · year 1</span>
                <span className="mono">${fitmentCost.toLocaleString()}</span>
              </div>
            )}
            {(tracking || trackingIncluded) && (
              <div className="bundle-line">
                <span>Tracking Setup</span>
                <span className="mono">{trackingIncluded ? "included" : "$300"}</span>
              </div>
            )}
          </div>

          <div className="hr" style={{ margin: "16px 0" }} />
          <div className="mono" style={{ color: "var(--fg-3)", fontSize: 11 }}>
            Numbers shown are first-year totals. Data subscriptions auto-renew at the same plan unless you give 30-day notice. Upgrade any time; downgrades wait for renewal.
          </div>
          <a href="#" className="btn btn-primary btn-arrow" style={{ width: "100%", justifyContent: "center", marginTop: 18 }}>
            Lock in this bundle
          </a>
        </aside>
      </div>
    </div>
  );
}

// ────────── competitor table ──────────
const COMPETITORS = [
  {
    rows: [
      ["Pricing", "$499 – $5,000/mo", "$$$$ / per-brand fees", "$$$$ / opaque tiers", "engineering salary"],
      ["Time to launch", "Days", "Months", "Months", "6 – 18 months"],
      ["MAP enforcement", "Daily → realtime", "Periodic", "Daily", "Manual chasing"],
      ["Inventory feed", "Daily → realtime", "Limited", "Where supported", "DIY"],
      ["Brand approval gate", "No (you own supplier relationships)", "Yes", "Yes", "N/A"],
      ["API access", "Pro & Enterprise", "Add-on", "Yes", "Build it"],
      ["Fitment data", "Recommended partners or included", "Optional", "Yes", "Buy or build"],
      ["Storefront build option", "Productized $5K–$7.5K", "—", "—", "Hire an agency"],
      ["Built by retailers", "✓", "—", "—", "—"],
    ],
    headers: ["", "WySync", "Legacy data co-op", "OEM-gated platform", "DIY scraping"],
  },
];

function CompareTable() {
  const headers = COMPETITORS[0].headers;
  return (
    <div className="compare-table">
      <div className="ct-row ct-th">
        {headers.map((h, i) => (
          <div key={i} className={i === 1 ? "ct-us" : ""}>{h}</div>
        ))}
      </div>
      {COMPETITORS[0].rows.map((row, i) => (
        <div key={i} className="ct-row">
          {row.map((cell, j) => (
            <div key={j} className={j === 1 ? "ct-us" : ""}>{cell}</div>
          ))}
        </div>
      ))}
    </div>
  );
}

Object.assign(window, {
  PricingGrid, BrandSlider, BundleCalc, CompareTable
});
