// Product modal + Cart drawer

const { useState: useStateM, useEffect: useEffectM } = React;

function ProductModal({ product, onClose, onAddToCart }) {
  const [ribbon, setRibbon] = useStateM('');
  const [qty, setQty] = useStateM(1);
  useEffectM(() => {
    if (product) {
      document.body.style.overflow = 'hidden';
      setRibbon('');
      setQty(1);
    } else {
      document.body.style.overflow = '';
    }
    return () => { document.body.style.overflow = ''; };
  }, [product]);

  if (!product) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 md:p-10 animate-fadeIn">
      <div className="absolute inset-0" style={{ background: 'rgba(12, 14, 28, 0.55)', backdropFilter: 'blur(8px)' }} onClick={onClose} />
      <div className="relative w-full max-w-5xl max-h-[92vh] overflow-y-auto grid md:grid-cols-2 animate-fadeInUp" style={{ background: 'var(--surface-container-lowest)' }}>
        <button onClick={onClose} className="absolute top-4 right-4 z-10 w-10 h-10 flex items-center justify-center hover:opacity-70 transition-opacity" style={{ background: 'var(--surface-container-lowest)' }}>
          <Icon name="close" />
        </button>
        <div className="aspect-[4/5] md:aspect-auto overflow-hidden" style={{ background: 'var(--surface-container-low)' }}>
          <img src={product.img} alt={product.name} className="w-full h-full object-cover" />
        </div>
        <div className="p-8 md:p-12 flex flex-col">
          <p className="uppercase tracking-widest text-[10px] mb-4" style={{ color: 'var(--primary)' }}>{product.category}</p>
          <h2 className="font-serif text-4xl md:text-5xl mb-6 leading-tight" style={{ color: 'var(--on-surface)' }}>{product.name}</h2>
          <p className="leading-relaxed mb-8" style={{ color: 'var(--on-surface-variant)' }}>{product.description}</p>
          <div className="space-y-4 mb-8 text-sm">
            <div className="flex justify-between">
              <span className="uppercase tracking-widest text-[10px]" style={{ color: 'var(--on-surface-variant)' }}>Coloris</span>
              <span style={{ color: 'var(--on-surface)' }}>{product.colors.join(' · ')}</span>
            </div>
            <div className="flex justify-between">
              <span className="uppercase tracking-widest text-[10px]" style={{ color: 'var(--on-surface-variant)' }}>Occasion</span>
              <span style={{ color: 'var(--on-surface)' }}>{product.occasion}</span>
            </div>
            <div className="flex justify-between">
              <span className="uppercase tracking-widest text-[10px]" style={{ color: 'var(--on-surface-variant)' }}>Livraison</span>
              <span style={{ color: 'var(--on-surface)' }}>Grand Lyon en 4h</span>
            </div>
          </div>

          <div className="mb-6">
            <label className="block uppercase tracking-widest text-[10px] mb-2" style={{ color: 'var(--primary)' }}>Message de ruban <span style={{ color: 'var(--on-surface-variant)' }}>(optionnel)</span></label>
            <input
              value={ribbon}
              onChange={e => setRibbon(e.target.value)}
              maxLength={60}
              placeholder="À notre cher Papa, avec toute notre tendresse"
              className="w-full px-4 py-3 text-sm focus:outline-none transition-colors"
              style={{ background: 'var(--surface-container-low)', color: 'var(--on-surface)', borderBottom: '1px solid transparent' }}
              onFocus={e => e.target.style.borderBottom = '1px solid var(--primary)'}
              onBlur={e => e.target.style.borderBottom = '1px solid transparent'}
            />
            <p className="mt-1 text-[10px]" style={{ color: 'var(--on-surface-variant)' }}>{ribbon.length}/60</p>
          </div>

          <div className="flex items-center gap-4 mb-8">
            <div className="flex items-center" style={{ background: 'var(--surface-container-low)' }}>
              <button onClick={() => setQty(Math.max(1, qty - 1))} className="w-10 h-10 hover:opacity-60" style={{ color: 'var(--on-surface)' }}>−</button>
              <span className="w-10 text-center font-medium" style={{ color: 'var(--on-surface)' }}>{qty}</span>
              <button onClick={() => setQty(qty + 1)} className="w-10 h-10 hover:opacity-60" style={{ color: 'var(--on-surface)' }}>+</button>
            </div>
            <span className="font-serif text-2xl" style={{ color: 'var(--on-surface)' }}>{(product.price * qty).toFixed(2).replace('.', ',')} €</span>
          </div>

          <button
            onClick={() => { onAddToCart(product, qty, ribbon); onClose(); }}
            className="w-full py-4 text-xs uppercase tracking-widest font-medium transition-opacity hover:opacity-90"
            style={{ background: 'var(--primary)', color: 'var(--on-primary)' }}
          >
            Ajouter au panier
          </button>
          <p className="text-[10px] text-center mt-4 uppercase tracking-widest" style={{ color: 'var(--on-surface-variant)' }}>Paiement sécurisé · Livraison discrète</p>
        </div>
      </div>
    </div>
  );
}

