/* inventory.jsx — inventory filtering + grid */

const { useState: useStateI, useMemo: useMemoI } = React;

function Inventory({ onSelect, onEnquire, initialFilter = {} }) {
  const [brand, setBrand] = useStateI(initialFilter.brand || "All");
  const [body, setBody] = useStateI(initialFilter.body || "All");
  const [status, setStatus] = useStateI(initialFilter.status || "all");
  const [sort, setSort] = useStateI("newest");
  const [view, setView] = useStateI("grid");

  const filtered = useMemoI(() => {
    let r = INVENTORY.filter((v) => {
      if (brand !== "All" && v.brand !== brand) return false;
      if (body !== "All" && v.body !== body) return false;
      if (status === "available" && v.status !== "available") return false;
      if (status === "sold" && v.status !== "sold") return false;
      return true;
    });
    if (sort === "newest") r = r.sort((a, b) => b.year - a.year);
    if (sort === "oldest") r = r.sort((a, b) => a.year - b.year);
    if (sort === "az") r = r.sort((a, b) => a.brand.localeCompare(b.brand) || a.model.localeCompare(b.model));
    return r;
  }, [brand, body, status, sort]);

  const counts = useMemoI(() => {
    const all = INVENTORY.length;
    const avail = INVENTORY.filter((v) => v.status === "available").length;
    const sold = INVENTORY.filter((v) => v.status === "sold").length;
    return { all, avail, sold };
  }, []);

  const brandCounts = useMemoI(() => {
    const c = {};
    INVENTORY.forEach((v) => { c[v.brand] = (c[v.brand] || 0) + 1; });
    return c;
  }, []);

  return (
    <main>
      {/* Page header */}
      <section style={{ paddingTop: 140, paddingBottom: 56, background: "var(--noir)", borderBottom: "1px solid var(--line)", position: "relative", overflow: "hidden" }}>
        <div style={{
          position: "absolute", right: 0, top: 0, bottom: 0, width: "50%",
          background: "url(media/inventory-cover.webp) center/cover",
          opacity: 0.4,
          maskImage: "linear-gradient(90deg, transparent 0%, black 50%)",
          WebkitMaskImage: "linear-gradient(90deg, transparent 0%, black 50%)",
        }} />
        <div className="wrap" style={{ position: "relative" }}>
          <div className="kbd-eyebrow" style={{ marginBottom: 18 }}>Inventory · Updated daily</div>
          <h1 className="display" style={{ fontSize: "clamp(48px, 7vw, 112px)", margin: 0, letterSpacing: "-0.04em", lineHeight: 0.95 }}>
            What's in <br /> the showroom.
          </h1>
          <p style={{ marginTop: 24, fontSize: 17, color: "var(--silver)", maxWidth: 560 }}>
            Filter by marque, bodystyle and status. Prices are private — request on the car you want to see.
          </p>
          <div style={{ marginTop: 24, display: "flex", alignItems: "center", gap: 14 }}>
            <DemoBadge>Demo inventory — replaced by feed in production</DemoBadge>
            <span className="mono" style={{ fontSize: 11, color: "var(--mute)", letterSpacing: "0.08em", textTransform: "uppercase" }}>
              {filtered.length} of {counts.all} shown
            </span>
          </div>
        </div>
      </section>

      {/* Filter bar */}
      <section style={{ background: "var(--ink)", borderBottom: "1px solid var(--line)", position: "sticky", top: 64, zIndex: 30, backdropFilter: "blur(10px)" }}>
        <div className="wrap" style={{ paddingBlock: 18 }}>
          <div style={{ display: "flex", gap: 16, alignItems: "center", flexWrap: "wrap" }}>
            {/* Status segmented */}
            <div style={{ display: "inline-flex", border: "1px solid var(--line)", borderRadius: 999, padding: 3 }}>
              {[
                ["all", "All", counts.all],
                ["available", "Available", counts.avail],
                ["sold", "Sold", counts.sold],
              ].map(([k, l, n]) => (
                <button key={k}
                  onClick={() => setStatus(k)}
                  style={{
                    padding: "6px 14px", borderRadius: 999,
                    background: status === k ? "var(--paper)" : "transparent",
                    color: status === k ? "var(--ink-on-paper)" : "var(--silver)",
                    border: 0, cursor: "pointer",
                    fontSize: 12, fontWeight: status === k ? 500 : 400,
                    display: "inline-flex", alignItems: "center", gap: 6,
                  }}>
                  {l} <span className="mono" style={{ opacity: 0.55, fontSize: 10 }}>{n}</span>
                </button>
              ))}
            </div>

            <div style={{ width: 1, height: 24, background: "var(--line)" }} />

            {/* Brand select */}
            <select value={brand} onChange={(e) => setBrand(e.target.value)}
              style={{ background: "transparent", border: "1px solid var(--line)", borderRadius: 999, padding: "8px 14px", color: "var(--silver)", fontSize: 13, cursor: "pointer" }}>
              <option value="All" style={{ background: "var(--ink)" }}>All marques</option>
              {Object.keys(brandCounts).sort().map((b) => (
                <option key={b} value={b} style={{ background: "var(--ink)" }}>{b} · {brandCounts[b]}</option>
              ))}
            </select>

            <select value={body} onChange={(e) => setBody(e.target.value)}
              style={{ background: "transparent", border: "1px solid var(--line)", borderRadius: 999, padding: "8px 14px", color: "var(--silver)", fontSize: 13, cursor: "pointer" }}>
              <option value="All" style={{ background: "var(--ink)" }}>All bodies</option>
              {BODIES.map((b) => <option key={b} value={b} style={{ background: "var(--ink)" }}>{b}</option>)}
            </select>

            {(brand !== "All" || body !== "All" || status !== "all") && (
              <button onClick={() => { setBrand("All"); setBody("All"); setStatus("all"); }}
                className="ul-link" style={{ background: "transparent", border: 0, color: "var(--accent)", cursor: "pointer", fontSize: 12, padding: 4 }}>
                Reset
              </button>
            )}

            <div style={{ marginInlineStart: "auto", display: "flex", gap: 12, alignItems: "center" }}>
              <select value={sort} onChange={(e) => setSort(e.target.value)}
                style={{ background: "transparent", border: 0, color: "var(--silver)", fontSize: 13, cursor: "pointer" }}>
                <option value="newest" style={{ background: "var(--ink)" }}>Sort: Newest year</option>
                <option value="oldest" style={{ background: "var(--ink)" }}>Sort: Oldest year</option>
                <option value="az" style={{ background: "var(--ink)" }}>Sort: A — Z</option>
              </select>
              <div style={{ display: "inline-flex", border: "1px solid var(--line)", borderRadius: 8, padding: 2 }}>
                <button onClick={() => setView("grid")} aria-label="Grid view"
                  style={{ padding: "6px 10px", background: view === "grid" ? "rgba(255,255,255,0.06)" : "transparent", border: 0, color: "var(--silver)", borderRadius: 6, cursor: "pointer" }}>
                  <svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor"><rect x="0" y="0" width="6" height="6"/><rect x="8" y="0" width="6" height="6"/><rect x="0" y="8" width="6" height="6"/><rect x="8" y="8" width="6" height="6"/></svg>
                </button>
                <button onClick={() => setView("list")} aria-label="List view"
                  style={{ padding: "6px 10px", background: view === "list" ? "rgba(255,255,255,0.06)" : "transparent", border: 0, color: "var(--silver)", borderRadius: 6, cursor: "pointer" }}>
                  <svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor"><rect x="0" y="1" width="14" height="2"/><rect x="0" y="6" width="14" height="2"/><rect x="0" y="11" width="14" height="2"/></svg>
                </button>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Grid */}
      <section style={{ paddingBlock: 56, background: "var(--noir)" }}>
        <div className="wrap">
          {filtered.length === 0 ? (
            <EmptyState onEnquire={onEnquire} />
          ) : view === "grid" ? (
            <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 20 }}>
              {filtered.map((v) => <VehicleCard key={v.slug} vehicle={v} onSelect={onSelect} />)}
            </div>
          ) : (
            <ListView vehicles={filtered} onSelect={onSelect} />
          )}
        </div>
      </section>

      {/* Bottom CTA */}
      <section className="paper sec-pad-sm">
        <div className="wrap" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 24, flexWrap: "wrap" }}>
          <div>
            <div className="kbd-eyebrow" style={{ color: "#6a6e75", marginBottom: 12 }}>Don't see it?</div>
            <h3 className="display" style={{ fontSize: 36, margin: 0, color: "var(--ink-on-paper)", maxWidth: 600 }}>
              Commission us to find your next car.
            </h3>
          </div>
          <button className="btn btn-primary" onClick={() => onEnquire({ intent: "enquire" })}>Start a sourcing brief</button>
        </div>
      </section>
    </main>
  );
}

