// MRB Auto storefront — Catalog / category listing page (mobile-first)
const _mkC = (n) => (props) => { const C = window.MRBAutoDesignSystem_73c751 && window.MRBAutoDesignSystem_73c751[n]; return C ? React.createElement(C, props) : null; };
const Icon = _mkC('Icon'), Button = _mkC('Button'), IconButton = _mkC('IconButton'), Badge = _mkC('Badge'),
  ProductCard = _mkC('ProductCard'), Select = _mkC('Select'), TrustItem = _mkC('TrustItem'), Rating = _mkC('Rating');

const CAT_PRODUCTS = [
  { vehicle: 'Mercedes GLC X253', title: 'Marche-pieds alu GLC X253 & Coupé C253 (2015-2022)', price: 249, oldPrice: 319, badge: { label: 'Top vente', variant: 'top' }, monthly: '62 €/mois', cat: 'Marche-pieds', rating: 4.9 },
  { vehicle: 'Mercedes Classe E W213', title: 'Calandre look Panamericana AMG GT — W213', price: 149, badge: { label: 'Top vente', variant: 'top' }, monthly: '37 €/mois', cat: 'Calandres', rating: 4.8 },
  { vehicle: 'BMW X5 E70', title: "Kit extensions d'ailes BMW X5 E70 & LCI", price: 299, oldPrice: 379, badge: { label: 'Top vente', variant: 'top' }, monthly: '75 €/mois', cat: "Extensions d'ailes", rating: 4.7 },
  { vehicle: 'Audi A6 C8', title: 'Calandre Audi A6 C8 look RS', price: 199, badge: { label: 'Nouveau', variant: 'new' }, monthly: '50 €/mois', cat: 'Calandres', rating: 4.6 },
  { vehicle: 'Mercedes ML W164', title: 'Marche-pieds latéraux Mercedes ML W164', price: 299, oldPrice: 369, monthly: '75 €/mois', cat: 'Marche-pieds', rating: 4.8 },
  { vehicle: 'Land Rover Defender', title: 'Échelle latérale noir brillant Defender 90/110 2019+', price: 499, badge: { label: 'Nouveau', variant: 'new' }, monthly: '125 €/mois', cat: 'Marche-pieds', rating: 5 },
  { vehicle: 'Porsche Cayenne Coupé', title: 'Marche-pieds aluminium Cayenne Coupé 2018+', price: 699, monthly: '175 €/mois', cat: 'Marche-pieds', rating: 4.9 },
  { vehicle: 'Mercedes Classe A W176', title: 'Pare-chocs avant sport look A45 AMG (2012-2015)', price: 749, badge: { label: 'Nouveau', variant: 'new' }, monthly: '187 €/mois', cat: 'Pare-chocs & kits', rating: 4.7 },
  { vehicle: 'BMW Série 3 G20', title: 'Jantes 19" style M double-branche (jeu de 4)', price: 899, oldPrice: 1090, badge: { label: 'Promo', variant: 'sale' }, monthly: '225 €/mois', cat: 'Jantes', rating: 4.8, stock: 3 },
  { vehicle: 'VW Golf 7', title: 'Embouts d\'échappement inox look R (paire)', price: 89, monthly: '22 €/mois', cat: 'Échappement & déco', rating: 4.5 },
  { vehicle: 'Audi Q5 FY', title: 'Coques de rétroviseurs carbone Q5 FY', price: 159, oldPrice: 199, badge: { label: 'Promo', variant: 'sale' }, monthly: '40 €/mois', cat: 'Échappement & déco', rating: 4.6 },
  { vehicle: 'Mercedes GLE W167', title: 'Kit tapis + coffre sur-mesure GLE W167', price: 129, monthly: '32 €/mois', cat: 'Tapis & intérieur', rating: 4.9 },
];

const FILTER_CATS = ['Marche-pieds', 'Calandres', 'Pare-chocs & kits', "Extensions d'ailes", 'Jantes', 'Éclairage LED', 'Tapis & intérieur', 'Échappement & déco'];
const FILTER_BRANDS = ['Mercedes', 'BMW', 'Audi', 'Land Rover', 'Porsche', 'Volkswagen'];