function CartDrawer({ open, onClose, cart, removeItem, updateQty }) {
  useEffectM(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  const total = cart.reduce((s, i) => s + i.product.price * i.qty, 0);

  return (
    <div className={`fixed inset-0 z-50 ${open ? '' : 'pointer-events-none'}`}>
      <div
        className="absolute inset-0 transition-opacity duration-500"
        style={{ background: 'rgba(12, 14, 28, 0.4)', opacity: open ? 1 : 0 }}
        onClick={onClose}
      />
      <aside
        className="absolute top-0 right-0 h-full w-full max-w-md flex flex-col transition-transform duration-500"
        style={{ background: 'var(--surface-container-lowest)', transform: open ? 'translateX(0)' : 'translateX(100%)' }}
      >
        <div className="flex items-center justify-between px-8 py-6">
          <div>
            <p className="uppercase tracking-widest text-[10px]" style={{ color: 'var(--primary)' }}>Votre sélection</p>
            <h3 className="font-serif text-2xl" style={{ color: 'var(--on-surface)' }}>Panier</h3>
          </div>
          <button onClick={onClose} className="hover:opacity-60"><Icon name="close" /></button>
        </div>

        <div className="flex-1 overflow-y-auto px-8">
          {cart.length === 0 ? (
            <div className="h-full flex flex-col items-center justify-center text-center py-20">
              <Icon name="shopping_basket" className="text-5xl mb-6" style={{ color: 'var(--primary)', opacity: 0.4 }} />
              <p className="font-serif text-lg mb-2" style={{ color: 'var(--on-surface)' }}>Votre panier est vide</p>
              <p className="text-sm max-w-xs" style={{ color: 'var(--on-surface-variant)' }}>Découvrez nos créations florales pour honorer la mémoire d'un proche.</p>
            </div>
          ) : (
            <div className="space-y-6 pb-6">
              {cart.map((item, idx) => (
                <div key={idx} className="flex gap-4 pb-6" style={{ borderBottom: idx < cart.length - 1 ? '1px solid color-mix(in srgb, var(--on-surface) 6%, transparent)' : 'none' }}>
                  <div className="w-20 h-24 flex-shrink-0 overflow-hidden" style={{ background: 'var(--surface-container-low)' }}>
                    <img src={item.product.img} alt="" className="w-full h-full object-cover" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="uppercase tracking-widest text-[9px] mb-1" style={{ color: 'var(--primary)' }}>{item.product.category}</p>
                    <p className="font-serif text-base mb-1" style={{ color: 'var(--on-surface)' }}>{item.product.name}</p>
                    {item.ribbon && <p className="text-[11px] italic mb-2 line-clamp-1" style={{ color: 'var(--on-surface-variant)' }}>"{item.ribbon}"</p>}
                    <div className="flex items-center justify-between mt-2">
                      <div className="flex items-center text-xs" style={{ background: 'var(--surface-container-low)' }}>
                        <button onClick={() => updateQty(idx, Math.max(1, item.qty - 1))} className="w-7 h-7 hover:opacity-60">−</button>
                        <span className="w-6 text-center">{item.qty}</span>
                        <button onClick={() => updateQty(idx, item.qty + 1)} className="w-7 h-7 hover:opacity-60">+</button>
                      </div>
                      <span className="font-serif text-sm" style={{ color: 'var(--on-surface)' }}>{(item.product.price * item.qty).toFixed(2).replace('.', ',')} €</span>
                    </div>
                  </div>
                  <button onClick={() => removeItem(idx)} className="self-start hover:opacity-60">
                    <Icon name="close" className="text-base" style={{ color: 'var(--on-surface-variant)' }} />
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>

        {cart.length > 0 && (
          <div className="px-8 py-6 space-y-4" style={{ background: 'var(--surface-container-low)' }}>
            <div className="flex justify-between items-baseline">
              <span className="uppercase tracking-widest text-[10px]" style={{ color: 'var(--on-surface-variant)' }}>Sous-total</span>
              <span className="font-serif text-2xl" style={{ color: 'var(--on-surface)' }}>{total.toFixed(2).replace('.', ',')} €</span>
            </div>
            <p className="text-[11px]" style={{ color: 'var(--on-surface-variant)' }}>Livraison Grand Lyon en 4h incluse</p>
            <button onClick={() => { window.location.href = '/shop/'; }} className="w-full py-4 text-xs uppercase tracking-widest font-medium transition-opacity hover:opacity-90" style={{ background: 'var(--primary)', color: 'var(--on-primary)' }}>
              Finaliser la commande
            </button>
          </div>
        )}
      </aside>
    </div>
  );
}

Object.assign(window, { ProductModal, CartDrawer });
