// Alba Cars — Inventory page (Buy)
const { useState: useStateI, useMemo: useMemoI } = React;

function InventoryPage({ setRoute, setVehicleId }) {
  const [brand, setBrand] = useStateI('All');
  const [body, setBody] = useStateI('All');
  const [yearMin, setYearMin] = useStateI(2020);
  const [priceMax, setPriceMax] = useStateI(1500000);
  const [sort, setSort] = useStateI('newest');
  const [includesPOA, setIncludesPOA] = useStateI(true);
  const [query, setQuery] = useStateI('');
  const [view, setView] = useStateI('grid');

  const filtered = useMemoI(() => {
    let out = VEHICLES.filter(v => {
      if (brand !== 'All' && v.make !== brand) return false;
      if (body !== 'All' && v.body !== body) return false;
      if (v.year < yearMin) return false;
      if (v.price != null && v.price > priceMax) return false;
      if (v.price == null && !includesPOA) return false;
      if (query && !`${v.make} ${v.model} ${v.variant}`.toLowerCase().includes(query.toLowerCase())) return false;
      return true;
    });
    out.sort((a, b) => {
      if (sort === 'newest') return b.year - a.year;
      if (sort === 'oldest') return a.year - b.year;
      if (sort === 'price-low') return (a.price ?? 9e9) - (b.price ?? 9e9);
      if (sort === 'price-high') return (b.price ?? 0) - (a.price ?? 0);
      if (sort === 'mileage') return a.mileage - b.mileage;
      return 0;
    });
    return out;
  }, [brand, body, yearMin, priceMax, sort, includesPOA, query]);

  return (
    <div style={{ paddingTop: 88, minHeight: '100vh' }}>
      {/* Header strip */}
      <div style={{ padding: '50px 0 36px', borderBottom: '1px solid var(--border)', background: 'var(--surface-2)' }}>
        <div className="container-wide">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 24, flexWrap: 'wrap' }}>
            <div>
              <Pill live>Live · 212 cars in stock</Pill>
              <h1 className="display" style={{ fontSize: 'clamp(40px, 6vw, 88px)', marginTop: 18, letterSpacing: '-0.045em' }}>
                Inventory <span style={{ color: 'var(--text-muted)', fontWeight: 400 }}>— {filtered.length} of {VEHICLES.length} shown</span>
              </h1>
              <p style={{ marginTop: 14, fontSize: 15, color: 'var(--text-muted)', maxWidth: 600 }}>
                Demo prices for illustration. Live build pulls real prices and full image sets from the inventory feed.
              </p>
            </div>
            <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
              <button onClick={() => setView('grid')} style={viewBtn(view === 'grid')}>Grid</button>
              <button onClick={() => setView('list')} style={viewBtn(view === 'list')}>List</button>
            </div>
          </div>
        </div>
      </div>

      <div className="container-wide" style={{ padding: '36px 32px 100px', display: 'grid', gridTemplateColumns: window.innerWidth > 1100 ? '280px 1fr' : '1fr', gap: 40 }}>
        {/* Filter sidebar */}
        <aside style={{ position: window.innerWidth > 1100 ? 'sticky' : 'static', top: 110, alignSelf: 'start' }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 28 }}>
            <div>
              <div style={{ position: 'relative' }}>
                <Icon name="search" size={15} />
                <input type="text" placeholder="Search make, model…" value={query} onChange={e => setQuery(e.target.value)}
                  className="input" style={{ paddingLeft: 40 }} />
                <div style={{ position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-muted)', pointerEvents: 'none' }}>
                  <Icon name="search" size={15} />
                </div>
              </div>
            </div>

            <FilterGroup label="Brand">
              <FilterChips options={['All', ...BRANDS]} value={brand} onChange={setBrand} />
            </FilterGroup>

            <FilterGroup label="Body type">
              <FilterChips options={['All', ...BODY_TYPES]} value={body} onChange={setBody} />
            </FilterGroup>

            <FilterGroup label="Year from">
              <SliderField min={2018} max={2024} step={1} value={yearMin} onChange={setYearMin} display={`${yearMin}+`} />
            </FilterGroup>

            <FilterGroup label="Max price (AED)">
              <SliderField min={100000} max={1500000} step={50000} value={priceMax} onChange={setPriceMax} display={priceMax >= 1500000 ? 'No cap' : fmtAED(priceMax)} />
              <label style={{ display: 'flex', gap: 10, alignItems: 'center', marginTop: 12, fontSize: 13, color: 'var(--text-muted)', cursor: 'pointer' }}>
                <input type="checkbox" checked={includesPOA} onChange={e => setIncludesPOA(e.target.checked)} /> Include POA cars
              </label>
            </FilterGroup>

            <FilterGroup label="Sort by">
              <select className="select" value={sort} onChange={e => setSort(e.target.value)}>
                <option value="newest">Newest year</option>
                <option value="oldest">Oldest year</option>
                <option value="price-low">Price · low to high</option>
                <option value="price-high">Price · high to low</option>
                <option value="mileage">Lowest mileage</option>
              </select>
            </FilterGroup>

            <button onClick={() => { setBrand('All'); setBody('All'); setYearMin(2018); setPriceMax(1500000); setQuery(''); }}
              style={{ background: 'none', border: 'none', fontFamily: 'var(--f-display)', fontSize: 12, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--accent)', cursor: 'pointer', textAlign: 'left' }}>
              Reset filters →
            </button>
          </div>
        </aside>

        {/* Results */}
        <div>
          {filtered.length === 0 ? (
            <div style={{ padding: 80, textAlign: 'center', border: '1px dashed var(--border)', borderRadius: 12 }}>
              <h3 className="display" style={{ fontSize: 24 }}>No cars match those filters.</h3>
              <p style={{ marginTop: 10, color: 'var(--text-muted)' }}>Try widening the price or year range.</p>
            </div>
          ) : view === 'grid' ? (
            <div style={{
              display: 'grid',
              gridTemplateColumns: window.innerWidth > 1400 ? 'repeat(3, 1fr)' : window.innerWidth > 700 ? 'repeat(2, 1fr)' : '1fr',
              gap: 22,
            }}>
              {filtered.map(v => (
                <VehicleCard key={v.id} v={v} onClick={() => { setVehicleId(v.id); setRoute('vehicle'); window.scrollTo({top:0}); }} />
              ))}
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              {filtered.map(v => (
                <VehicleRow key={v.id} v={v} onClick={() => { setVehicleId(v.id); setRoute('vehicle'); window.scrollTo({top:0}); }} />
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function viewBtn(active) {
  return {
    padding: '8px 16px', borderRadius: 999,
    border: '1px solid var(--border)',
    background: active ? 'var(--ink)' : 'transparent',
    color: active ? '#fff' : 'var(--text)',
    fontFamily: 'var(--f-display)', fontSize: 12, fontWeight: 500,
    letterSpacing: '0.06em', textTransform: 'uppercase',
    cursor: 'pointer',
  };
}

function FilterGroup({ label, children }) {
  return (
    <div>
      <div className="label">{label}</div>
      {children}
    </div>
  );
}

function FilterChips({ options, value, onChange }) {
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
      {options.map(opt => (
        <button key={opt} onClick={() => onChange(opt)} style={{
          padding: '7px 12px', borderRadius: 999,
          border: '1px solid ' + (value === opt ? 'var(--text)' : 'var(--border)'),
          background: value === opt ? 'var(--text)' : 'transparent',
          color: value === opt ? 'var(--bg)' : 'var(--text)',
          fontFamily: 'var(--f-display)', fontSize: 12, fontWeight: 500,
          cursor: 'pointer', transition: 'all 0.15s',
        }}>{opt}</button>
      ))}
    </div>
  );
}

function SliderField({ min, max, step, value, onChange, display }) {
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, marginBottom: 8 }}>
        <span className="mono">{display}</span>
      </div>
      <input type="range" min={min} max={max} step={step} value={value} onChange={e => onChange(+e.target.value)} style={{
        width: '100%', appearance: 'none', height: 4, borderRadius: 2,
        background: `linear-gradient(to right, var(--alba-red) 0%, var(--alba-red) ${((value-min)/(max-min))*100}%, var(--border) ${((value-min)/(max-min))*100}%, var(--border) 100%)`,
      }} />
    </div>
  );
}

function VehicleRow({ v, onClick }) {
  const isPOA = v.price == null;
  return (
    <article onClick={onClick} style={{
      display: 'grid',
      gridTemplateColumns: window.innerWidth > 800 ? '320px 1fr auto' : '1fr',
      gap: 24, padding: 20, alignItems: 'center',
      background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 12,
      cursor: 'pointer', transition: 'all 0.2s',
    }}
    onMouseEnter={(e) => e.currentTarget.style.borderColor = 'var(--text)'}
    onMouseLeave={(e) => e.currentTarget.style.borderColor = 'var(--border)'}
    >
      <div style={{ aspectRatio: '4/3', borderRadius: 8, overflow: 'hidden', background: 'var(--surface-2)' }}>
        <img src={v.photo} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
      </div>
      <div>
        <div style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--text-muted)', fontFamily: 'var(--f-display)' }}>
          {v.year} · {v.make} · <span className="mono">{v.stockId}</span>
        </div>
        <h3 className="display" style={{ fontSize: 26, marginTop: 6, letterSpacing: '-0.02em' }}>
          {v.model} <span style={{ color: 'var(--text-muted)', fontWeight: 400 }}>{v.variant}</span>
        </h3>
        <div style={{ display: 'flex', gap: 22, marginTop: 14, flexWrap: 'wrap' }}>
          {[
            ['Mileage', fmtMileage(v.mileage)],
            ['Engine', v.engine],
            ['Trans', v.trans],
            ['Drive', v.drive],
            ['Body', v.body],
          ].map(([k, val]) => (
            <div key={k} style={{ fontSize: 12 }}>
              <div style={{ color: 'var(--text-muted)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>{k}</div>
              <div className="mono" style={{ marginTop: 2 }}>{val}</div>
            </div>
          ))}
        </div>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div style={{ fontSize: 10, color: 'var(--text-muted)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>
          {isPOA ? 'Inquire' : 'Demo price'}
        </div>
        <div className="mono" style={{ fontSize: 22, fontWeight: 600, marginTop: 4 }}>
          {fmtAED(v.price)}
        </div>
        <Btn variant="primary" icon="arrow-right" style={{ marginTop: 14 }}>View</Btn>
      </div>
    </article>
  );
}

Object.assign(window, { InventoryPage });