function FilterCheck({ label, count, checked, onChange }) {
  return (
    <label style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '7px 0', cursor: 'pointer' }}>
      <span style={{ width: 20, height: 20, flexShrink: 0, borderRadius: 5, border: `1px solid ${checked ? 'var(--accent)' : 'var(--border-strong)'}`, background: checked ? 'var(--accent)' : 'var(--surface-card)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        {checked && <Icon name="check" size={13} color="var(--white)" />}
      </span>
      <input type="checkbox" checked={checked} onChange={onChange} style={{ position: 'absolute', opacity: 0, width: 0, height: 0 }} />
      <span style={{ flex: 1, fontFamily: 'var(--font-sans)', fontSize: '14px', color: 'var(--text-primary)' }}>{label}</span>
      {count != null && <span style={{ fontFamily: 'var(--font-mono)', fontSize: '12px', color: 'var(--text-muted)' }}>{count}</span>}
    </label>
  );
}

function FilterGroup({ title, children, defaultOpen = true }) {
  const [open, setOpen] = React.useState(defaultOpen);
  return (
    <div style={{ borderBottom: '1px solid var(--border-default)', padding: '16px 0' }}>
      <button type="button" onClick={() => setOpen((o) => !o)} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%', background: 'transparent', border: 'none', cursor: 'pointer', padding: 0 }}>
        <span style={{ fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: '13px', letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--text-primary)' }}>{title}</span>
        <Icon name="chevronDown" size={16} color="var(--text-muted)" style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform var(--dur-base)' }} />
      </button>
      {open && <div style={{ marginTop: 10 }}>{children}</div>}
    </div>
  );
}

function Filters({ state, setState }) {
  const toggle = (key, val) => setState((s) => {
    const set = new Set(s[key]);
    set.has(val) ? set.delete(val) : set.add(val);
    return { ...s, [key]: set };
  });
  const countByCat = (c) => CAT_PRODUCTS.filter((p) => p.cat === c).length;
  const countByBrand = (b) => CAT_PRODUCTS.filter((p) => p.vehicle.startsWith(b)).length;

  return (
    <div>
      <FilterGroup title="Catégorie">
        {FILTER_CATS.map((c) => <FilterCheck key={c} label={c} count={countByCat(c)} checked={state.cat.has(c)} onChange={() => toggle('cat', c)} />)}
      </FilterGroup>
      <FilterGroup title="Marque">
        {FILTER_BRANDS.map((b) => <FilterCheck key={b} label={b} count={countByBrand(b)} checked={state.brand.has(b)} onChange={() => toggle('brand', b)} />)}
      </FilterGroup>
      <FilterGroup title="Prix">
        {['< 150 €', '150 – 300 €', '300 – 600 €', '> 600 €'].map((p) => <FilterCheck key={p} label={p} checked={state.price.has(p)} onChange={() => toggle('price', p)} />)}
      </FilterGroup>
      <FilterGroup title="Disponibilité" defaultOpen={false}>
        <FilterCheck label="En stock" checked={state.avail.has('stock')} onChange={() => toggle('avail', 'stock')} />
        <FilterCheck label="En promotion" checked={state.avail.has('promo')} onChange={() => toggle('avail', 'promo')} />
      </FilterGroup>
    </div>
  );
}

function Breadcrumb({ items }) {
  return (
    <nav style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', fontFamily: 'var(--font-sans)', fontSize: '13px', color: 'var(--text-muted)', padding: '14px 0' }}>
      {items.map((it, i) => (
        <React.Fragment key={it}>
          {i > 0 && <Icon name="chevronRight" size={13} color="var(--ink-300)" />}
          <a href={it === 'Accueil' ? 'index.html' : (it.indexOf('Marche') === 0 ? 'catalog.html' : '#')} style={{ color: i === items.length - 1 ? 'var(--text-primary)' : 'var(--text-muted)', fontWeight: i === items.length - 1 ? 600 : 400 }}>{it}</a>
        </React.Fragment>
      ))}
    </nav>
  );
}

function Catalog() {
  const [cart, setCart] = React.useState(2);
  const [drawer, setDrawer] = React.useState(false);
  const [sort, setSort] = React.useState('pop');
  const [state, setState] = React.useState({ cat: new Set(['Marche-pieds']), brand: new Set(), price: new Set(), avail: new Set() });

  React.useEffect(() => { document.body.style.overflow = drawer ? 'hidden' : ''; return () => { document.body.style.overflow = ''; }; }, [drawer]);

  // filtering
  let items = CAT_PRODUCTS.filter((p) => {
    if (state.cat.size && !state.cat.has(p.cat)) return false;
    if (state.brand.size && ![...state.brand].some((b) => p.vehicle.startsWith(b))) return false;
    if (state.avail.has('promo') && !p.oldPrice) return false;
    if (state.price.size) {
      const inRange = [...state.price].some((r) =>
        (r === '< 150 €' && p.price < 150) || (r === '150 – 300 €' && p.price >= 150 && p.price < 300) ||
        (r === '300 – 600 €' && p.price >= 300 && p.price < 600) || (r === '> 600 €' && p.price >= 600));
      if (!inRange) return false;
    }
    return true;
  });
  if (sort === 'asc') items = [...items].sort((a, b) => a.price - b.price);
  if (sort === 'desc') items = [...items].sort((a, b) => b.price - a.price);
  if (sort === 'rating') items = [...items].sort((a, b) => (b.rating || 0) - (a.rating || 0));

  const activeCount = state.cat.size + state.brand.size + state.price.size + state.avail.size;

  return (
    <React.Fragment>
      <window.MRBHeader cartCount={cart} onSearch={() => {}} active="Catégories" />

      <div className="kit-wrap">
        <Breadcrumb items={['Accueil', 'Mercedes', 'Marche-pieds']} />
      </div>

      {/* Page hero */}
      <div style={{ background: 'var(--surface-alt)', borderTop: '1px solid var(--border-subtle)', borderBottom: '1px solid var(--border-default)' }}>
        <div className="kit-wrap" style={{ padding: '24px 16px' }}>
          <span style={{ fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: '12px', letterSpacing: 'var(--ls-caps)', textTransform: 'uppercase', color: 'var(--text-accent)' }}>Relooking & carrosserie</span>
          <h1 className="h-page" style={{ margin: '8px 0 0', fontFamily: 'var(--font-display)', fontWeight: 800, textTransform: 'uppercase', letterSpacing: 'var(--ls-display)', lineHeight: 0.95, color: 'var(--text-primary)' }}>Marche-pieds & seuils</h1>
          <p style={{ margin: '10px 0 0', maxWidth: 620, fontFamily: 'var(--font-sans)', fontSize: '14.5px', lineHeight: 1.55, color: 'var(--text-secondary)' }}>
            Marche-pieds aluminium et échelles latérales, montés sur les points d'origine — sans perçage. Sélectionnez votre véhicule pour n'afficher que les modèles compatibles.
          </p>
        </div>
      </div>

      {/* Toolbar */}
      <div style={{ position: 'sticky', top: 60, zIndex: 30, background: 'var(--surface-page)', borderBottom: '1px solid var(--border-default)' }}>
        <div className="kit-wrap" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '10px 16px' }}>
          <span style={{ fontFamily: 'var(--font-sans)', fontSize: '13px', color: 'var(--text-secondary)' }}>
            <strong style={{ color: 'var(--text-primary)', fontWeight: 700 }}>{items.length}</strong> résultat{items.length > 1 ? 's' : ''}
          </span>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <button type="button" className="only-mobile" onClick={() => setDrawer(true)}
              style={{ display: 'flex', alignItems: 'center', gap: 7, height: 40, padding: '0 16px', borderRadius: 'var(--radius-pill)', border: '1px solid var(--border-strong)', background: 'var(--surface-card)', cursor: 'pointer', fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: '13px', color: 'var(--text-primary)' }}>
              <Icon name="compare" size={16} /> Filtres{activeCount > 0 ? ` (${activeCount})` : ''}
            </button>
            <div style={{ minWidth: 180 }}>
              <Select value={sort} onChange={(e) => setSort(e.target.value)} placeholder="Trier"
                options={[{ value: 'pop', label: 'Popularité' }, { value: 'asc', label: 'Prix croissant' }, { value: 'desc', label: 'Prix décroissant' }, { value: 'rating', label: 'Les mieux notés' }]} />
            </div>
          </div>
        </div>
      </div>

      {/* Layout */}
      <div className="kit-wrap" style={{ padding: '24px 16px 64px' }}>
        <div className="catalog-layout">
          <aside className="catalog-sidebar">
            <Filters state={state} setState={setState} />
          </aside>

          <div>
            {items.length === 0 ? (
              <div style={{ padding: '64px 24px', textAlign: 'center', background: 'var(--surface-alt)', borderRadius: 'var(--radius-card)' }}>
                <Icon name="search" size={40} color="var(--ink-300)" style={{ margin: '0 auto 14px' }} />
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, textTransform: 'uppercase', fontSize: '1.4rem', color: 'var(--text-primary)' }}>Aucun produit</div>
                <p style={{ fontFamily: 'var(--font-sans)', fontSize: '14px', color: 'var(--text-muted)' }}>Élargissez vos filtres pour voir plus de résultats.</p>
                <Button variant="secondary" onClick={() => setState({ cat: new Set(), brand: new Set(), price: new Set(), avail: new Set() })}>Réinitialiser les filtres</Button>
              </div>
            ) : (
              <>
                <div className="prod-grid">
                  {items.map((p) => (
                    <a key={p.title} href="product.html" style={{ display: 'block' }}>
                      <ProductCard {...p} onAdd={() => setCart((c) => c + 1)} />
                    </a>
                  ))}
                </div>
                <div style={{ display: 'flex', justifyContent: 'center', marginTop: 40 }}>
                  <Button variant="secondary" size="lg" iconRight="chevronDown">Voir plus de produits</Button>
                </div>
              </>
            )}
          </div>
        </div>
      </div>

      {/* Mobile filter drawer */}
      <div className="drawer-backdrop" data-open={drawer ? 'true' : 'false'} onClick={() => setDrawer(false)} />
      <aside className="drawer-panel drawer-panel--right" data-open={drawer ? 'true' : 'false'}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px', borderBottom: '1px solid var(--border-default)', position: 'sticky', top: 0, background: 'var(--surface-page)', zIndex: 2 }}>
          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 800, textTransform: 'uppercase', fontSize: '1.2rem' }}>Filtres</span>
          <IconButton icon="x" label="Fermer" onClick={() => setDrawer(false)} />
        </div>
        <div style={{ padding: '0 16px' }}><Filters state={state} setState={setState} /></div>
        <div style={{ position: 'sticky', bottom: 0, background: 'var(--surface-page)', borderTop: '1px solid var(--border-default)', padding: '12px 16px', display: 'flex', gap: 10 }}>
          <Button variant="ghost" onClick={() => setState({ cat: new Set(), brand: new Set(), price: new Set(), avail: new Set() })}>Effacer</Button>
          <Button variant="accent" fullWidth onClick={() => setDrawer(false)}>Voir {items.length} résultats</Button>
        </div>
      </aside>

      <window.MRBFooter />
    </React.Fragment>
  );
}

// mount
(function mount() {
  const ns = window.MRBAutoDesignSystem_73c751;
  if (!ns || typeof ns.Icon !== 'function' || !window.MRBHeader || !window.MRBFooter) return setTimeout(mount, 30);
  const el = document.getElementById('page-root');
  if (!el || el.__mounted) return;
  el.__mounted = true;
  ReactDOM.createRoot(el).render(<Catalog />);
})();
