/* global React, VEHICLES, BODY_TYPES, FUEL_TYPES, MAKES, fmt$, VehicleCard, Eyebrow, Photo, calcPayment, TOTAL_INVENTORY */
const { useState, useMemo } = React;

function PriceRange({ min, max, value, onChange }) {
  const [a, b] = value;
  const pctA = ((a - min) / (max - min)) * 100;
  const pctB = ((b - min) / (max - min)) * 100;
  return (
    <div>
      <div className="range-track">
        <div className="range-line">
          <div className="range-fill" style={{ left: pctA + '%', right: (100 - pctB) + '%' }}></div>
          <div className="range-thumb" style={{ left: pctA + '%' }}></div>
          <div className="range-thumb" style={{ left: pctB + '%' }}></div>
        </div>
        <input type="range" min={min} max={max} step="500" value={a}
          onChange={e => onChange([+e.target.value, b])}
          style={{ position: 'absolute', width: '100%', opacity: 0, cursor: 'pointer', inset: 0 }} />
        <input type="range" min={min} max={max} step="500" value={b}
          onChange={e => onChange([a, +e.target.value])}
          style={{ position: 'absolute', width: '100%', opacity: 0, cursor: 'pointer', inset: 0 }} />
      </div>
      <div className="range-readout">
        <span>{fmt$(a)}</span><span>{fmt$(b)}</span>
      </div>
    </div>
  );
}

function Filters({ state, setState }) {
  const { search, body, make, price, miles } = state;
  const upd = (k, v) => setState({ ...state, [k]: v });
  return (
    <aside className="filters">
      <div>
        <input className="search-input" placeholder="Search stock, make, model, VIN…" value={search} onChange={e => upd('search', e.target.value)} />
      </div>
      <div className="filter-group">
        <div className="filter-label">Body <span>{body === 'All' ? 'Any' : body}</span></div>
        <div className="filter-chip-row">
          {BODY_TYPES.map(b => (
            <button key={b} className={'fchip' + (body === b ? ' active' : '')} onClick={() => upd('body', b)}>{b}</button>
          ))}
        </div>
      </div>
      <div className="filter-group">
        <div className="filter-label">Price <span>{fmt$(price[0])} – {fmt$(price[1])}</span></div>
        <PriceRange min={5500} max={56000} value={price} onChange={v => upd('price', v)} />
      </div>
      <div className="filter-group">
        <div className="filter-label">Max miles <span>{miles.toLocaleString()} mi</span></div>
        <input type="range" min="50000" max="260000" step="5000" value={miles}
          className="calc-slider"
          onChange={e => upd('miles', +e.target.value)} />
      </div>
      <div className="filter-group">
        <div className="filter-label">Make</div>
        <select className="search-input" style={{ fontSize: 14, fontFamily: 'var(--mono)', padding: '10px 0', letterSpacing: '0.08em', textTransform: 'uppercase' }}
          value={make} onChange={e => upd('make', e.target.value)}>
          {MAKES.map(m => <option key={m} value={m} style={{ background: 'var(--bg)', color: 'var(--fg)' }}>{m}</option>)}
        </select>
      </div>
      <button className="btn btn-sm btn-ghost" style={{ justifyContent: 'space-between' }} onClick={() => setState({
        search: '', body: 'All', fuel: 'All', make: 'All', price: [5500, 56000], miles: 260000, drive: 'All', sort: 'featured',
      })}>
        Reset filters <span>↺</span>
      </button>
    </aside>
  );
}

