function euros(c) {
  try {
    return new Intl.NumberFormat('fr-FR', { style: 'currency', currency: 'EUR' }).format((c || 0) / 100);
  } catch {
    return (c / 100).toFixed(2) + '€';
  }
}

function ProductModal({ product, open, onClose }) {
  const { addItem } = window.CartContext.useCart();
  const [variationId, setVariationId] = React.useState(undefined);
  const [qty, setQty] = React.useState(1);
  const [selectedOptionIds, setSelectedOptionIds] = React.useState([]);

  React.useEffect(() => {
    if (!open) return;
    // Default variation selection
    if (Array.isArray(product.variations) && product.variations.length > 0) {
      setVariationId(product.variations[0].id);
    } else {
      setVariationId(undefined);
    }
    // Reset qty and options on open
    setQty(1);
    setSelectedOptionIds([]);
  }, [open, product.id]);

  // Gallery state (ensure images are consistently sorted by sort_index)
  const images = (() => {
    if (Array.isArray(product.images) && product.images.length > 0) {
      const arr = [...product.images];
      arr.sort((a, b) => (Number(a.sort_index) || 0) - (Number(b.sort_index) || 0) || (Number(a.id) || 0) - (Number(b.id) || 0));
      return arr;
    }
    return product.image_url ? [{ id: 'main', url: product.image_url, sort_index: 0 }] : [];
  })();
  const [activeIndex, setActiveIndex] = React.useState(0);
  React.useEffect(()=>{ setActiveIndex(0); }, [product.id, open]);

  // Compute current unit price with options
  const basePrice = (() => {
    const v = Array.isArray(product.variations) ? product.variations.find(x=>x.id===variationId) : null;
    return (v && v.price_cents != null ? v.price_cents : product.price_cents) || 0;
  })();
  const options = Array.isArray(product.options) ? product.options : [];
  const optionsTotal = options.filter(o=>selectedOptionIds.includes(o.id)).reduce((a,b)=>a + (b.price_cents||0), 0);
  const unitPrice = basePrice + optionsTotal;

  function toggleOption(id) {
    setSelectedOptionIds(prev => prev.includes(id) ? prev.filter(x=>x!==id) : [...prev, id]);
  }

  function doAddToCart() {
    const selectedOptions = options.filter(o=>selectedOptionIds.includes(o.id)).map(o=>({ id: o.id, name: o.name, price_cents: o.price_cents }));
    const entry = variationId
      ? { ...product, id: product.id, price_cents: unitPrice, name: product.name + ' - ' + (product.variations.find(v=>v.id===variationId)?.name || '') }
      : { ...product, price_cents: unitPrice };
    addItem({ ...entry, variationId }, qty, selectedOptions);
    onClose && onClose();
  }

  if (!open) return null;
  const imgUrl = images[activeIndex]?.url || product.image_url || '/images/placeholder.svg';
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e)=>e.stopPropagation()} style={{ maxWidth: 900 }}>
        <div className="modal-header">
          <h3>{product.name}</h3>
          <button onClick={onClose} aria-label="Fermer">×</button>
        </div>
        <div className="modal-body" style={{ display:'grid', gridTemplateColumns:'1.2fr 1fr', gap:16 }}>
          <div>
            <div style={{ width:'100%', aspectRatio:'1.2', border:'1px solid var(--brand-border)', borderRadius:8, overflow:'hidden' }}>
              <img src={imgUrl} alt={product.name} style={{ width:'100%', height:'100%', objectFit:'cover' }} onError={(e)=>{ e.currentTarget.src='/images/placeholder.svg'; }} />
            </div>
            {images.length>1 && (
              <div style={{ display:'flex', gap:8, marginTop:8, overflowX:'auto', paddingBottom:6 }}>
                {images.map((im, idx)=> (
                  <img key={im.id||idx} src={im.url} alt="" width="64" height="64" style={{ objectFit:'cover', borderRadius:6, border: idx===activeIndex?'2px solid #2563eb':'1px solid #eee', cursor:'pointer' }} onClick={()=>setActiveIndex(idx)} onError={(e)=>{ e.currentTarget.src='/images/placeholder.svg'; }} />
                ))}
              </div>
            )}
          </div>
          <div>
            {product.description && <p style={{ color:'var(--brand-muted)' }}>{product.description}</p>}
            {Array.isArray(product.variations) && product.variations.length > 0 && (
              <div style={{ marginBottom:8 }}>
                <label>Variante
                  <select value={variationId ?? ''} onChange={e=>setVariationId(e.target.value?Number(e.target.value):undefined)} style={{ marginLeft:8 }}>
                    {product.variations.map(v => (
                      <option key={v.id} value={v.id}>{v.name} {v.price_cents!=null?`(${euros(v.price_cents)})`:''}</option>
                    ))}
                  </select>
                </label>
              </div>
            )}
            {options.length>0 && (
              <div style={{ margin:'8px 0' }}>
                <div style={{ fontWeight:600, marginBottom:6 }}>Options</div>
                <div style={{ display:'grid', gap:6 }}>
                  {options.map(opt => (
                    <label key={opt.id} style={{ display:'flex', alignItems:'center', gap:8 }}>
                      <input type="checkbox" checked={selectedOptionIds.includes(opt.id)} onChange={()=>toggleOption(opt.id)} />
                      <span>{opt.name} {opt.price_cents ? <i style={{ color:'#666' }}>+{euros(opt.price_cents)}</i> : ''}</span>
                    </label>
                  ))}
                </div>
              </div>
            )}
            <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginTop:8 }}>
              <div>
                <div style={{ fontSize:12, color:'#666' }}>Prix unitaire</div>
                <div style={{ fontWeight:800, fontSize:20 }}>{euros(unitPrice)}</div>
              </div>
              <window.Components.QuantitySelector value={qty} onChange={setQty} />
              <button onClick={doAddToCart}>Ajouter au panier</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.Components = window.Components || {};
window.Components.ProductModal = ProductModal;
