// WySync — interactive widgets shared across pages.
// Brand list, sample wheels/tires catalog, refresh viz, YMMS, plan tiers.

const BRANDS = [
  "Forgiato", "Vossen", "Rotiform", "HRE", "Niche", "Fuel", "American Racing",
  "Method", "BBS", "Enkei", "Konig", "ESR", "Avant Garde", "Velgen", "Ferrada",
  "Lexani", "Asanti", "Klutch", "TSW", "OZ Racing", "Volk", "Work", "Rays",
  "Advan", "Rotiform", "Apex", "Forgestar", "Stance SF", "Rohana", "ANRKY",
  "BC Forged", "Brixton Forged", "ADV.1", "Savini", "Dub", "MHT", "Black Rhino",
  "XD Wheels", "Pro Comp", "Mickey Thompson", "Toyo", "Nitto", "Falken",
  "Yokohama", "BFGoodrich", "Continental", "Michelin", "Pirelli", "Hankook",
  "Cooper", "Kumho", "Nexen", "General", "Goodyear", "Bridgestone", "Sumitomo",
  "Maxxis", "Atturo", "Achilles", "Federal", "Vredestein", "Westlake", "GT Radial",
];

const SAMPLE_WHEELS = [
  { id: "FRG-F215", brand: "Forgiato",   model: "F2.15",       size: '24x10',  bolt: "6x139.7", finish: "Brushed Bronze", price: 4250, stock: 12, type: "wheel" },
  { id: "VSN-HF61", brand: "Vossen",     model: "HF-6.1",      size: '22x10.5',bolt: "5x114.3", finish: "Tinted Gloss",   price: 1890, stock: 48, type: "wheel" },
  { id: "RTF-LSR",  brand: "Rotiform",   model: "LSR",         size: '19x8.5', bolt: "5x112",   finish: "Matte Black",    price:  529, stock: 124,type: "wheel" },
  { id: "HRE-P101", brand: "HRE",        model: "P101",        size: '20x9',   bolt: "5x120",   finish: "Liquid Silver",  price: 3200, stock: 6,  type: "wheel" },
  { id: "NCH-MIS",  brand: "Niche",      model: "Misano",      size: '22x9',   bolt: "5x114.3", finish: "Gloss Black",    price:  749, stock: 86, type: "wheel" },
  { id: "FUL-MAV",  brand: "Fuel",       model: "Maverick",    size: '20x9',   bolt: "6x135",   finish: "Black/Milled",   price:  399, stock: 220,type: "wheel" },
  { id: "MTH-305",  brand: "Method",     model: "305 NV",      size: '17x8.5', bolt: "6x139.7", finish: "Matte Black",    price:  329, stock: 152,type: "wheel" },
  { id: "TYO-PXT",  brand: "Toyo",       model: "Proxes Sport",size: '275/35R20',bolt:"—",      finish: "—",              price:  389, stock: 96, type: "tire"  },
  { id: "NTT-NT05", brand: "Nitto",      model: "NT05",        size: '305/30R20',bolt:"—",      finish: "—",              price:  329, stock: 64, type: "tire"  },
  { id: "MIC-PS4",  brand: "Michelin",   model: "Pilot Sport 4S",size:'285/35R19',bolt:"—",     finish: "—",              price:  349, stock: 180,type: "tire"  },
  { id: "BFG-KO2",  brand: "BFGoodrich", model: "All-Terrain KO2",size:'285/70R17',bolt:"—",    finish: "—",              price:  295, stock: 312,type: "tire"  },
  { id: "BBS-CHR",  brand: "BBS",        model: "CH-R II",     size: '20x9',   bolt: "5x112",   finish: "Satin Bronze",   price: 1490, stock: 18, type: "wheel" },
];

