function Home() {
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [bundles, setBundles] = React.useState([]);
  const { addItem } = window.CartContext.useCart();
  const [modalProduct, setModalProduct] = React.useState(null);

  React.useEffect(() => {
    // Sécurité: évite de setState après démontage du composant
    let mounted = true;
    (async () => {
      try {
        const [topRes, bundlesRes] = await Promise.all([
          window.ProductsAPI.top(8),
          window.BundlesAPI.list().catch(() => ({ items: [] })),
        ]);
        if (mounted) {
          setItems(topRes.items || []);
          setBundles(bundlesRes.items || []);
        }
      } catch (e) {
        // Journalisation non bloquante si le chargement échoue (ex: réseau)
        try { console.error('Échec du chargement des produits en avant', e); } catch {}
      } finally {
        if (mounted) setLoading(false);
      }
    })();
    return () => { mounted = false; };
  }, []);

  return (
    <div className="container">
      <h1>Bienvenue sur la boutique</h1>
      <p>Découvrez notre sélection mise en avant, puis explorez tout le catalogue.</p>

      {bundles.length > 0 && (
        <div style={{ marginTop: 16, padding: 12, border: '1px solid var(--brand-border)', borderRadius: 8, background: 'transparent' }}>
          <h3 style={{ marginTop: 0 }}>Offres promotionnelles</h3>
          <ul style={{ margin: 0, paddingLeft: 18 }}>
            {bundles.slice(0, 5).map(b => (
              <li key={b.id}>
                <b>{b.name}</b>
                {b.description ? ` — ${b.description}` : ''}
                <span style={{ color: '#666' }}> ({b.discount_type === 'percent' ? `${Number(b.discount_value).toLocaleString('fr-FR', { maximumFractionDigits: 2 })}%` : `${(b.discount_value/100).toFixed(2)}€`} de remise)</span>
              </li>
            ))}
          </ul>
        </div>
      )}

  <h3 style={{ marginTop: 24 }}>Coups de coeur</h3>
      {loading ? (
        <p>Chargement…</p>
      ) : items.length === 0 ? (
        <p>Aucun produit en avant pour le moment. <a href="#/catalog">Voir le catalogue</a></p>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: 16 }}>
          {items.map(p => (
            <window.Components.ProductCard key={p.id} product={p} onAdd={addItem} polaroid onOpen={()=>setModalProduct(p)} />
          ))}
        </div>
      )}
      <window.Components.ProductModal product={modalProduct||{}} open={!!modalProduct} onClose={()=>setModalProduct(null)} />
    </div>
  );
}

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