function euros(c) { return (c/100).toFixed(2) + '€'; }

function Catalog() {
  try { console.log('[Catalog.jsx] mounted'); } catch {}
  const [data, setData] = React.useState({ items: [], page: 1, total: 0, limit: 50 });
  const [search, setSearch] = React.useState('');
  const [category, setCategory] = React.useState('');
  const [sort, setSort] = React.useState('recent'); // recent | name | price-asc | price-desc
  const { addItem } = window.CartContext.useCart();
  const [modalProduct, setModalProduct] = React.useState(null);

  // Lit le paramètre de catégorie depuis le hash (ex: #/catalog?cat=tshirt)
  function readCategoryFromHash() {
    const h = String(window.location.hash || '');
    const [, query = ''] = h.split('?');
    const params = new URLSearchParams(query);
    return params.get('cat') || '';
  }

  // Charge la liste des produits selon recherche + catégorie
  async function load(opts = {}) {
    const s = Object.prototype.hasOwnProperty.call(opts, 'search') ? opts.search : search;
    const c = Object.prototype.hasOwnProperty.call(opts, 'category') ? opts.category : category;
    const page = Object.prototype.hasOwnProperty.call(opts, 'page') ? opts.page : data.page || 1;
    const limit = data.limit || 50;
    const so = Object.prototype.hasOwnProperty.call(opts, 'sort') ? opts.sort : sort;
    const res = await window.ProductsAPI.list({ search: s, category: c, page, limit, sort: so });
    try { console.debug('Catalog.load result', { search: s, category: c, count: (res.items||[]).length, res }); } catch {}
    setData(res);
  }
  React.useEffect(() => {
    const firstCat = readCategoryFromHash();
    setCategory(firstCat);
    const onHash = () => {
      const c = readCategoryFromHash();
      setCategory(c);
      setSearch('');
      load({ category: c, search: '' });
    };
    window.addEventListener('hashchange', onHash);
    load({ category: firstCat });
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  // Note: on recharge lors d'un changement de hash et au montage initial avec la catégorie appropriée

  function makePageList(page, total, limit) {
    const totalPages = Math.max(1, Math.ceil((total || 0) / (limit || 50)));
    const p = Math.min(Math.max(1, page || 1), totalPages);
    if (totalPages <= 10) return Array.from({ length: totalPages }, (_, i) => i + 1);
    const pages = new Set([1, totalPages]);
    for (let i = p - 2; i <= p + 2; i++) if (i >= 1 && i <= totalPages) pages.add(i);
    const arr = Array.from(pages).sort((a, b) => a - b);
    const result = [];
    for (let i = 0; i < arr.length; i++) {
      result.push(arr[i]);
      if (i < arr.length - 1 && arr[i + 1] !== arr[i] + 1) result.push('…');
    }
    return result;
  }

  return (
    <div className="container">
      {/* Ligne d'information Route/Catégorie supprimée pour alléger l'interface */}
      <div style={{ position:'sticky', top: 180, zIndex: 900, background: 'rgba(255,255,255,0.9)', backdropFilter: 'blur(4px)', padding: '8px 0', marginBottom: 12, borderBottom: '1px solid #eee' }}>
        <div style={{ display:'flex', gap:8, alignItems:'center' }}>
          <input placeholder="Rechercher..." value={search} onChange={(e)=>setSearch(e.target.value)} />
          <button onClick={load}>Rechercher</button>
          <div style={{ marginLeft: 12, display:'flex', alignItems:'center', gap:6 }}>
            <label style={{ fontSize:12, color:'#666' }}>Trier par
              <select value={sort} onChange={(e)=>{ setSort(e.target.value); load({ sort: e.target.value, page: 1 }); }} style={{ marginLeft: 6 }}>
                <option value="recent">Plus récent</option>
                <option value="name">Alphabetique (A→Z)</option>
                <option value="price-asc">Prix croissant</option>
                <option value="price-desc">Prix décroissant</option>
              </select>
            </label>
          </div>
          <div style={{ marginLeft: 12, fontSize: 12, color: '#666' }}>
            {/* On n'affiche que les produits en stock et non archivés */}
            {category ? `Filtre: ${category} • ` : ''}Résultats: {Array.isArray(data.items) ? data.items.filter(p => !p.archived && p.stock > 0).length : 0}
          </div>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: 16 }}>
        {data.items
          .filter(p => !p.archived && p.stock > 0)
          .map((p) => (
            <div key={p.id} onClick={()=>setModalProduct(p)} style={{ cursor:'pointer' }}>
              <window.Components.ProductCard product={p} onAdd={addItem} polaroid />
            </div>
          ))}
      </div>
      {(() => {
        const page = data.page || 1;
        const limit = data.limit || 50;
        const total = data.total || 0;
        const totalPages = Math.max(1, Math.ceil(total / limit));
        const showPrev = page > 1;
        const showNext = page < totalPages;
        const showPager = totalPages > 1;
        if (!showPrev && !showNext && !showPager) return null; // rien à afficher
        return (
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginTop: 12 }}>
            <div>
              {showPrev && (
                <button onClick={()=>load({ page: Math.max(1, page-1) })}>« Précédent</button>
              )}
            </div>
            {showPager && (
              <div style={{ display:'flex', gap:6, alignItems:'center' }}>
                {makePageList(page, total, limit).map((p, idx) => (
                  typeof p === 'number' ? (
                    <button key={idx} onClick={()=>load({ page: p })} disabled={p === page} style={{ padding:'4px 8px', borderRadius:6, border: p===page?'1px solid #2563eb':'1px solid #ddd', background: p===page?'#eff6ff':'#fff' }}>{p}</button>
                  ) : (
                    <span key={idx} style={{ color:'#999' }}>…</span>
                  )
                ))}
              </div>
            )}
            <div>
              {showNext && (
                <button onClick={()=>load({ page: page+1 })}>Suivant »</button>
              )}
            </div>
          </div>
        );
      })()}
      {data.items.filter(p=>!p.archived && p.stock>0).length === 0 && (
        <p>Aucun produit disponible pour le moment.</p>
      )}
      <window.Components.ProductModal product={modalProduct||{}} open={!!modalProduct} onClose={()=>setModalProduct(null)} />
    </div>
  );
}

window.Pages = window.Pages || {};
window.Pages.Catalog = Catalog;
