// Listing screen with filters
function ListingScreen({ navigate, addToCart, isMobile, initial }) {
  const P = window.POP;
  const allProducts = window.POP_PRODUCTS;
  const categories = [...new Set(allProducts.map(p => p.category).filter(Boolean))].sort();
  const brands     = [...new Set(allProducts.map(p => p.brand).filter(Boolean))].sort();
  const maxPrice   = allProducts.length ? Math.max(...allProducts.map(p => p.price)) : 2000;

  const [selectedCat, setSelectedCat] = React.useState(
    initial?.category && initial.category !== 'Ofertas' ? [initial.category] : []
  );
  const [selectedBrand, setSelectedBrand] = React.useState([]);
  const [priceMax, setPriceMax] = React.useState(maxPrice);
  const [onlyDiscount, setOnlyDiscount] = React.useState(initial?.category === 'Ofertas');
  const [sort, setSort] = React.useState('relevance');
  const [filtersOpenMobile, setFiltersOpenMobile] = React.useState(false);
  const [page, setPage] = React.useState(1);

  const toggle = (list, setList, item) =>
    setList(list.includes(item) ? list.filter(x => x !== item) : [...list, item]);

  let filtered = allProducts.filter(p => {
    if (selectedCat.length && !selectedCat.includes(p.category)) return false;
    if (selectedBrand.length && !selectedBrand.includes(p.brand)) return false;
    if (p.price > priceMax) return false;
    if (onlyDiscount && !p.discount) return false;
    return true;
  });

  if (sort === 'price-asc')  filtered = [...filtered].sort((a, b) => a.price - b.price);
  if (sort === 'price-desc') filtered = [...filtered].sort((a, b) => b.price - a.price);
  if (sort === 'rating')     filtered = [...filtered].sort((a, b) => b.rating - a.rating);
  if (sort === 'discount')   filtered = [...filtered].sort((a, b) => (b.discount || 0) - (a.discount || 0));

  const PAGE_SIZE = 50;
  const totalPages = Math.ceil(filtered.length / PAGE_SIZE);
  const pageProducts = filtered.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);

  React.useEffect(() => { setPage(1); }, [selectedCat, selectedBrand, priceMax, onlyDiscount, sort]);

  const goToPage = p => {
    setPage(p);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const pageNums = (() => {
    if (totalPages <= 7) return Array.from({ length: totalPages }, (_, i) => i + 1);
    const pages = [1];
    if (page > 3) pages.push('...');
    for (let i = Math.max(2, page - 1); i <= Math.min(totalPages - 1, page + 1); i++) pages.push(i);
    if (page < totalPages - 2) pages.push('...');
    pages.push(totalPages);
    return pages;
  })();

  const fmt = n => n.toLocaleString('es-MX');
  const activeFilterCount = selectedCat.length + selectedBrand.length + (onlyDiscount ? 1 : 0);

  const FiltersPanel = () => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div>
        <div style={{ fontFamily: P.display, fontSize: 13, letterSpacing: 1, marginBottom: 10 }}>CATEGORÍA</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {categories.map(c => (
            <label key={c} style={{ display: 'flex', gap: 10, alignItems: 'center', fontSize: 13, cursor: 'pointer' }}>
              <input type="checkbox" checked={selectedCat.includes(c)} onChange={() => toggle(selectedCat, setSelectedCat, c)}
                style={{ width: 18, height: 18, accentColor: P.ink }} />
              <span style={{ flex: 1 }}>{c}</span>
              <span style={{ fontSize: 11, color: P.dim }}>({allProducts.filter(p => p.category === c).length})</span>
            </label>
          ))}
        </div>
      </div>

      <div>
        <div style={{ fontFamily: P.display, fontSize: 13, letterSpacing: 1, marginBottom: 10 }}>PRECIO MÁXIMO</div>
        <input type="range" min="0" max={maxPrice} step={Math.max(1, Math.round(maxPrice / 100))} value={priceMax} onChange={e => setPriceMax(+e.target.value)}
          style={{ width: '100%', accentColor: P.ink, cursor: 'pointer' }} />
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginTop: 6 }}>
          <span style={{ color: P.dim }}>$0</span>
          <span style={{ fontFamily: P.display, fontSize: 14 }}>${fmt(priceMax)}</span>
        </div>
      </div>

      <div>
        <div style={{ fontFamily: P.display, fontSize: 13, letterSpacing: 1, marginBottom: 10 }}>OFERTAS</div>
        <label style={{ display: 'flex', gap: 10, alignItems: 'center', fontSize: 13, cursor: 'pointer' }}>
          <input type="checkbox" checked={onlyDiscount} onChange={e => setOnlyDiscount(e.target.checked)}
            style={{ width: 18, height: 18, accentColor: P.ink }} />
          <span>Solo productos en oferta 🔥</span>
        </label>
      </div>

      <div>
        <div style={{ fontFamily: P.display, fontSize: 13, letterSpacing: 1, marginBottom: 10 }}>MARCA</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {brands.map(b => (
            <PopChip key={b} color={P.cream} size="sm" active={selectedBrand.includes(b)}
              onClick={() => toggle(selectedBrand, setSelectedBrand, b)}>{b}</PopChip>
          ))}
        </div>
      </div>

      <PopButton variant="secondary" size="sm" full onClick={() => {
        setSelectedCat([]); setSelectedBrand([]); setPriceMax(maxPrice); setOnlyDiscount(false);
      }}>Limpiar filtros</PopButton>
    </div>
  );

  return (
    <div className="pop-page-in" style={{ padding: isMobile ? 16 : 32, overflow: 'hidden' }}>

      {/* Breadcrumb + title */}
      <div style={{ marginBottom: isMobile ? 16 : 24 }}>
        <div style={{ fontSize: 11, color: P.dim, letterSpacing: 0.5, marginBottom: 6, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          <span onClick={() => navigate('home')} style={{ cursor: 'pointer', textDecoration: 'underline' }}>Inicio</span>
          {' › '}
          <span>{selectedCat.length === 1 ? selectedCat[0] : (onlyDiscount ? 'Ofertas' : 'Todos los productos')}</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
          <div style={{ minWidth: 0, flex: '1 1 200px' }}>
            <div style={{ fontFamily: P.display, fontSize: isMobile ? 26 : 48, letterSpacing: -1.5, lineHeight: 1, wordBreak: 'break-word' }}>
              {selectedCat.length === 1 ? selectedCat[0].toUpperCase() :
               onlyDiscount ? <><span>HOT WEEK </span><span style={{ color: P.red }}>🔥</span></> :
               'TODOS LOS PRODUCTOS'}
            </div>
            <div style={{ fontSize: 13, color: P.dim, marginTop: 6, fontWeight: 500 }}>
              {filtered.length} resultado{filtered.length !== 1 ? 's' : ''} de {allProducts.length}
              {totalPages > 1 && ` · Página ${page} de ${totalPages}`}
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
            {isMobile && (
              <PopButton variant="secondary" size="md" onClick={() => setFiltersOpenMobile(true)}>
                ⚙ Filtros{activeFilterCount > 0 && ` · ${activeFilterCount}`}
              </PopButton>
            )}
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, background: P.card, border: `2px solid ${P.ink}`,
              borderRadius: 10, padding: '6px 10px', boxShadow: `2px 2px 0 ${P.ink}`, maxWidth: '100%' }}>
              <span style={{ fontSize: 10, fontFamily: P.display, letterSpacing: 1, whiteSpace: 'nowrap' }}>ORDENAR</span>
              <select value={sort} onChange={e => setSort(e.target.value)} style={{
                border: 'none', background: 'transparent', fontFamily: P.font, fontSize: 12, fontWeight: 600,
                outline: 'none', cursor: 'pointer', maxWidth: isMobile ? 120 : 'auto',
              }}>
                <option value="relevance">Relevancia</option>
                <option value="price-asc">Menor precio</option>
                <option value="price-desc">Mayor precio</option>
                <option value="rating">Mejor calificados</option>
                <option value="discount">Mayor descuento</option>
              </select>
            </div>
          </div>
        </div>

        {/* Active filter chips */}
        {activeFilterCount > 0 && (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 14 }}>
            {selectedCat.map(c => (
              <PopChip key={c} color={P.yellow} size="sm" onClick={() => toggle(selectedCat, setSelectedCat, c)}>
                {c} <span style={{ fontSize: 14, marginLeft: 4 }}>×</span>
              </PopChip>
            ))}
            {selectedBrand.map(b => (
              <PopChip key={b} color={P.pink} size="sm" onClick={() => toggle(selectedBrand, setSelectedBrand, b)}>
                {b} <span style={{ fontSize: 14, marginLeft: 4 }}>×</span>
              </PopChip>
            ))}
            {onlyDiscount && (
              <PopChip color={P.red} size="sm" onClick={() => setOnlyDiscount(false)}>
                <span style={{ color: P.card }}>🔥 OFERTAS ×</span>
              </PopChip>
            )}
          </div>
        )}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '260px 1fr', gap: isMobile ? 0 : 24 }}>
        {/* Filters sidebar — desktop */}
        {!isMobile && (
          <div style={{ background: P.card, border: `2px solid ${P.ink}`, borderRadius: 14, padding: 20,
            boxShadow: `4px 4px 0 ${P.ink}`, height: 'fit-content', position: 'sticky', top: 140 }}>
            <div style={{ fontFamily: P.display, fontSize: 18, letterSpacing: -0.5, marginBottom: 14,
              paddingBottom: 10, borderBottom: `2px dashed ${P.ink}` }}>⚙ FILTROS</div>
            <FiltersPanel />
          </div>
        )}

        {/* Product grid */}
        <div>
          {filtered.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '80px 16px', background: P.card, border: `2px dashed ${P.ink}`, borderRadius: 14 }}>
              <div style={{ fontSize: 48 }}>🔍</div>
              <div style={{ fontFamily: P.display, fontSize: 24, marginTop: 12 }}>Sin resultados</div>
              <div style={{ fontSize: 13, color: P.dim, marginTop: 6 }}>Prueba a quitar algunos filtros.</div>
            </div>
          ) : (
            <div style={{ display: 'grid', gridTemplateColumns: isMobile ? 'repeat(2,1fr)' : 'repeat(4,1fr)', gap: isMobile ? 12 : 12 }}>
              {pageProducts.map((p, i) => (
                <div key={p.id} className="pop-fade-up" style={{ animationDelay: `${Math.min(i, 8) * 0.04}s` }}>
                  <ProductCard product={p} onClick={() => navigate('pdp', { id: p.id })} onAddToCart={addToCart} />
                </div>
              ))}
            </div>
          )}

          {totalPages > 1 && (
            <div style={{ display: 'flex', justifyContent: 'center', gap: 6, marginTop: 32, alignItems: 'center', flexWrap: 'wrap' }}>
              <PopChip color={P.card} size="md" onClick={() => page > 1 && goToPage(page - 1)}>←</PopChip>
              {pageNums.map((n, i) =>
                n === '...'
                  ? <span key={`dots-${i}`} style={{ color: P.dim, padding: '0 2px', lineHeight: '36px' }}>···</span>
                  : <PopChip key={n} color={n === page ? P.yellow : P.card} active={n === page} size="md" onClick={() => goToPage(n)}>{n}</PopChip>
              )}
              <PopChip color={P.card} size="md" onClick={() => page < totalPages && goToPage(page + 1)}>→</PopChip>
            </div>
          )}
        </div>
      </div>

      {/* Mobile filter drawer */}
      {isMobile && filtersOpenMobile && (
        <>
          <div onClick={() => setFiltersOpenMobile(false)} className="pop-overlay-in"
            style={{ position: 'fixed', inset: 0, background: 'rgba(26,20,16,0.5)', zIndex: 99 }}></div>
          <div className="pop-drawer-in" style={{
            position: 'fixed', top: 0, right: 0, bottom: 0, width: 'min(380px, 95vw)',
            background: P.bg, zIndex: 100, display: 'flex', flexDirection: 'column',
            borderLeft: `3px solid ${P.ink}`,
          }}>
            <div style={{ padding: '18px 20px', background: P.yellow, borderBottom: `3px solid ${P.ink}`,
              display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div style={{ fontFamily: P.display, fontSize: 20, letterSpacing: -0.5 }}>⚙ FILTROS</div>
              <button onClick={() => setFiltersOpenMobile(false)} className="pop-press" style={{
                width: 36, height: 36, borderRadius: 10, background: P.card, border: `2px solid ${P.ink}`,
                boxShadow: `2px 2px 0 ${P.ink}`, fontFamily: P.display, fontSize: 14,
              }}>✕</button>
            </div>
            <div style={{ flex: 1, overflowY: 'auto', padding: 20 }}>
              <FiltersPanel />
            </div>
            <div style={{ padding: 16, borderTop: `3px solid ${P.ink}`, background: P.cream }}>
              <PopButton variant="dark" size="lg" full onClick={() => setFiltersOpenMobile(false)}>
                Ver {filtered.length} resultado{filtered.length !== 1 ? 's' : ''} →
              </PopButton>
            </div>
          </div>
        </>
      )}
    </div>
  );
}

window.ListingScreen = ListingScreen;
