// CATÁLOGO con filtros laterales
// embedded=true → se usa dentro del home (sin su propio hero, el home ya tiene uno)
const CatalogScreen = ({ initialSearch, onSelectVehicle, embedded }) => {
  const { vehicles, marcas, carrocerias, combustibles, transmisiones } = window.OMEGA_DATA;
  const { fmtPrice } = window.OMEGA_HELPERS;

  const [filters, setFilters] = useState({
    marca: initialSearch?.marca || 'Todas',
    modelo: 'Todos',
    version: 'Todas',
    carroceria: initialSearch?.carroceria || 'Todas',
    combustible: 'Todos',
    transmision: 'Todas',
    precioMin: 0,
    precioMax: initialSearch?.precioMax || 70000000,
    anioMin: 1980,
    anioMax: 2026,
    kmMax: 300000,
    soloConFotos: false,
    soloDestacados: false,
    q: ''
  });
  const [verMasMarcas, setVerMasMarcas] = useState(false);
  const { fmtKm } = window.OMEGA_HELPERS;
  const [sort, setSort] = useState('relevancia');
  // En mobile arrancan colapsados para que las cards se vean primero
  const [showFilters, setShowFilters] = useState(typeof window !== 'undefined' ? window.innerWidth > 860 : true);

  const filtered = useMemo(() => {
    let out = vehicles.filter(v => {
      if (filters.marca !== 'Todas' && v.marca !== filters.marca) return false;
      if (filters.modelo !== 'Todos' && ((v.modelo||'').trim().split(/\s+/)[0].toUpperCase()) !== filters.modelo) return false;
      if (filters.version !== 'Todas' && v.modelo !== filters.version) return false;
      if (filters.carroceria !== 'Todas' && v.carroceria !== filters.carroceria) return false;
      if (filters.combustible !== 'Todos' && v.combustible !== filters.combustible) return false;
      if (filters.transmision !== 'Todas' && v.transmision !== filters.transmision) return false;
      if (v.precio < filters.precioMin || v.precio > filters.precioMax) return false;
      if (v.anio && (v.anio < filters.anioMin || v.anio > filters.anioMax)) return false;
      if (filters.kmMax < 300000 && (v.km || 0) > filters.kmMax) return false;
      if (filters.soloConFotos && !(v.photos && v.photos.length > 0)) return false;
      if (filters.soloDestacados && !v.tag) return false;
      if (filters.q && !(`${v.marca} ${v.modelo} ${v.carroceria}`.toLowerCase().includes(filters.q.toLowerCase()))) return false;
      return true;
    });
    if (sort === 'precio-asc') out.sort((a,b)=>a.precio-b.precio);
    else if (sort === 'precio-desc') out.sort((a,b)=>b.precio-a.precio);
    else if (sort === 'anio-desc') out.sort((a,b)=>b.anio-a.anio);
    else if (sort === 'km-asc') out.sort((a,b)=>a.km-b.km);
    return out;
  }, [vehicles, filters, sort]);

  // ── Híbrido deRuedas: desplegables + acordeón (mobile) ──
  const marcaCount = useMemo(() => {
    const c = {}; vehicles.forEach(v => { c[v.marca] = (c[v.marca]||0)+1; }); return c;
  }, [vehicles]);
  const carroCount = useMemo(() => {
    const c = {}; vehicles.forEach(v => { if(v.carroceria) c[v.carroceria] = (c[v.carroceria]||0)+1; }); return c;
  }, [vehicles]);
  const combCount = useMemo(() => {
    const c = {}; vehicles.forEach(v => { if(v.combustible) c[v.combustible] = (c[v.combustible]||0)+1; }); return c;
  }, [vehicles]);
  const transCount = useMemo(() => {
    const c = {}; vehicles.forEach(v => { if(v.transmision) c[v.transmision] = (c[v.transmision]||0)+1; }); return c;
  }, [vehicles]);
  const baseModelo = (m) => (m||'').trim().split(/\s+/)[0].toUpperCase();
  // Modelos disponibles para la marca elegida (cascada, con conteo)
  const modelosOpts = useMemo(() => {
    const c = {};
    vehicles.filter(v => filters.marca==='Todas' || v.marca===filters.marca)
            .forEach(v => { const b = baseModelo(v.modelo); if (b) c[b] = (c[b]||0)+1; });
    return Object.keys(c).sort().map(k => ({ value:k, label:`${k} (${c[k]})` }));
  }, [vehicles, filters.marca]);
  // Versiones disponibles para marca+modelo (cascada, con conteo)
  const versionOpts = useMemo(() => {
    if (filters.modelo==='Todos') return [];
    const c = {};
    vehicles.filter(v => (filters.marca==='Todas' || v.marca===filters.marca) && baseModelo(v.modelo)===filters.modelo)
            .forEach(v => { c[v.modelo] = (c[v.modelo]||0)+1; });
    return Object.keys(c).sort().map(k => {
      const ver = k.replace(new RegExp('^'+filters.modelo+'\\s*','i'),'').trim() || k;
      return { value:k, label:`${ver} (${c[k]})` };
    });
  }, [vehicles, filters.marca, filters.modelo]);
  const setMarca = (m) => setFilters(f => ({...f, marca:m, modelo:'Todos', version:'Todas'}));
  const setModelo = (m) => setFilters(f => ({...f, modelo:m, version:'Todas'}));
  const money = (n) => n >= 1000000 ? `$${(n/1000000).toLocaleString('es-AR',{maximumFractionDigits:1})}M` : `$${Math.round(n/1000)}k`;
  const PRECIO_STEPS = [0,5,10,15,20,25,30,40,50,60,70].map(n=>n*1000000);
  const ANIOS = []; for (let y=2026; y>=1980; y--) ANIOS.push(y);
  const KM_STEPS = [50000,100000,150000,200000,250000];
  const [openSec, setOpenSec] = useState({ marca:true });
  const toggleSec = (k)=> setOpenSec(s=>({...s,[k]:!s[k]}));
  const AccBlock = ({id,label,value,children}) => (
    <div className={`acc ${openSec[id]?'acc-open':''}`}>
      <button type="button" className="acc-h" onClick={()=>toggleSec(id)}>
        <span className="acc-l">{label}</span>
        <span className="acc-r">{value ? <span className="acc-v">{value}</span> : null}<span className="chev">⌄</span></span>
      </button>
      <div className="acc-b">{children}</div>
    </div>
  );
  const kmLabel = filters.kmMax >= 300000 ? '' : `Hasta ${fmtKm(filters.kmMax)}`;
  const precioLabel = (filters.precioMin>0 || filters.precioMax<70000000)
    ? `${filters.precioMin>0?money(filters.precioMin):'$0'} – ${filters.precioMax<70000000?money(filters.precioMax):'$70M+'}` : '';
  const anioLabel = (filters.anioMin>1980 || filters.anioMax<2026) ? `${filters.anioMin}–${filters.anioMax}` : '';

  const reset = () => setFilters({ marca:'Todas', modelo:'Todos', version:'Todas', carroceria:'Todas', combustible:'Todos', transmision:'Todas', precioMin:0, precioMax:70000000, anioMin:1980, anioMax:2026, kmMax:300000, soloConFotos:false, soloDestacados:false, q:'' });
  const set1 = (patch) => setFilters(f => ({...f, ...patch}));
  // Chips de filtros activos (removibles)
  const activeChips = [];
  if (filters.q) activeChips.push({ k:'q', label:`"${filters.q}"`, clear:()=>set1({q:''}) });
  if (filters.marca!=='Todas') activeChips.push({ k:'marca', label:filters.marca, clear:()=>setMarca('Todas') });
  if (filters.modelo!=='Todos') activeChips.push({ k:'modelo', label:filters.modelo, clear:()=>setModelo('Todos') });
  if (filters.version!=='Todas') activeChips.push({ k:'version', label:filters.version.replace(new RegExp('^'+filters.modelo+'\\s*','i'),'').trim()||filters.version, clear:()=>set1({version:'Todas'}) });
  if (precioLabel) activeChips.push({ k:'precio', label:precioLabel, clear:()=>set1({precioMin:0,precioMax:70000000}) });
  if (anioLabel) activeChips.push({ k:'anio', label:anioLabel, clear:()=>set1({anioMin:1980,anioMax:2026}) });
  if (kmLabel) activeChips.push({ k:'km', label:kmLabel, clear:()=>set1({kmMax:300000}) });
  if (filters.carroceria!=='Todas') activeChips.push({ k:'carro', label:filters.carroceria, clear:()=>set1({carroceria:'Todas'}) });
  if (filters.combustible!=='Todos') activeChips.push({ k:'comb', label:filters.combustible, clear:()=>set1({combustible:'Todos'}) });
  if (filters.transmision!=='Todas') activeChips.push({ k:'trans', label:filters.transmision, clear:()=>set1({transmision:'Todas'}) });
  if (filters.soloConFotos) activeChips.push({ k:'fotos', label:'Con fotos', clear:()=>set1({soloConFotos:false}) });
  if (filters.soloDestacados) activeChips.push({ k:'dest', label:'Destacados', clear:()=>set1({soloDestacados:false}) });

  return (
    <main className={`catalog-root ${embedded ? 'catalog-embedded' : ''}`}>
      {!embedded && (
        <section className="catalog-hero">
          <div className="container">
            <div className="eyebrow">Catálogo · Mendoza</div>
            <h1 className="display-lg" style={{marginTop:10}}>Toda la flota disponible.</h1>
            <p style={{maxWidth:560, color:'var(--ink-dim)', marginTop:12}}>{vehicles.length} unidades seleccionadas, inspeccionadas y listas para entrega. Filtr&aacute; por marca, tipo, presupuesto o año.</p>
          </div>
        </section>
      )}

      <div className="container catalog-body">
        <aside className={`filters ${showFilters ? '' : 'collapsed'}`}>
          <div className="filters-head">
            <div className="eyebrow">Filtros</div>
            <button className="filters-clear" onClick={reset}>Limpiar todo</button>
          </div>

          <div className="filter-search">
            <Icon.Search width="16" height="16"/>
            <input placeholder="Buscar marca, modelo..." value={filters.q} onChange={e=>setFilters({...filters, q:e.target.value})}/>
          </div>

          <div className="afilter-bar">
            <span className="afilter-count"><strong>{filtered.length}</strong> resultado{filtered.length!==1?'s':''}</span>
            {activeChips.length>0 && <button className="afilter-reset" onClick={reset}>Limpiar</button>}
          </div>
          {activeChips.length>0 && (
            <div className="achips">
              {activeChips.map(ch => (
                <button key={ch.k} type="button" className="achip" onClick={ch.clear}>{ch.label}<span className="ax">✕</span></button>
              ))}
            </div>
          )}

          <AccBlock id="vehiculo" label="Vehículo" value={filters.marca!=='Todas'?(filters.modelo!=='Todos'?`${filters.marca} ${filters.modelo}`:filters.marca):''}>
            <div className="fsel-stack">
              <select className="fsel" value={filters.marca} onChange={e=>setMarca(e.target.value)}>
                {marcas.map(m => <option key={m} value={m}>{m==='Todas'?`Todas las marcas (${vehicles.length})`:`${m} (${marcaCount[m]||0})`}</option>)}
              </select>
              <select className="fsel" value={filters.modelo} onChange={e=>setModelo(e.target.value)} disabled={modelosOpts.length===0}>
                <option value="Todos">{filters.marca==='Todas'?'Modelo (elegí marca)':'Todos los modelos'}</option>
                {modelosOpts.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
              </select>
              <select className="fsel" value={filters.version} onChange={e=>setFilters({...filters, version:e.target.value})} disabled={versionOpts.length===0}>
                <option value="Todas">{filters.modelo==='Todos'?'Versión (elegí modelo)':'Todas las versiones'}</option>
                {versionOpts.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
              </select>
            </div>
          </AccBlock>

          <AccBlock id="precio" label="Precio" value={precioLabel}>
            <div className="fsel-pair">
              <select className="fsel" value={filters.precioMin} onChange={e=>setFilters({...filters, precioMin:Math.min(+e.target.value, filters.precioMax)})}>
                <option value={0}>Desde</option>
                {PRECIO_STEPS.filter(n=>n>0&&n<70000000).map(n=> <option key={n} value={n}>{money(n)}</option>)}
              </select>
              <select className="fsel" value={filters.precioMax} onChange={e=>setFilters({...filters, precioMax:Math.max(+e.target.value, filters.precioMin)})}>
                {PRECIO_STEPS.filter(n=>n>0).map(n=> <option key={n} value={n}>{n>=70000000?'Hasta $70M+':`Hasta ${money(n)}`}</option>)}
              </select>
            </div>
          </AccBlock>

          <AccBlock id="anio" label="Año" value={anioLabel}>
            <div className="fsel-pair">
              <select className="fsel" value={filters.anioMin} onChange={e=>setFilters({...filters, anioMin:Math.min(+e.target.value, filters.anioMax)})}>
                {ANIOS.map(y=> <option key={y} value={y}>{y===1980?'Desde 1980':`Desde ${y}`}</option>)}
              </select>
              <select className="fsel" value={filters.anioMax} onChange={e=>setFilters({...filters, anioMax:Math.max(+e.target.value, filters.anioMin)})}>
                {ANIOS.map(y=> <option key={y} value={y}>{y===2026?'Hasta 2026':`Hasta ${y}`}</option>)}
              </select>
            </div>
          </AccBlock>

          <AccBlock id="km" label="Kilometraje" value={kmLabel}>
            <select className="fsel" value={filters.kmMax} onChange={e=>setFilters({...filters, kmMax:+e.target.value})}>
              <option value={300000}>Cualquier kilometraje</option>
              {KM_STEPS.map(n=> <option key={n} value={n}>{`Hasta ${fmtKm(n)}`}</option>)}
            </select>
          </AccBlock>

          <AccBlock id="carroceria" label="Carrocería" value={filters.carroceria!=='Todas'?filters.carroceria:''}>
            <div className="mlist">
              {carrocerias.map(c => (
                <button key={c} type="button" className={`mitem ${filters.carroceria===c?'on':''}`} onClick={()=>setFilters({...filters, carroceria:c})}>
                  <span>{c}</span><span className="mn">{c==='Todas'?vehicles.length:(carroCount[c]||0)}</span>
                </button>
              ))}
            </div>
          </AccBlock>

          <AccBlock id="combustible" label="Combustible" value={filters.combustible!=='Todos'?filters.combustible:''}>
            <div className="mlist">
              {combustibles.map(c => (
                <button key={c} type="button" className={`mitem ${filters.combustible===c?'on':''}`} onClick={()=>setFilters({...filters, combustible:c})}>
                  <span>{c}</span><span className="mn">{c==='Todos'?vehicles.length:(combCount[c]||0)}</span>
                </button>
              ))}
            </div>
          </AccBlock>

          <AccBlock id="transmision" label="Transmisión" value={filters.transmision!=='Todas'?filters.transmision:''}>
            <div className="mlist">
              {transmisiones.map(t => (
                <button key={t} type="button" className={`mitem ${filters.transmision===t?'on':''}`} onClick={()=>setFilters({...filters, transmision:t})}>
                  <span>{t}</span><span className="mn">{t==='Todas'?vehicles.length:(transCount[t]||0)}</span>
                </button>
              ))}
            </div>
          </AccBlock>

          <div className="filter-toggles">
            <label className="toggle-row">
              <span>Sólo con fotos</span>
              <span className={`tsw ${filters.soloConFotos?'on':''}`}><input type="checkbox" checked={filters.soloConFotos} onChange={e=>setFilters({...filters, soloConFotos:e.target.checked})}/></span>
            </label>
            <label className="toggle-row">
              <span>Sólo destacados / premium</span>
              <span className={`tsw ${filters.soloDestacados?'on':''}`}><input type="checkbox" checked={filters.soloDestacados} onChange={e=>setFilters({...filters, soloDestacados:e.target.checked})}/></span>
            </label>
          </div>

          <button type="button" className="filter-apply" onClick={()=>{ setShowFilters(false); document.querySelector('.catalog-results')?.scrollIntoView({behavior:'smooth', block:'start'}); }}>
            Ver {filtered.length} resultado{filtered.length!==1?'s':''}
          </button>
        </aside>

        <section className="catalog-results">
          <div className="results-bar">
            <button className="btn btn-ghost btn-sm" onClick={()=>setShowFilters(!showFilters)}>
              <Icon.Filter width="14" height="14"/> {showFilters?'Ocultar':'Mostrar'} filtros
            </button>
            <div className="results-count mono">
              <strong style={{color:'var(--ink)'}}>{filtered.length}</strong> / {vehicles.length} unidades
            </div>
            <div className="results-sort">
              <span className="eyebrow">Ordenar</span>
              <select className="select" style={{width:'auto', minWidth:180}} value={sort} onChange={e=>setSort(e.target.value)}>
                <option value="relevancia">Relevancia</option>
                <option value="precio-asc">Precio: menor a mayor</option>
                <option value="precio-desc">Precio: mayor a menor</option>
                <option value="anio-desc">Año: más nuevos</option>
                <option value="km-asc">Kilometraje: menor</option>
              </select>
            </div>
          </div>

          {filtered.length === 0 ? (
            <div className="empty-state empty-state-rich">
              <RequestCarForm preset={filters} variant="empty"/>
              <div style={{marginTop:32, paddingTop:32, borderTop:'1px solid var(--line)', textAlign:'center'}}>
                <button className="btn btn-ghost btn-sm" onClick={reset}>Ver toda la flota</button>
              </div>
            </div>
          ) : (
            <div className="grid-vehicles grid-vehicles-3">
              {filtered.map(v => <VehicleCard key={v.id} v={v} onClick={onSelectVehicle}/>)}
            </div>
          )}
        </section>
      </div>
    </main>
  );
};

Object.assign(window, { CatalogScreen });