function Inventory({ openVehicle, favorites, toggleFav }) {
  const [state, setState] = useState({
    search: '', body: 'All', fuel: 'All', make: 'All',
    price: [5500, 56000], miles: 260000, drive: 'All',
    sort: 'featured',
  });
  const [view, setView] = useState('grid');

  const filtered = useMemo(() => {
    let out = VEHICLES.filter(v => {
      if (state.body !== 'All' && v.body !== state.body) return false;
      if (state.make !== 'All' && v.make !== state.make) return false;
      if (v.price < state.price[0] || v.price > state.price[1]) return false;
      if (v.miles > state.miles) return false;
      if (state.search) {
        const q = state.search.toLowerCase();
        if (!`${v.year} ${v.make} ${v.model} ${v.trim} ${v.stock} ${v.vin}`.toLowerCase().includes(q)) return false;
      }
      return true;
    });
    switch (state.sort) {
      case 'price-asc':  out = [...out].sort((a, b) => a.price - b.price); break;
      case 'price-desc': out = [...out].sort((a, b) => b.price - a.price); break;
      case 'miles-asc':  out = [...out].sort((a, b) => a.miles - b.miles); break;
      case 'year-desc':  out = [...out].sort((a, b) => b.year - a.year); break;
      case 'year-asc':   out = [...out].sort((a, b) => a.year - b.year); break;
      default:           out = [...out].sort((a, b) => (b.featured ? 1 : 0) - (a.featured ? 1 : 0));
    }
    return out;
  }, [state]);

  return (
    <div className="container">
      <div style={{ padding: '48px 0 28px', borderBottom: '1px solid var(--line)' }}>
        <Eyebrow num={1}>The lot</Eyebrow>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'end', marginTop: 18, flexWrap: 'wrap', gap: 24 }}>
          <h1 className="display" style={{ fontSize: 'clamp(44px, 6vw, 88px)', lineHeight: 0.93, letterSpacing: '-0.025em' }}>
            {TOTAL_INVENTORY} vehicles.<br/>{VEHICLES.filter(v => v.body === 'Pickup').length} of them <em style={{ color: 'var(--accent)' }}>pickups.</em>
          </h1>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
            <span className="chip chip-sage"><span className="chip-dot"/>Live inventory feed</span>
            <span className="chip">Call to confirm availability</span>
          </div>
        </div>
      </div>

      <div className="inv-layout">
        <Filters state={state} setState={setState} />
        <div>
          <div className="toolbar">
            <div className="toolbar-left">
              <span className="toolbar-count">{filtered.length}</span>
              <span className="toolbar-of">of {VEHICLES.length} matching</span>
            </div>
            <div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
              <select className="mono" style={{
                background: 'var(--bg)',
                border: '1px solid var(--line)',
                borderRadius: 3,
                padding: '9px 12px',
                fontSize: 10.5, letterSpacing: '0.16em', textTransform: 'uppercase',
                color: 'var(--fg)', fontWeight: 500,
              }}
                value={state.sort} onChange={e => setState({ ...state, sort: e.target.value })}>
                <option value="featured">Sort: Featured</option>
                <option value="price-asc">Price · low → high</option>
                <option value="price-desc">Price · high → low</option>
                <option value="miles-asc">Mileage · low → high</option>
                <option value="year-desc">Year · newest</option>
                <option value="year-asc">Year · oldest</option>
              </select>
              <div className="view-toggle">
                <button className={view === 'grid' ? 'active' : ''} onClick={() => setView('grid')}>Grid</button>
                <button className={view === 'list' ? 'active' : ''} onClick={() => setView('list')}>List</button>
              </div>
            </div>
          </div>

          {view === 'grid' ? (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(290px, 1fr))', gap: 24 }}>
              {filtered.map(v => (
                <VehicleCard key={v.id} v={v} onClick={openVehicle} favorite={favorites.has(v.id)} onFav={toggleFav} />
              ))}
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              {filtered.map(v => (
                <a key={v.id} className="inv-row" onClick={() => openVehicle(v)}>
                  <Photo label={v.stock} hue={v.hue} photo={v.photo} aspect="5/4" style={{ borderRadius: 4 }} />
                  <div>
                    <div className="mono" style={{ fontSize: 10.5, letterSpacing: '0.18em', color: 'var(--fg-dim)', textTransform: 'uppercase', fontWeight: 500 }}>
                      {v.year} · {v.body} · Stock {v.stock}
                    </div>
                    <div style={{ fontFamily: 'var(--display)', fontSize: 26, marginTop: 6, letterSpacing: '-0.015em', lineHeight: 1.05 }}>
                      {v.make} {v.model}
                      <span style={{ color: 'var(--fg-mute)', fontStyle: 'italic', marginLeft: 8 }}>{v.trim}</span>
                    </div>
                    <div style={{ display: 'flex', gap: 14, marginTop: 8, fontFamily: 'var(--mono)', fontSize: 10.5, color: 'var(--fg-mute)', letterSpacing: '0.04em', flexWrap: 'wrap' }}>
                      <span>{v.miles.toLocaleString()} mi</span>
                      <span>·</span>
                      <span>VIN {v.vin}</span>
                    </div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontFamily: 'var(--display)', fontSize: 30, letterSpacing: '-0.02em' }}>{fmt$(v.price)}</div>
                    <div className="mono" style={{ fontSize: 10.5, color: 'var(--fg-dim)', letterSpacing: '0.14em', fontWeight: 500, marginTop: 2 }}>
                      Estimate available after approval
                    </div>
                  </div>
                  <button className="btn btn-sm">View <span className="btn-arrow">→</span></button>
                </a>
              ))}
            </div>
          )}

          {filtered.length === 0 && (
            <div style={{ padding: 80, textAlign: 'center', border: '1px solid var(--line)', borderRadius: 6 }}>
              <Eyebrow>No matches</Eyebrow>
              <h3 className="display" style={{ fontSize: 40, marginTop: 18, letterSpacing: '-0.02em' }}>Nothing fits those filters.</h3>
              <p className="mute" style={{ marginTop: 14 }}>Widen the price or the mileage. Or just call the lot — (540) 450-5373 — and tell him what you&apos;re after.</p>
              <button className="btn btn-primary" style={{ marginTop: 22 }} onClick={() => setState({
                search: '', body: 'All', fuel: 'All', make: 'All', price: [5500, 56000], miles: 260000, drive: 'All', sort: 'featured',
              })}>Reset filters <span className="btn-arrow">→</span></button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

window.Inventory = Inventory;
