// Catalog page — product browser with filters, sort, color search.

function PageCatalog() {
  const [category, setCategory] = useState('all');
  const [family, setFamily] = useState('all');
  const [search, setSearch] = useState('');
  const [sort, setSort] = useState('popular');
  const [view, setView] = useState('grid');

  const items = useMemo(() => {
    let list = PRODUCTS.slice();
    if (category !== 'all') list = list.filter(p => p.category === category);
    if (family !== 'all')   list = list.filter(p => {
      const sw = RAL_COLORS.find(c => c.ral === p.ral);
      return sw && sw.family === family;
    });
    if (search) {
      const q = search.toLowerCase();
      list = list.filter(p =>
        (p.name + p.brand + p.subtitle + p.subcat).toLowerCase().includes(q));
    }
    if (sort === 'price-asc')  list.sort((a, b) => a.price - b.price);
    if (sort === 'price-desc') list.sort((a, b) => b.price - a.price);
    if (sort === 'popular')    list.sort((a, b) => (b.popular ? 1 : 0) - (a.popular ? 1 : 0));
    if (sort === 'name')       list.sort((a, b) => a.name.localeCompare(b.name, 'pl'));
    return list;
  }, [category, family, search, sort]);

  return (
    <>
      <div className="page-head">
        <div className="container">
          <div className="page-head__crumbs">
            <Link to="/">Start</Link> <Icon name="chevron-right" size={11}/> <span>Katalog</span>
          </div>
          <div className="page-head__title">
            <h1>Pełny <em style={{ fontStyle: 'italic', fontWeight: 380, color: 'var(--brand)' }}>katalog</em><br/>
              farb, lakierów<br/>i akcesoriów.</h1>
            <p className="page-head__lede">
              {PRODUCTS.length * 53} pozycji w aktywnym stanie magazynu, w trzech oddziałach.
              Mieszamy w 8 minut. Wyszukaj producenta, kategorię, albo otwórz wzornik RAL.
            </p>
          </div>
        </div>
      </div>

      <section className="section section--tight">
        <div className="container">
          <div className="cat-toolbar">
            <div className="cat-search">
              <Icon name="search" size={16} stroke={1.8} style={{ color: 'var(--ink-3)' }}/>
              <input className="cat-search__input"
                placeholder="Szukaj produktu, marki, koloru…"
                value={search} onChange={e => setSearch(e.target.value)}/>
              {search && (
                <button onClick={() => setSearch('')}
                  style={{ background: 'transparent', border: 0, padding: 4, color: 'var(--ink-3)' }}>
                  <Icon name="x" size={14}/>
                </button>
              )}
              <span className="kbd">/</span>
            </div>
            <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
              <select className="select cat-sort" value={sort} onChange={e => setSort(e.target.value)}>
                <option value="popular">Popularne</option>
                <option value="price-asc">Cena rosnąco</option>
                <option value="price-desc">Cena malejąco</option>
                <option value="name">Nazwa A–Z</option>
              </select>
              <div className="view-toggle">
                <button className={view === 'grid' ? 'is-active' : ''} onClick={() => setView('grid')}
                  aria-label="Widok siatki">
                  <Icon name="sliders" size={14}/>
                </button>
                <button className={view === 'list' ? 'is-active' : ''} onClick={() => setView('list')}
                  aria-label="Widok listy">
                  <Icon name="menu" size={14}/>
                </button>
              </div>
            </div>
          </div>

          <div className="cat-grid">
            <aside className="cat-side">
              <div className="cat-side__sec">
                <h4>Kategoria</h4>
                <div className="cat-side__list">
                  <FilterPill label="Wszystkie" count={PRODUCTS.length}
                    active={category === 'all'} onClick={() => setCategory('all')}/>
                  {CATEGORIES.map(c => (
                    <FilterPill key={c.id} label={c.title} count={PRODUCTS.filter(p => p.category === c.id).length}
                      active={category === c.id} onClick={() => setCategory(c.id)}/>
                  ))}
                </div>
              </div>
              <div className="cat-side__sec">
                <h4>Rodzina kolorów</h4>
                <div className="cat-fams">
                  <button className={'cat-fam' + (family === 'all' ? ' is-active' : '')}
                    onClick={() => setFamily('all')}>
                    <span style={{
                      width: 22, height: 22, borderRadius: 6,
                      background: 'conic-gradient(from 0deg, #E5BE01, #F44611, #AF2B1E, #924E7D, #2271B3, #4C9141, #E5BE01)'
                    }}/>
                    <span>Wszystkie</span>
                  </button>
                  {RAL_FAMILIES.map(f => (
                    <button key={f.id}
                      className={'cat-fam' + (family === f.id ? ' is-active' : '')}
                      onClick={() => setFamily(f.id)}>
                      <span className="swatch" style={{ background: f.hex, width: 22, height: 22, borderRadius: 6 }}/>
                      <span>{f.label}</span>
                    </button>
                  ))}
                </div>
              </div>
              <div className="cat-side__sec">
                <h4>Marka</h4>
                <div className="cat-side__list">
                  {['Tikkurila', 'Beckers', 'Dulux', 'Dekoral', 'Teknos', 'Sika', 'Alcea'].map(b => (
                    <label key={b} className="checkbox">
                      <input type="checkbox" defaultChecked={['Tikkurila', 'Beckers'].includes(b)}/>
                      <span>{b}</span>
                      <span className="text-mono text-3" style={{ marginLeft: 'auto', fontSize: 11 }}>
                        {PRODUCTS.filter(p => p.brand === b).length}
                      </span>
                    </label>
                  ))}
                </div>
              </div>
              <div className="cat-side__sec">
                <h4>Cena (zł)</h4>
                <div style={{ display: 'flex', gap: 8 }}>
                  <input className="input" placeholder="Od" defaultValue="0"/>
                  <input className="input" placeholder="Do" defaultValue="2000"/>
                </div>
                <div style={{
                  height: 4, background: 'var(--bg-tint)', borderRadius: 999, marginTop: 16, position: 'relative'
                }}>
                  <div style={{ position: 'absolute', left: '8%', right: '32%', top: 0, bottom: 0,
                    background: 'var(--brand)', borderRadius: 999 }}/>
                  <div style={{ position: 'absolute', left: '8%', top: -4, width: 12, height: 12,
                    borderRadius: 999, background: 'var(--bg-elev)', border: '2px solid var(--brand)' }}/>
                  <div style={{ position: 'absolute', left: '68%', top: -4, width: 12, height: 12,
                    borderRadius: 999, background: 'var(--bg-elev)', border: '2px solid var(--brand)' }}/>
                </div>
              </div>

              <button className="btn btn--ghost btn--sm" style={{ width: '100%', justifyContent: 'center' }}
                onClick={() => { setCategory('all'); setFamily('all'); setSearch(''); }}>
                Wyczyść filtry
              </button>
            </aside>

            <div>
              <div style={{ display: 'flex', justifyContent: 'space-between',
                marginBottom: 16, alignItems: 'center' }}>
                <span className="text-3" style={{ fontSize: 13 }}>
                  Znaleziono <strong style={{ color: 'var(--ink)' }}>{items.length}</strong> z {PRODUCTS.length}
                </span>
                <span className="text-mono text-3" style={{ fontSize: 11, letterSpacing: '0.1em' }}>
                  STAN MAGAZYNU · NA ŻYWO
                </span>
              </div>

              {view === 'grid' ? (
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
                  {items.map(p => <ProductCard key={p.id} p={p}/>)}
                </div>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {items.map(p => <ProductRow key={p.id} p={p}/>)}
                </div>
              )}

              {items.length === 0 && (
                <div className="card" style={{ textAlign: 'center', padding: 64 }}>
                  <Icon name="search" size={32} stroke={1.4} style={{ color: 'var(--ink-3)' }}/>
                  <h3 style={{ marginTop: 16, fontSize: 24 }}>Nic nie znaleźliśmy</h3>
                  <p className="text-3" style={{ fontSize: 14, marginTop: 8 }}>
                    Spróbuj innych słów kluczowych albo zadzwoń: 44 633 56 25 — pomożemy znaleźć.
                  </p>
                </div>
              )}
            </div>
          </div>
        </div>
      </section>

      <style>{`
        .cat-toolbar {
          display: grid; grid-template-columns: 1fr auto;
          gap: 16px; align-items: center;
          padding: 14px;
          background: var(--bg-elev);
          border: var(--hairline);
          border-radius: var(--r-pill);
          margin-bottom: 32px;
        }
        .cat-search {
          display: flex; align-items: center; gap: 10px;
          padding: 0 14px;
        }
        .cat-search__input {
          flex: 1; border: 0; background: transparent; outline: none;
          font: inherit; padding: 10px 0; color: var(--ink);
        }
        .cat-sort {
          padding: 8px 14px; border-radius: 999px; font-size: 13px;
          appearance: none;
          background: var(--bg-tint);
          border: 0;
          padding-right: 30px;
          background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%236a6358' stroke-width='2'><path d='M6 9l6 6 6-6'/></svg>");
          background-repeat: no-repeat; background-position: right 10px center;
        }
        .view-toggle { display: inline-flex; padding: 3px; background: var(--bg-tint); border-radius: 999px; gap: 2px; }
        .view-toggle button {
          width: 32px; height: 32px; border-radius: 999px; border: 0; background: transparent;
          color: var(--ink-3); display: grid; place-items: center;
        }
        .view-toggle button.is-active { background: var(--bg-elev); color: var(--ink); box-shadow: var(--sh-1); }

        .cat-grid {
          display: grid; grid-template-columns: 280px 1fr; gap: var(--space-6);
          align-items: start;
        }
        .cat-side {
          position: sticky; top: 80px;
          display: flex; flex-direction: column; gap: 28px;
          padding: 24px;
          background: var(--bg-elev);
          border: var(--hairline);
          border-radius: var(--r-lg);
        }
        .cat-side__sec h4 {
          font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.18em;
          text-transform: uppercase; color: var(--ink-3); margin-bottom: 12px;
        }
        .cat-side__list { display: flex; flex-direction: column; gap: 4px; }
        .cat-fams { display: flex; flex-wrap: wrap; gap: 6px; }
        .cat-fam {
          display: inline-flex; align-items: center; gap: 8px;
          padding: 6px 12px 6px 6px;
          border: 1px solid var(--line); background: var(--bg-elev);
          border-radius: 999px; font-size: 12px; color: var(--ink-2);
          transition: 160ms ease;
        }
        .cat-fam.is-active { background: var(--ink); color: var(--bg); border-color: var(--ink); }
        .cat-fam:hover:not(.is-active) { border-color: var(--ink); }

        .checkbox {
          display: flex; align-items: center; gap: 10px;
          padding: 8px 12px; border-radius: 8px;
          font-size: 13px; cursor: pointer; transition: 160ms ease;
        }
        .checkbox:hover { background: var(--bg-tint); }
        .checkbox input { accent-color: var(--brand); }

        @media (max-width: 980px) {
          .cat-grid { grid-template-columns: 1fr; }
          .cat-side { position: static; }
          .cat-grid > div [style*="grid-template-columns: repeat(3, 1fr)"] {
            grid-template-columns: repeat(2, 1fr) !important;
          }
        }
        @media (max-width: 600px) {
          .cat-toolbar { grid-template-columns: 1fr; padding: 8px; }
          .cat-grid > div [style*="grid-template-columns: repeat(3, 1fr)"] {
            grid-template-columns: 1fr !important;
          }
        }
      `}</style>
    </>
  );
}

