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

function CustomOrder() {
  const { user } = window.AuthContext.useAuth();
  const { addItem } = window.CartContext.useCart();
  const toast = window.Toast.useToast();
  const [categories, setCategories] = React.useState([]);
  const [category, setCategory] = React.useState('');
  const [note, setNote] = React.useState('');
  const [price, setPrice] = React.useState(null);
  const [priceMap, setPriceMap] = React.useState({});

  React.useEffect(() => {
    (async () => {
      try {
        const res = await window.ProductsAPI.categories();
        setCategories(res.items || []);
      } catch {}
      try {
        const cfg = await window.API.get('/api/custom-prices');
        setPriceMap(cfg.prices || {});
      } catch {}
    })();
  }, []);

  React.useEffect(() => {
    if (!category) { setPrice(null); return; }
    const p = priceMap[category];
    if (Number.isInteger(p)) setPrice(p);
    else setPrice(null);
  }, [category, priceMap]);

  function submit(e) {
    e.preventDefault();
    if (!category) { toast.error('Choisissez une catégorie'); return; }
    if (!Number.isInteger(price)) { toast.error('Prix indisponible'); return; }
    const catLabel = category || 'personnalisé';
    const name = `Création personnalisée (${catLabel})`;
    const pseudoProduct = {
      id: 1000000000 + Math.floor(Math.random()*1000000),
      name,
      price_cents: Number(price),
    };
    // Encode custom metadata into name for email summary (lightweight)
    const noteText = (note||'').trim();
    const itemName = noteText ? `${name} — ${noteText}` : name;
    addItem({ ...pseudoProduct, name: itemName }, 1);
    toast.success('Demande personnalisée ajoutée au panier');
    window.navigate('/cart');
  }

  return (
    <div className="container">
      <h1>Commande personnalisée</h1>
      <p>Décrivez votre demande de création personnelle. Choisissez une catégorie (ex: T-shirt, Mug...) et indiquez le texte ou les précisions.</p>
      <form onSubmit={submit} style={{ display:'grid', gridTemplateColumns:'1fr', gap:12, maxWidth: 600 }}>
        <label>Catégorie<br/>
          <select value={category} onChange={e=>setCategory(e.target.value)}>
            <option value="">— Choisir —</option>
            {categories.map(c => (
              <option key={c} value={Number.isInteger(priceMap[c]) ? c : ''} disabled={!Number.isInteger(priceMap[c])}>
                {c} {Number.isInteger(priceMap[c]) ? '' : '— non disponible'}
              </option>
            ))}
          </select>
        </label>
        <label>Votre texte / description<br/>
          <textarea rows="4" value={note} onChange={e=>setNote(e.target.value)} placeholder={'Des stickers avec des abeilles, ou avec autre chose ...'} />
        </label>
        {Number.isInteger(price) ? (
          <div style={{ color:'#444' }}>Prix indicatif: {euros(price)}</div>
        ) : (
          <div style={{ color:'#888' }}>Sélectionnez une catégorie avec tarif défini</div>
        )}
        <div>
          <button type="submit" disabled={!category || !Number.isInteger(price)}>
            {Number.isInteger(price) ? `Ajouter au panier (${euros(price)})` : 'Ajouter au panier'}
          </button>
        </div>
      </form>
    </div>
  );
}

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