/* ============================================================
   PRESTIGE BIMMER — Inventory: VehicleCard, Grid, Featured
   ============================================================ */

/* ---------------- spec pill ---------------- */
function Spec({ icon, value }) {
  return (
    <span className="spec mono"><Icon name={icon} size={14} />{value}</span>
  );
}

const statusLabel = { available: "Available", reserved: "Reserved", sold: "Sold" };

/* ---------------- Vehicle card ---------------- */
function VehicleCard({ v, i = 0, reveal = true }) {
  const tilt = useRef(null);
  const onMove = (e) => {
    const el = tilt.current; if (!el) return;
    const r = el.getBoundingClientRect();
    const px = (e.clientX - r.left) / r.width - 0.5;
    const py = (e.clientY - r.top) / r.height - 0.5;
    el.style.setProperty("--rx", (py * -5).toFixed(2) + "deg");
    el.style.setProperty("--ry", (px * 6).toFixed(2) + "deg");
  };
  const reset = () => {
    const el = tilt.current; if (!el) return;
    el.style.setProperty("--rx", "0deg"); el.style.setProperty("--ry", "0deg");
  };
  return (
    <a href={"#/vehicle/" + v.id} className="vcard" ref={tilt}
      onMouseMove={onMove} onMouseLeave={reset}
      {...(reveal ? { "data-reveal": "scale" } : {})} style={{ "--d": `${(i % 3) * 90}ms` }}>
      <div className="vcard-media">
        <Photo className="vcard-photo" label={v.images && v.images[0] ? v.images[0] : v.model} src={v.heroImg || (v.imageUrls && v.imageUrls[0])} />
        <span className={"badge badge-" + v.status + " vcard-badge"}>{statusLabel[v.status]}</span>
        {v.featured && <span className="vcard-fav mono"><Icon name="star" size={12} fill /> Featured</span>}
        <span className="vcard-series mono">{v.series}</span>
      </div>
      <div className="vcard-body">
        <div className="vcard-head">
          <div>
            <span className="vcard-year mono">{v.year}</span>
            <h3 className="vcard-title">{v.model}</h3>
          </div>
          <span className="vcard-price tnum">{fmtPrice(v.price)}</span>
        </div>
        <div className="vcard-specs">
          <Spec icon="road" value={fmtMiles(v.mileage) + " mi"} />
          <Spec icon="gauge" value={v.power + " hp"} />
          <Spec icon="cog" value={v.drivetrain.split(" ")[0]} />
          <Spec icon="fuel" value={v.fuel} />
        </div>
        <div className="vcard-foot">
          <span className="vcard-cta">View details <Icon name="arrow" size={15} /></span>
          <span className="vcard-color mono">{v.color}</span>
        </div>
      </div>
      <div className="vcard-glow" />
    </a>
  );
}

/* ---------------- Featured showcase (homepage) ---------------- */
function FeaturedShowcase() {
  useRevealObserver();
  const featured = useInventory().filter(v => v.featured && v.status !== "sold").slice(0, 3);
  if (!featured.length) return null;
  return (
    <section className="section featured" id="featured">
      <div className="wrap">
        <div className="sec-head sec-head-row">
          <div>
            <span className="kicker" data-reveal>Featured this week</span>
            <h2 className="display-l" data-reveal style={{ "--d": "60ms" }}>The current highlights.</h2>
          </div>
          <a href="#/inventory" className="btn btn-ghost sec-head-cta" data-reveal style={{ "--d": "120ms" }}>
            View all inventory <Icon name="arrow" size={16} />
          </a>
        </div>
        <div className="featured-grid">
          {featured.map((v, i) => <VehicleCard key={v.id} v={v} i={i} />)}
        </div>
      </div>
    </section>
  );
}

/* ---------------- Full inventory page ---------------- */
function InventoryPage() {
  const all = useInventory();
  const [series, setSeries] = useState("All");
  const [body, setBody] = useState("All");
  const [sort, setSort] = useState("featured");
  const [q, setQ] = useState("");
  const [hideSold, setHideSold] = useState(false);

  useRevealObserver(series + body + sort + q + hideSold);

  const seriesOpts = ["All", ...PB.SERIES];
  const bodyOpts = ["All", ...PB.BODIES];

  let list = all.filter(v => {
    if (series !== "All" && v.series !== series) return false;
    if (body !== "All" && v.body !== body) return false;
    if (hideSold && v.status === "sold") return false;
    if (q) {
      const hay = (v.model + " " + v.color + " " + v.series + " " + v.year).toLowerCase();
      if (!hay.includes(q.toLowerCase())) return false;
    }
    return true;
  });
  list = list.slice().sort((a, b) => {
    if (sort === "price-asc") return a.price - b.price;
    if (sort === "price-desc") return b.price - a.price;
    if (sort === "miles") return a.mileage - b.mileage;
    if (sort === "year") return b.year - a.year;
    return (b.featured - a.featured) || (b.year - a.year);
  });

  return (
    <main className="inv-page">
      <div className="inv-hero">
        <div className="wrap">
          <span className="kicker" data-reveal>The collection</span>
          <h1 className="display-l" data-reveal style={{ "--d": "60ms" }}>Inventory</h1>
          <p className="lede" data-reveal style={{ "--d": "120ms" }}>
            {all.filter(v => v.status === "available").length} cars available now · every one inspected, documented and ready to drive.
          </p>
        </div>
      </div>

      <div className="inv-controls wrap">
        <div className="inv-search">
          <Icon name="search" size={18} />
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search model, colour, year…" />
          {q && <button onClick={() => setQ("")} className="inv-search-clear"><Icon name="x" size={15} /></button>}
        </div>
        <div className="inv-sort">
          <Icon name="filter" size={16} />
          <select value={sort} onChange={e => setSort(e.target.value)}>
            <option value="featured">Featured first</option>
            <option value="price-asc">Price · low to high</option>
            <option value="price-desc">Price · high to low</option>
            <option value="miles">Lowest mileage</option>
            <option value="year">Newest year</option>
          </select>
        </div>
      </div>

      <div className="inv-filters wrap">
        <div className="inv-chips">
          {seriesOpts.map(s => (
            <button key={s} className={"chip " + (series === s ? "active" : "")} onClick={() => setSeries(s)}>{s}</button>
          ))}
        </div>
        <div className="inv-chips-sub">
          {bodyOpts.map(b => (
            <button key={b} className={"chip " + (body === b ? "active" : "")} onClick={() => setBody(b)}>{b}</button>
          ))}
          <button className={"chip " + (hideSold ? "active" : "")} onClick={() => setHideSold(s => !s)}>
            <Icon name="check" size={12} /> Hide sold
          </button>
        </div>
      </div>

      <div className="wrap">
        <div className="inv-count mono">{list.length} {list.length === 1 ? "result" : "results"}</div>
        {list.length ? (
          <div className="inv-grid">
            {list.map((v, i) => <VehicleCard key={v.id} v={v} i={i} />)}
          </div>
        ) : (
          <div className="inv-empty">
            <Icon name="search" size={40} />
            <h3>No cars match those filters.</h3>
            <button className="btn btn-ghost" onClick={() => { setSeries("All"); setBody("All"); setQ(""); setHideSold(false); }}>Clear filters</button>
          </div>
        )}
      </div>
    </main>
  );
}

Object.assign(window, { VehicleCard, FeaturedShowcase, InventoryPage, Spec, statusLabel });
