/* global React, ReactDOM, I, CarMedia, Nav, Footer, FabWa, useReveal,
          INVENTORY, fmtPrice, fmtKm, fuelLabel, transmissionLabel, carStatus, carDrive, fullModel, fullVariant, useInventory */
const { useState, useMemo, useEffect, useRef } = React;

/* INVENTORY now comes from shared.jsx */

/* ─── DROPDOWN FILTER ──────────────────────────────────────── */
function FilterDropdown({ label, count, children }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const onClick = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", onClick);
    return () => document.removeEventListener("mousedown", onClick);
  }, []);
  return (
    <div className="fdrop" ref={ref}>
      <button className={"fbtn " + (count > 0 || open ? "active" : "")} onClick={() => setOpen((v) => !v)}>
        {label}
        {count > 0 && <span className="fbtn__count">{count}</span>}
        <span className="fbtn__caret" />
      </button>
      {open && <div className="fdrop__panel">{children}</div>}
    </div>
  );
}

/* ─── SORT DROPDOWN (custom single-select, themed) ─────────── */
function SortDropdown({ value, onChange, options }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const onClick = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", onClick);
    return () => document.removeEventListener("mousedown", onClick);
  }, []);
  const current = options.find((o) => o.v === value) || options[0];
  return (
    <div className="fdrop sort-drop" ref={ref}>
      <button className="sort" onClick={() => setOpen((v) => !v)}>
        <I.sliders />
        <span className="sort__label">{current.label}</span>
        <span className="fbtn__caret" />
      </button>
      {open && (
        <div className="fdrop__panel sort-drop__panel">
          {options.map((o) => (
            <button
              key={o.v}
              className={"fdrop__opt" + (o.v === value ? " is-active" : "")}
              onClick={() => { onChange(o.v); setOpen(false); }}
            >
              {o.label}
              {o.v === value && <span className="fdrop__opt-meta">✓</span>}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

/* ─── INDIVIDUAL FILTER PANELS ─────────────────────────────── */
function MultiSelect({ title, options, value, onChange, counts }) {
  const toggle = (v) => {
    onChange(value.includes(v) ? value.filter((x) => x !== v) : [...value, v]);
  };
  return (
    <>
      <h6>{title}</h6>
      <div className="fdrop__opts">
        {options.map((o) => (
          <label key={o} className="fdrop__opt">
            <input type="checkbox" checked={value.includes(o)} onChange={() => toggle(o)} />
            <span>{o}</span>
            {counts && counts[o] !== undefined && <span className="fdrop__opt-meta">{counts[o]}</span>}
          </label>
        ))}
      </div>
    </>
  );
}

function RangeFilter({ title, min, max, value, onChange, unit }) {
  const [lo, hi] = value;
  return (
    <>
      <h6>{title}</h6>
      <div className="fdrop__range">
        <div>
          <label>Vanaf</label>
          <input
            type="number" min={min} max={max} value={lo ?? ""}
            placeholder={String(min) + (unit ? " " + unit : "")}
            onChange={(e) => onChange([e.target.value === "" ? null : Number(e.target.value), hi])}
          />
        </div>
        <div>
          <label>Tot</label>
          <input
            type="number" min={min} max={max} value={hi ?? ""}
            placeholder={String(max) + (unit ? " " + unit : "")}
            onChange={(e) => onChange([lo, e.target.value === "" ? null : Number(e.target.value)])}
          />
        </div>
      </div>
    </>
  );
}

/* ─── PAGE ─────────────────────────────────────────────────── */
const PAGE_SIZE = 9;

function AanbodPage() {
  useReveal();
  const { cars: liveCars, loading, fromLive } = useInventory();
  const INV = liveCars;

  const [q, setQ]                 = useState("");
  const [brands, setBrands]       = useState([]);
  const [bodies, setBodies]       = useState([]);
  const [fuels, setFuels]         = useState([]);
  const [transmissions, setTrans] = useState([]);
  const [priceRange, setPriceRange] = useState([null, null]);
  const [yearRange, setYearRange]   = useState([null, null]);
  const [sort, setSort]           = useState("recent");
  const [view, setView]           = useState("grid");
  const [page, setPage]           = useState(1);

  // derived filter option lists + counts
  const allBrands = useMemo(() => [...new Set(INV.map(c => c.merk))].sort(),         [INV]);
  const allBodies = useMemo(() => [...new Set(INV.map(c => c.carrosserie))].sort(),  [INV]);
  const allFuels  = useMemo(() => [...new Set(INV.map(c => c.brandstof))].sort(),    [INV]);
  const allTrans  = useMemo(() => [...new Set(INV.map(c => c.transmissie))].sort(),  [INV]);
  const brandCounts = useMemo(() => Object.fromEntries(allBrands.map(b => [b, INV.filter(c => c.merk === b).length])), [allBrands, INV]);

  const filtered = useMemo(() => {
    let r = INV.filter((c) => {
      const hay = (c.merk + " " + c.model + " " + (c.type || "") + " " + (c.uitrustingsniveau || "")).toLowerCase();
      if (q && !hay.includes(q.toLowerCase())) return false;
      if (brands.length        && !brands.includes(c.merk))         return false;
      if (bodies.length        && !bodies.includes(c.carrosserie))  return false;
      if (fuels.length         && !fuels.includes(c.brandstof))     return false;
      if (transmissions.length && !transmissions.includes(c.transmissie)) return false;
      if (priceRange[0] != null && c.verkoopprijs_particulier < priceRange[0]) return false;
      if (priceRange[1] != null && c.verkoopprijs_particulier > priceRange[1]) return false;
      if (yearRange[0]  != null && c.bouwjaar < yearRange[0])  return false;
      if (yearRange[1]  != null && c.bouwjaar > yearRange[1])  return false;
      return true;
    });
    if      (sort === "price-asc")  r.sort((a, b) => a.verkoopprijs_particulier - b.verkoopprijs_particulier);
    else if (sort === "price-desc") r.sort((a, b) => b.verkoopprijs_particulier - a.verkoopprijs_particulier);
    else if (sort === "year-desc")  r.sort((a, b) => b.bouwjaar - a.bouwjaar);
    else if (sort === "km-asc")     r.sort((a, b) => a.tellerstand - b.tellerstand);
    // 'recent' = source order
    return r;
  }, [INV, q, brands, bodies, fuels, transmissions, priceRange, yearRange, sort]);

  // reset page when filters change
  useEffect(() => { setPage(1); }, [q, brands, bodies, fuels, transmissions, priceRange, yearRange, sort]);

  const pageCount = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
  const pageItems = filtered.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);

  // active filter chips
  const chips = [];
  brands.forEach((b)        => chips.push({ k: "brand-" + b, label: b,    onRm: () => setBrands(brands.filter(x => x !== b)) }));
  bodies.forEach((b)        => chips.push({ k: "body-"  + b, label: b,    onRm: () => setBodies(bodies.filter(x => x !== b)) }));
  fuels.forEach((f)         => chips.push({ k: "fuel-"  + f, label: f,    onRm: () => setFuels(fuels.filter(x => x !== f)) }));
  transmissions.forEach((t) => chips.push({ k: "trans-" + t, label: t,    onRm: () => setTrans(transmissions.filter(x => x !== t)) }));
  if (priceRange[0] != null || priceRange[1] != null) {
    chips.push({ k: "price", label: "Prijs " + (priceRange[0] != null ? "€" + priceRange[0] : "") + "–" + (priceRange[1] != null ? "€" + priceRange[1] : ""), onRm: () => setPriceRange([null, null]) });
  }
  if (yearRange[0] != null || yearRange[1] != null) {
    chips.push({ k: "year", label: "Jaar " + (yearRange[0] != null ? yearRange[0] : "") + "–" + (yearRange[1] != null ? yearRange[1] : ""), onRm: () => setYearRange([null, null]) });
  }
  if (q) chips.push({ k: "q", label: "\u201C" + q + "\u201D", onRm: () => setQ("") });

  const clearAll = () => {
    setQ(""); setBrands([]); setBodies([]); setFuels([]); setTrans([]);
    setPriceRange([null, null]); setYearRange([null, null]);
  };

  const activeCount = chips.length;

  // pagination renderer
  const renderPagi = () => {
    if (pageCount <= 1) return null;
    const items = [];
    items.push(<button key="prev" className="pagi__btn" onClick={() => setPage(p => Math.max(1, p - 1))} disabled={page === 1}>‹</button>);
    for (let p = 1; p <= pageCount; p++) {
      if (p === 1 || p === pageCount || Math.abs(p - page) <= 1) {
        items.push(<button key={p} className={"pagi__btn " + (p === page ? "active" : "")} onClick={() => setPage(p)}>{p}</button>);
      } else if (p === 2 || p === pageCount - 1) {
        items.push(<span key={"e" + p} className="pagi__ellipsis">…</span>);
      }
    }
    items.push(<button key="next" className="pagi__btn" onClick={() => setPage(p => Math.min(pageCount, p + 1))} disabled={page === pageCount}>›</button>);
    return <div className="pagi">{items}</div>;
  };

  return (
    <>
      <Nav active="aanbod" />

      <header className="page-head" data-screen-label="Aanbod · Header">
        <div className="container">
          <div className="crumb">
            <a href="index.html">Home</a>
            <span className="crumb__sep">/</span>
            <span className="crumb__current">Aanbod</span>
          </div>
          <div className="page-head__inner">
            <h1 className="page-head__title">
              Het complete <em>aanbod</em>.
            </h1>
            <div className="page-head__meta">
              <div className="page-head__count">
                <small>Voorraad{fromLive ? " · live" : ""}</small>
                {loading ? "…" : INV.length} auto&apos;s
              </div>
            </div>
          </div>
        </div>
      </header>

      <section className="filterbar" data-screen-label="Aanbod · Filters">
        <div className="container">
          <div className="filterbar__row">
            <div className="filterbar__group">
              <div className="search">
                <I.search />
                <input
                  type="text" placeholder="Zoek op merk, model…"
                  value={q} onChange={(e) => setQ(e.target.value)}
                />
              </div>

              <FilterDropdown label="Merk" count={brands.length}>
                <MultiSelect title="Merk" options={allBrands} value={brands} onChange={setBrands} counts={brandCounts} />
              </FilterDropdown>

              <FilterDropdown label="Carrosserie" count={bodies.length}>
                <MultiSelect title="Carrosserie" options={allBodies} value={bodies} onChange={setBodies} />
              </FilterDropdown>

              <FilterDropdown label="Brandstof" count={fuels.length}>
                <MultiSelect title="Brandstof" options={allFuels} value={fuels} onChange={setFuels} />
              </FilterDropdown>

              <FilterDropdown label="Transmissie" count={transmissions.length}>
                <MultiSelect title="Transmissie" options={allTrans} value={transmissions} onChange={setTrans} />
              </FilterDropdown>

              <FilterDropdown label="Prijs" count={priceRange[0] != null || priceRange[1] != null ? 1 : 0}>
                <RangeFilter title="Prijs (€)" min={0} max={100000} value={priceRange} onChange={setPriceRange} unit="" />
              </FilterDropdown>

              <FilterDropdown label="Bouwjaar" count={yearRange[0] != null || yearRange[1] != null ? 1 : 0}>
                <RangeFilter title="Bouwjaar" min={2000} max={2026} value={yearRange} onChange={setYearRange} />
              </FilterDropdown>
            </div>

            <div className="filterbar__actions">
              <SortDropdown
                value={sort}
                onChange={setSort}
                options={[
                  { v: "recent",     label: "Meest recent" },
                  { v: "price-asc",  label: "Prijs ↑" },
                  { v: "price-desc", label: "Prijs ↓" },
                  { v: "year-desc",  label: "Nieuwste jaar" },
                  { v: "km-asc",     label: "Laagste KM" },
                ]}
              />
              <div className="view-toggle" role="tablist">
                <button className={view === "grid" ? "active" : ""} onClick={() => setView("grid")} aria-label="Grid weergave">
                  <I.grid />
                </button>
                <button className={view === "list" ? "active" : ""} onClick={() => setView("list")} aria-label="Lijst weergave">
                  <I.list />
                </button>
              </div>
            </div>
          </div>

          {activeCount > 0 && (
            <div className="active-filters">
              <span className="active-filters__label">{activeCount} filter{activeCount === 1 ? "" : "s"} actief</span>
              {chips.map((c) => (
                <span key={c.k} className="tag">
                  {c.label}
                  <button onClick={c.onRm} aria-label={"Verwijder " + c.label}><I.x /></button>
                </span>
              ))}
              <button className="fbtn" onClick={clearAll}>Wis alles</button>
            </div>
          )}
        </div>
      </section>

      <section className="results">
        <div className="container">
          <div className="results__bar">
            <div className="results__count">
              <strong>{filtered.length}</strong> resultaten {filtered.length !== INV.length && <span>· van {INV.length} totaal</span>}
            </div>
            <div className="results__count">
              Pagina {page} / {pageCount}
            </div>
          </div>

          {filtered.length === 0 ? (
            <div style={{ padding: "80px 0", textAlign: "center", color: "var(--fg-mute)" }}>
              <p style={{ fontFamily: "var(--font-display)", fontSize: 28, color: "var(--fg)", marginBottom: 12 }}>
                Geen auto's gevonden.
              </p>
              <p style={{ fontSize: 14, marginBottom: 24 }}>Probeer minder filters of zoek op een ander merk.</p>
              <button className="fbtn" onClick={clearAll}>Wis alle filters</button>
            </div>
          ) : (
            <div className={"cars " + (view === "list" ? "cars--list" : "")}>
              {pageItems.map((c, i) => {
                const status = carStatus(c);
                const statusClass = status === "sold" ? "car--sold" : status === "reserved" ? "car--reserved" : "";
                const badge =
                  status === "sold"      ? { cls: "badge--sold",     text: "Verkocht" }
                : status === "reserved"  ? { cls: "badge--reserved", text: "Gereserveerd" }
                : status === "expected"  ? { cls: "badge--reserved", text: "Verwacht" }
                : c._abba_tag === "featured" ? { cls: "badge--featured", text: "Uitgelicht" }
                : c._isNew                   ? { cls: "badge--new",      text: "Nieuw binnen", pulse: true }
                : null;

                return (
                  <article className={"car " + statusClass} key={c.voertuignr_hexon}>
                    <CarMedia label={fullModel(c)} car={c} />
                    {badge && (
                      <span className={"badge " + badge.cls + (badge.pulse ? " badge--live" : "")}>
                        {badge.pulse && <span className="car__badge-pulse" aria-hidden="true" />}
                        {badge.text}
                      </span>
                    )}
                    <div className="car__body">
                      <h3 className="car__title">{fullModel(c)}</h3>
                      <div className="car__sub">{fullVariant(c)}</div>
                      <div className="car__specs">
                        <div className="car__spec"><div className="car__spec-label">Bouwjaar</div><div className="car__spec-value">{c.bouwjaar}</div></div>
                        <div className="car__spec"><div className="car__spec-label">KM-stand</div><div className="car__spec-value">{fmtKm(c.tellerstand)}</div></div>
                        <div className="car__spec"><div className="car__spec-label">Brandstof</div><div className="car__spec-value">{fuelLabel(c.brandstof)}</div></div>
                        <div className="car__spec"><div className="car__spec-label">Transmissie</div><div className="car__spec-value">{transmissionLabel(c.transmissie)}</div></div>
                      </div>
                      <div className="car__foot">
                        <div className="car__price"><small>Vanaf</small>{fmtPrice(c.verkoopprijs_particulier)}</div>
                        <a href={`Auto.html?id=${c.voertuignr_hexon}`} className="car__cta">Bekijk <span className="btn__arrow"><I.arrow /></span></a>
                      </div>
                    </div>
                  </article>
                );
              })}
            </div>
          )}

          {renderPagi()}
        </div>
      </section>

      <Footer />
      <FabWa />
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<AanbodPage />);