function ListView({ vehicles, onSelect }) {
  return (
    <div style={{ borderTop: "1px solid var(--line)" }}>
      {vehicles.map((v) => (
        <button key={v.slug} onClick={() => onSelect(v.slug)}
          style={{
            display: "grid", gridTemplateColumns: "140px 1fr 100px 120px 120px 80px",
            gap: 24, alignItems: "center",
            padding: "16px 0", width: "100%",
            background: "transparent", border: 0, borderBottom: "1px solid var(--line)", cursor: "pointer", color: "var(--paper)", textAlign: "left",
          }}>
          <div style={{ aspectRatio: "16/10", overflow: "hidden", borderRadius: 6, background: "#0e0f12" }}>
            <img src={v.img} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
          </div>
          <div>
            <div className="mono" style={{ fontSize: 10, color: "var(--mute)", letterSpacing: "0.12em", textTransform: "uppercase" }}>{v.brand}</div>
            <div className="display" style={{ fontSize: 22, marginTop: 4 }}>{v.model}</div>
          </div>
          <div className="mono num" style={{ color: "var(--silver)" }}>{v.year}</div>
          <div className="mono" style={{ fontSize: 12, color: "var(--silver)", letterSpacing: "0.08em", textTransform: "uppercase" }}>{v.body}</div>
          <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
            <span style={{ width: 6, height: 6, borderRadius: 99, background: v.status === "available" ? "#7CE0A8" : "var(--accent)" }} />
            <span className="mono" style={{ fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--silver)" }}>{v.status === "available" ? "Available" : "Sold"}</span>
          </div>
          <div style={{ textAlign: "right", color: "var(--silver)", fontSize: 13 }}>Request →</div>
        </button>
      ))}
    </div>
  );
}

function EmptyState({ onEnquire }) {
  return (
    <div style={{
      border: "1px dashed var(--line)", borderRadius: 16,
      padding: "72px 48px", textAlign: "center", maxWidth: 720, margin: "0 auto",
    }}>
      <div className="kbd-eyebrow" style={{ marginBottom: 16 }}>No matches in current stock</div>
      <h3 className="display" style={{ fontSize: 32, margin: 0 }}>
        New arrivals weekly. <br />
        <span style={{ color: "var(--mute)" }}>Register your interest.</span>
      </h3>
      <p style={{ marginTop: 16, color: "var(--mute)", maxWidth: 460, marginInline: "auto" }}>
        We'll notify you privately when something matching your filters lands at the showroom.
      </p>
      <div style={{ marginTop: 24, display: "flex", justifyContent: "center", gap: 10 }}>
        <button className="btn btn-primary" onClick={() => onEnquire({ intent: "enquire" })}>Notify me</button>
        <button className="btn btn-ghost" onClick={() => onEnquire({ intent: "enquire" })}>Commission a search</button>
      </div>
    </div>
  );
}

Object.assign(window, { Inventory });