// ────────── catalog browser ──────────
function CatalogBrowser() {
  const [q, setQ] = useState("");
  const [type, setType] = useState("all");
  const [sort, setSort] = useState("brand");

  const rows = useMemo(() => {
    let r = SAMPLE_WHEELS.slice();
    if (type !== "all") r = r.filter(w => w.type === type);
    if (q.trim()) {
      const s = q.toLowerCase();
      r = r.filter(w =>
        w.brand.toLowerCase().includes(s) ||
        w.model.toLowerCase().includes(s) ||
        w.id.toLowerCase().includes(s)
      );
    }
    r.sort((a, b) => sort === "price" ? a.price - b.price : a.brand.localeCompare(b.brand));
    return r;
  }, [q, type, sort]);

  return (
    <div className="catalog">
      <div className="catalog-head">
        <div className="mono" style={{ color: "var(--fg-3)" }}>GET /v1/catalog?limit=12</div>
        <div className="catalog-controls">
          <input
            className="cat-input"
            placeholder="Search brand, model, SKU…"
            value={q}
            onChange={e => setQ(e.target.value)}
          />
          <div className="seg">
            {["all", "wheel", "tire"].map(t => (
              <button key={t}
                className={`seg-btn ${type === t ? "on" : ""}`}
                onClick={() => setType(t)}>{t}</button>
            ))}
          </div>
          <select className="cat-select" value={sort} onChange={e => setSort(e.target.value)}>
            <option value="brand">Sort: Brand</option>
            <option value="price">Sort: Price</option>
          </select>
        </div>
      </div>

      <div className="catalog-table">
        <div className="cat-row cat-th">
          <div>SKU</div><div>Brand / Model</div><div>Size</div>
          <div>Bolt pattern</div><div>Finish</div>
          <div className="ta-r">MAP</div><div className="ta-r">Stock</div>
        </div>
        {rows.slice(0, 9).map((w, i) => (
          <div className="cat-row" key={w.id} style={{ animationDelay: `${i * 30}ms` }}>
            <div className="mono" style={{ color: "var(--fg-3)" }}>{w.id}</div>
            <div><strong>{w.brand}</strong> <span style={{ color: "var(--fg-2)" }}>{w.model}</span></div>
            <div className="mono">{w.size}</div>
            <div className="mono">{w.bolt}</div>
            <div>{w.finish}</div>
            <div className="ta-r mono"><span style={{ color: "var(--accent)" }}>${w.price.toLocaleString()}</span></div>
            <div className="ta-r mono">{w.stock > 100 ? <span style={{ color: "var(--good)" }}>{w.stock}</span> : w.stock < 20 ? <span style={{ color: "var(--warn)" }}>{w.stock}</span> : w.stock}</div>
          </div>
        ))}
        {rows.length === 0 && (
          <div className="cat-empty mono">No results — but the real catalog has {((window.WYSYNC_DATA?.counts?.combined?.brands) || 573)}+ brands.</div>
        )}
      </div>

      <div className="catalog-foot mono">
        <span>showing {Math.min(rows.length, 9)} of {rows.length} sample rows · live catalog: {((window.WYSYNC_DATA?.counts?.combined?.skus) || 285455).toLocaleString()}+ SKUs</span>
        <span className="catalog-live"><span className="pulse" /> Streaming</span>
      </div>
    </div>
  );
}

