/* global React, Icon, VehicleCard, CV_INVENTORY, CV_BRANDS */
const { useState, useEffect, useMemo } = React;

// ─────────────────────────────────────────────────────────────────────────────
// INVENTORY
// ─────────────────────────────────────────────────────────────────────────────
function InventoryPage({ setPage, openVehicle, initialFilter }) {
  const [query, setQuery] = useState("");
  const [brand, setBrand] = useState("All");
  const [body, setBody] = useState(initialFilter && ["SUV","Coupe","Sedan","Convertible","Hypercar","Classic"].includes(initialFilter) ? initialFilter : "All");
  const [tag, setTag] = useState(initialFilter && ["Sport","Luxury","Classic","Halo","New"].includes(initialFilter) ? initialFilter : "All");
  const [yearRange, setYearRange] = useState("All");
  const [sort, setSort] = useState("featured");
  const [view, setView] = useState("grid"); // grid | row

  const bodies = ["All", "Hypercar", "Coupe", "Convertible", "Sedan", "SUV", "Classic"];
  const tags = ["All", "Halo", "Sport", "Luxury", "Classic", "New"];
  const brands = ["All", ...new Set(CV_INVENTORY.map(v => v.make))];

  const filtered = useMemo(() => {
    let out = CV_INVENTORY.slice();
    if (query) {
      const q = query.toLowerCase();
      out = out.filter(v => `${v.year} ${v.make} ${v.model}`.toLowerCase().includes(q));
    }
    if (brand !== "All") out = out.filter(v => v.make === brand);
    if (body !== "All") out = out.filter(v => v.body === body);
    if (tag !== "All") out = out.filter(v => v.tag === tag);
    if (yearRange !== "All") {
      const [lo, hi] = ({
        "2024+": [2024, 9999],
        "2020+": [2020, 9999],
        "2015–2019": [2015, 2019],
        "Pre-2015": [0, 2014]
      })[yearRange];
      out = out.filter(v => v.year >= lo && v.year <= hi);
    }
    if (sort === "yearDesc") out.sort((a,b) => b.year - a.year);
    if (sort === "yearAsc") out.sort((a,b) => a.year - b.year);
    if (sort === "az") out.sort((a,b) => a.make.localeCompare(b.make));
    return out;
  }, [query, brand, body, tag, yearRange, sort]);

  const clearAll = () => {
    setQuery(""); setBrand("All"); setBody("All"); setTag("All"); setYearRange("All"); setSort("featured");
  };

  const active = [
    query && ["search", `"${query}"`],
    brand !== "All" && ["brand", brand],
    body !== "All" && ["body", body],
    tag !== "All" && ["tag", tag],
    yearRange !== "All" && ["year", yearRange]
  ].filter(Boolean);

  return (
    <main data-screen-label="Inventory" className="cv-inventory">
      <div className="cv-inv-head">
        <div className="cv-container">
          <div className="cv-eyebrow">Inventory · {filtered.length} of {CV_INVENTORY.length}</div>
          <h1 className="cv-h1">
            Cars currently <em className="cv-italic">on the floor.</em>
          </h1>
          <p className="cv-inv-note">
            Demo inventory drawn from the public showroom listing — production wiring is per-car
            SSG/ISR over the client's live feed, so each vehicle becomes its own indexable page.
          </p>
        </div>
      </div>

      <div className="cv-inv-toolbar">
        <div className="cv-container cv-inv-toolbar-inner">
          <div className="cv-inv-search">
            <Icon.search />
            <input
              placeholder="Search make or model — e.g. Ferrari, Ghost, Huracán"
              value={query}
              onChange={e => setQuery(e.target.value)}
            />
            {query && <button onClick={() => setQuery("")}><Icon.close /></button>}
          </div>

          <div className="cv-inv-sort">
            <label>Sort</label>
            <select value={sort} onChange={e => setSort(e.target.value)}>
              <option value="featured">Featured</option>
              <option value="yearDesc">Year — newest</option>
              <option value="yearAsc">Year — oldest</option>
              <option value="az">Make A–Z</option>
            </select>
          </div>

          <div className="cv-inv-view">
            <button className={view === "grid" ? "is-on" : ""} onClick={() => setView("grid")} title="Grid">
              <svg width="14" height="14" viewBox="0 0 14 14"><rect x="1" y="1" width="5" height="5" fill="currentColor"/><rect x="8" y="1" width="5" height="5" fill="currentColor"/><rect x="1" y="8" width="5" height="5" fill="currentColor"/><rect x="8" y="8" width="5" height="5" fill="currentColor"/></svg>
            </button>
            <button className={view === "row" ? "is-on" : ""} onClick={() => setView("row")} title="Row">
              <svg width="14" height="14" viewBox="0 0 14 14"><rect x="1" y="2" width="12" height="2" fill="currentColor"/><rect x="1" y="6" width="12" height="2" fill="currentColor"/><rect x="1" y="10" width="12" height="2" fill="currentColor"/></svg>
            </button>
          </div>
        </div>
      </div>

      <div className="cv-container cv-inv-body">
        <aside className="cv-inv-filters">
          <div className="cv-filt-h">Filter</div>

          <div className="cv-filt-group">
            <div className="cv-filt-label">Brand</div>
            <div className="cv-filt-chips">
              {brands.map(b => (
                <button
                  key={b}
                  className={`cv-chip ${brand === b ? "is-on" : ""}`}
                  onClick={() => setBrand(b)}
                >{b}</button>
              ))}
            </div>
          </div>

          <div className="cv-filt-group">
            <div className="cv-filt-label">Body</div>
            <div className="cv-filt-chips">
              {bodies.map(b => (
                <button
                  key={b}
                  className={`cv-chip ${body === b ? "is-on" : ""}`}
                  onClick={() => setBody(b)}
                >{b}</button>
              ))}
            </div>
          </div>

          <div className="cv-filt-group">
            <div className="cv-filt-label">Character</div>
            <div className="cv-filt-chips">
              {tags.map(t => (
                <button
                  key={t}
                  className={`cv-chip ${tag === t ? "is-on" : ""}`}
                  onClick={() => setTag(t)}
                >{t}</button>
              ))}
            </div>
          </div>

          <div className="cv-filt-group">
            <div className="cv-filt-label">Year</div>
            <div className="cv-filt-chips cv-filt-chips-stack">
              {["All","2024+","2020+","2015–2019","Pre-2015"].map(y => (
                <button
                  key={y}
                  className={`cv-chip ${yearRange === y ? "is-on" : ""}`}
                  onClick={() => setYearRange(y)}
                >{y}</button>
              ))}
            </div>
          </div>

          <div className="cv-filt-group">
            <div className="cv-filt-label">Price</div>
            <p className="cv-filt-poa">
              No public price list — every car is listed POA. Use the enquiry form on the vehicle page
              to receive the asking figure.
            </p>
          </div>

          <button className="cv-link cv-link-warn" onClick={clearAll}>
            Clear all filters <Icon.close />
          </button>
        </aside>

        <div className="cv-inv-results">
          {active.length > 0 && (
            <div className="cv-active-chips">
              {active.map(([k, label]) => (
                <span key={k} className="cv-chip is-on">{label}</span>
              ))}
              <button className="cv-link cv-link-warn" onClick={clearAll}>
                <Icon.close /> Clear
              </button>
            </div>
          )}

          {filtered.length === 0 ? (
            <div className="cv-empty">
              <h3>No cars match — yet.</h3>
              <p>
                Inventory rotates quickly. WhatsApp the showroom and we'll flag the next arrival
                that fits your brief.
              </p>
              <a className="cv-btn cv-btn-primary" href={CV_FACTS.whatsapp} target="_blank" rel="noopener">
                <Icon.wa /> WhatsApp the desk
              </a>
            </div>
          ) : view === "grid" ? (
            <div className="cv-card-grid cv-card-grid-3">
              {filtered.map(v => <VehicleCard key={v.id} v={v} onOpen={openVehicle} />)}
            </div>
          ) : (
            <div className="cv-row-list">
              {filtered.map(v => <InventoryRow key={v.id} v={v} onOpen={openVehicle} />)}
            </div>
          )}
        </div>
      </div>
    </main>
  );
}

function InventoryRow({ v, onOpen }) {
  return (
    <button className="cv-row" onClick={() => onOpen(v)}>
      <div className="cv-row-media"><img src={v.image} alt="" loading="lazy" /></div>
      <div className="cv-row-meta">
        <div className="cv-row-meta-h">
          <span className="cv-row-year">{v.year}</span>
          <span className="cv-row-title">{v.make} {v.model}</span>
        </div>
        <div className="cv-row-meta-s">{v.headline}</div>
      </div>
      <div className="cv-row-specs">
        <div><span>Body</span>{v.body}</div>
        <div><span>Drivetrain</span>{v.drivetrain}</div>
        <div><span>Transmission</span>{v.transmission}</div>
        <div><span>Exterior</span>{v.exterior}</div>
      </div>
      <div className="cv-row-end">
        <div className="cv-row-price">{v.price === "POA" ? <em>POA</em> : v.price}</div>
        <span className="cv-row-cta">View <Icon.arrow /></span>
      </div>
    </button>
  );
}

window.InventoryPage = InventoryPage;