function FilterPill({ label, count, active, onClick }) {
  return (
    <button onClick={onClick}
      style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '8px 12px', borderRadius: 8,
        background: active ? 'var(--ink)' : 'transparent',
        color: active ? 'var(--bg)' : 'var(--ink-2)',
        border: 0, fontSize: 13, fontWeight: 500, transition: '160ms ease',
        textAlign: 'left',
      }}
      onMouseEnter={e => { if (!active) e.currentTarget.style.background = 'var(--bg-tint)'; }}
      onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'transparent'; }}>
      <span>{label}</span>
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11,
        opacity: active ? 0.7 : 1,
        color: active ? 'var(--bg)' : 'var(--ink-3)' }}>{count}</span>
    </button>
  );
}

function ProductRow({ p }) {
  const swatch = RAL_COLORS.find(c => c.ral === p.ral) || RAL_COLORS[0];
  return (
    <Link to={'/katalog?id=' + p.id} className="prod-row">
      <div className="prod-row__swatch" style={{ background: swatch.hex }}/>
      <div className="prod-row__main">
        <div className="text-mono text-3" style={{ fontSize: 10, letterSpacing: '0.16em' }}>
          {p.brand.toUpperCase()} · {p.subcat.toUpperCase()} · RAL {p.ral}
        </div>
        <h3 style={{ fontSize: 18, marginTop: 4 }}>{p.name}</h3>
        <p className="text-3" style={{ fontSize: 13, marginTop: 2 }}>{p.subtitle}</p>
      </div>
      <div className="prod-row__meta">
        <span className="chip">{p.finish}</span>
        <span className="chip">{p.coverage}</span>
        <span className="chip">{p.sizes.join(' / ')}</span>
      </div>
      <div className="prod-row__price">
        <span style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500 }}>
          od {p.price}
        </span>
        <span className="text-3" style={{ fontSize: 12 }}>zł brutto</span>
      </div>
      <div style={{
        width: 36, height: 36, borderRadius: 999, background: 'var(--ink)', color: 'var(--bg)',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center'
      }}>
        <Icon name="arrow-right" size={14}/>
      </div>
      <style>{`
        .prod-row {
          display: grid;
          grid-template-columns: 56px 1fr auto auto 36px;
          gap: 24px; align-items: center;
          padding: 14px 20px;
          background: var(--bg-elev);
          border: var(--hairline);
          border-radius: var(--r-md);
          transition: 200ms ease;
        }
        .prod-row:hover {
          border-color: var(--ink);
          background: var(--bg-tint);
        }
        .prod-row__swatch { width: 56px; height: 56px; border-radius: 8px;
          box-shadow: inset 0 0 0 1px rgba(0,0,0,0.08); }
        .prod-row__meta { display: flex; gap: 6px; flex-wrap: wrap; }
        .prod-row__price { text-align: right; display: flex; flex-direction: column; align-items: end; }
        @media (max-width: 720px) {
          .prod-row { grid-template-columns: 48px 1fr 36px; }
          .prod-row__meta, .prod-row__price { display: none; }
        }
      `}</style>
    </Link>
  );
}

window.PageCatalog = PageCatalog;