// ────────── refresh viz: daily → hourly → realtime ──────────
function RefreshViz() {
  const [tier, setTier] = useState(2); // 0..3
  const tiers = [
    { name: "Starter",    catalog: "weekly",  map: "daily",   inv: "—",       cadence: 168, label: "STARTER" },
    { name: "Growth",     catalog: "daily",   map: "daily",   inv: "daily",   cadence: 24,  label: "GROWTH" },
    { name: "Pro",        catalog: "daily",   map: "hourly",  inv: "hourly",  cadence: 1,   label: "PRO" },
    { name: "Enterprise", catalog: "realtime",map: "realtime",inv: "realtime",cadence: 0.0167, label: "ENTERPRISE" },
  ];
  const t = tiers[tier];

  // live ticker
  const [now, setNow] = useState(0);
  useEffect(() => {
    const iv = setInterval(() => setNow(n => n + 1), 80);
    return () => clearInterval(iv);
  }, []);

  // emit dots based on cadence
  const dotCount = tier === 3 ? 60 : tier === 2 ? 24 : tier === 1 ? 8 : 2;

  return (
    <div className="refresh">
      <div className="refresh-head">
        <div>
          <div className="mono" style={{ color: "var(--fg-3)" }}>SYNC CADENCE</div>
          <h3 style={{ marginTop: 8 }}>{t.name} · {t.catalog === "realtime" ? "realtime" : t.map} push</h3>
        </div>
        <div className="seg">
          {tiers.map((x, i) => (
            <button key={x.label}
              className={`seg-btn ${tier === i ? "on" : ""}`}
              onClick={() => setTier(i)}>{x.label}</button>
          ))}
        </div>
      </div>

      <div className="refresh-grid">
        <div className="refresh-row">
          <div className="rrow-label mono">Catalog</div>
          <div className="rrow-track">
            <DotStream count={Math.max(2, Math.round(dotCount * 0.4))} active offset={now} />
          </div>
          <div className="rrow-val mono">{t.catalog}</div>
        </div>
        <div className="refresh-row">
          <div className="rrow-label mono">MAP</div>
          <div className="rrow-track">
            <DotStream count={Math.max(2, Math.round(dotCount * 0.7))} active offset={now * 1.4} />
          </div>
          <div className="rrow-val mono">{t.map}</div>
        </div>
        <div className="refresh-row">
          <div className="rrow-label mono">Inventory</div>
          <div className="rrow-track">
            {t.inv === "—"
              ? <div className="mono" style={{ color: "var(--fg-3)", padding: "4px 0" }}>not included</div>
              : <DotStream count={dotCount} active offset={now * 1.8} />}
          </div>
          <div className="rrow-val mono">{t.inv}</div>
        </div>
      </div>
      <div className="mono" style={{ color: "var(--fg-3)", marginTop: 16 }}>
        ⇒ {tier === 0 ? "Catalog stable; pricing kept honest." :
             tier === 1 ? "Inventory live; supplier handoffs included." :
             tier === 2 ? "Hourly pulse; API-first storefronts stay in sync." :
             "Realtime stream; every price, every SKU, the moment it changes."}
      </div>
    </div>
  );
}

function DotStream({ count, offset }) {
  const dots = Array.from({ length: count });
  return (
    <div className="dotstream">
      {dots.map((_, i) => {
        const phase = ((i / count) + (offset / 100)) % 1;
        const lit = phase > 0.85 ? 1 : phase > 0.7 ? 0.6 : 0.18;
        return <span key={i} className="dot-tick" style={{ opacity: lit }} />;
      })}
    </div>
  );
}

// ────────── YMMS fitment widget ──────────
const YMMS_DATA = {
  2024: {
    "Ford":  { "F-150": ["XLT", "Lariat", "Raptor", "Tremor"], "Mustang": ["GT", "EcoBoost", "Dark Horse"], "Bronco": ["Wildtrak", "Badlands", "Raptor"] },
    "Chevy": { "Silverado 1500": ["LT", "RST", "Trail Boss", "ZR2"], "Tahoe": ["LT", "RST", "Z71"], "Camaro": ["SS 1LE", "ZL1"] },
    "Toyota":{ "Tacoma": ["TRD Sport", "TRD Off-Road", "TRD Pro"], "4Runner": ["TRD Pro", "TRD Off-Road"], "Tundra": ["SR5", "TRD Pro"] },
    "BMW":   { "M3": ["Competition", "CS"], "M4": ["Competition", "CSL"], "X5 M": ["Competition"] },
    "Tesla": { "Model 3": ["Performance", "Long Range"], "Model Y": ["Performance", "Long Range"], "Cybertruck": ["AWD", "Cyberbeast"] },
  },
  2023: {
    "Ford":  { "F-150": ["XLT", "Lariat", "Raptor"], "Mustang": ["GT", "Mach 1"] },
    "Toyota":{ "Tacoma": ["TRD Sport", "TRD Off-Road", "TRD Pro"] },
  },
  2022: {
    "Ford":  { "F-150": ["XLT", "Lariat", "Raptor"] },
    "Chevy": { "Silverado 1500": ["LT", "RST", "Trail Boss"] },
  },
};

function YmmsWidget({ embedded = false }) {
  const [step, setStep] = useState(0);
  const [year, setYear] = useState("");
  const [make, setMake] = useState("");
  const [model, setModel] = useState("");
  const [sub, setSub] = useState("");

  const years  = Object.keys(YMMS_DATA);
  const makes  = year ? Object.keys(YMMS_DATA[year]) : [];
  const models = year && make ? Object.keys(YMMS_DATA[year][make] || {}) : [];
  const subs   = year && make && model ? (YMMS_DATA[year][make][model] || []) : [];

  const reset = () => { setYear(""); setMake(""); setModel(""); setSub(""); setStep(0); };

  const fits = useMemo(() => {
    if (!sub) return [];
    // pseudorandom but stable selection
    const seed = (year + make + model + sub).split("").reduce((a, c) => a + c.charCodeAt(0), 0);
    const wheels = SAMPLE_WHEELS.filter(w => w.type === "wheel");
    return wheels.slice(0, 3 + (seed % 3)).map((w, i) => ({
      ...w,
      offset: ["+18mm", "+25mm", "+30mm", "+35mm", "+42mm"][(seed + i) % 5],
      backspace: ["5.5\"", "5.75\"", "6.0\"", "6.25\""][(seed + i) % 4],
    }));
  }, [year, make, model, sub]);

  return (
    <div className={`ymms ${embedded ? "ymms-embed" : ""}`}>
      <div className="ymms-head">
        <div className="ymms-brand mono">
          <span className="brand-mark" style={{ width: 14, height: 14, borderWidth: 1 }} />
          Fitment by WySync
        </div>
        <div className="mono" style={{ color: "var(--fg-3)" }}>STEP {Math.min(step + 1, 4)} / 4</div>
      </div>

      {!sub ? (
        <>
          <div className="ymms-title">Will it fit your vehicle?</div>
          <div className="ymms-sub mono">Select year → make → model → submodel</div>

          <div className="ymms-grid">
            <YmmsCol label="Year" value={year}>
              {years.map(y => (
                <button key={y}
                  className={`ymms-pick ${year === y ? "on" : ""}`}
                  onClick={() => { setYear(y); setMake(""); setModel(""); setSub(""); setStep(1); }}>{y}</button>
              ))}
            </YmmsCol>
            <YmmsCol label="Make" value={make} disabled={!year}>
              {makes.map(m => (
                <button key={m}
                  className={`ymms-pick ${make === m ? "on" : ""}`}
                  onClick={() => { setMake(m); setModel(""); setSub(""); setStep(2); }}>{m}</button>
              ))}
            </YmmsCol>
            <YmmsCol label="Model" value={model} disabled={!make}>
              {models.map(m => (
                <button key={m}
                  className={`ymms-pick ${model === m ? "on" : ""}`}
                  onClick={() => { setModel(m); setSub(""); setStep(3); }}>{m}</button>
              ))}
            </YmmsCol>
            <YmmsCol label="Submodel" value={sub} disabled={!model}>
              {subs.map(s => (
                <button key={s}
                  className={`ymms-pick ${sub === s ? "on" : ""}`}
                  onClick={() => { setSub(s); setStep(4); }}>{s}</button>
              ))}
            </YmmsCol>
          </div>
        </>
      ) : (
        <>
          <div className="ymms-result">
            <div>
              <div className="mono" style={{ color: "var(--good)" }}>✓ MATCH FOUND</div>
              <div className="ymms-vehicle">{year} {make} {model} <span style={{ color: "var(--fg-2)" }}>{sub}</span></div>
            </div>
            <button className="btn btn-sm btn-ghost" onClick={reset}>← Change vehicle</button>
          </div>

          <div className="ymms-fits">
            {fits.map(w => (
              <div className="ymms-fit" key={w.id}>
                <div className="ymms-fit-img placeholder">
                  <span>{w.brand.split(" ")[0].toUpperCase()}</span>
                </div>
                <div className="ymms-fit-body">
                  <div className="ymms-fit-title">{w.brand} <span style={{ color: "var(--fg-2)" }}>{w.model}</span></div>
                  <div className="mono" style={{ color: "var(--fg-3)", marginTop: 4 }}>
                    {w.size} · {w.bolt} · offset {w.offset}
                  </div>
                  <div className="ymms-fit-foot">
                    <span className="mono" style={{ color: "var(--accent)" }}>${w.price.toLocaleString()}</span>
                    <span className="mono" style={{ color: "var(--good)" }}>✓ Confirmed fit</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </>
      )}
    </div>
  );
}

function YmmsCol({ label, value, disabled, children }) {
  return (
    <div className={`ymms-col ${disabled ? "off" : ""}`}>
      <div className="ymms-col-head mono">
        <span>{label}</span>
        {value && <span style={{ color: "var(--accent)" }}>{value}</span>}
      </div>
      <div className="ymms-col-body">
        {!disabled ? children : <div className="mono" style={{ color: "var(--fg-3)", padding: "8px" }}>—</div>}
      </div>
    </div>
  );
}

// ────────── plan tiers data ──────────
const PLAN_TIERS = [
  {
    id: "starter", name: "Starter",
    monthly: 499, annual: 5489, annualMonths: 8,
    brands: 30, brandsMax: 30,
    rows: [
      ["Catalog refresh", "weekly"],
      ["MAP updates", "daily"],
      ["Inventory feed", "—"],
      ["Supplier contacts", "—"],
      ["API access", "—"],
      ["Lifestyle images", "—"],
      ["Storefront integration", "✓"],
    ],
    best: "New entrants. Clean catalog without the inventory complexity.",
  },
  {
    id: "growth", name: "Growth",
    monthly: 1200, annual: 13200, annualMonths: 8,
    brands: 75, brandsMax: 75,
    rows: [
      ["Catalog refresh", "daily"],
      ["MAP updates", "daily"],
      ["Inventory feed", "daily"],
      ["Supplier contacts", "✓"],
      ["API access", "—"],
      ["Lifestyle images", "—"],
      ["Storefront integration", "✓"],
    ],
    best: "Retailers needing live inventory and supplier handoffs.",
    popular: true,
  },
  {
    id: "pro", name: "Pro",
    monthly: 2999, annual: 32989, annualMonths: 8,
    brands: 250, brandsMax: 250,
    rows: [
      ["Catalog refresh", "per scope"],
      ["MAP updates", "hourly"],
      ["Inventory feed", "hourly"],
      ["Supplier contacts", "✓"],
      ["API access", "✓ scoped"],
      ["Lifestyle images", "✓"],
      ["Storefront integration", "✓"],
    ],
    best: "Big retailers running API-first storefronts.",
  },
  {
    id: "enterprise", name: "Enterprise",
    monthly: 5000, annual: 55000, annualMonths: 8,
    brands: 450, brandsMax: 450,
    rows: [
      ["Catalog refresh", "realtime"],
      ["MAP updates", "realtime"],
      ["Inventory feed", "realtime"],
      ["Supplier contacts", "✓"],
      ["API access", "✓"],
      ["Lifestyle images", "✓"],
      ["Priority requests", "5 biz days"],
      ["Custom format exports", "✓"],
      ["Dedicated support", "✓"],
    ],
    best: "Dominant retailers needing the entire catalog.",
    annualOnly: true,
  },
];

Object.assign(window, {
  BRANDS, SAMPLE_WHEELS, PLAN_TIERS,
  CatalogBrowser, RefreshViz, YmmsWidget
});
