// Composants partagés : Header, Footer, CartDrawer, PizzaCard, Toast

const { useState, useEffect, useRef } = React;

const BADGE_LABEL = {
  spicy: '🌶 Piquante',
  veg: 'Végé',
  nouveau: 'Nouveau',
  premium: 'Premium',
};

function PizzaCard({ pizza, onAdd }) {
  const [added, setAdded] = useState(false);
  const [showSaucePicker, setShowSaucePicker] = useState(false);
  const [pickedSauces, setPickedSauces] = useState([]);
  const eligible = itemHasSauce(pizza);

  const toggleSauce = (sid) => {
    setPickedSauces(arr => arr.includes(sid) ? arr.filter(x => x !== sid) : [...arr, sid]);
  };
  const handleAddDirect = () => {
    if (eligible) { setShowSaucePicker(true); setPickedSauces([]); return; }
    addToCart(pizza.id);
    setAdded(true);
    onAdd && onAdd(pizza);
    setTimeout(() => setAdded(false), 1400);
  };
  const confirmSauces = () => {
    addToCart(pizza.id, { sauceIds: pickedSauces });
    setShowSaucePicker(false);
    setPickedSauces([]);
    setAdded(true);
    onAdd && onAdd(pizza);
    setTimeout(() => setAdded(false), 1400);
  };
  const sauceExtra = pickedSauces.reduce((s, sid) => {
    const sa = SAUCES.find(x => x.id === sid);
    return s + (sa ? sa.price : 0);
  }, 0);
  return (
    <article className="pizza-card" data-cat={pizza.category}>
      <div className={`pizza-card-img cat-${pizza.category} ${pizza.photo ? 'has-photo' : ''}`}>
        {pizza.photo && (
          <img
            src={pizza.photo}
            alt={`${pizza.name} — ${pizza.ingredients} — Pizzeria ILYES Oran`}
            loading="lazy"
            width="400"
            height="400"
          />
        )}
        {pizza.badge && (
          <span className={`pizza-badge ${pizza.badge}`}>
            {BADGE_LABEL[pizza.badge] || pizza.badge}
          </span>
        )}
      </div>
      <div className="pizza-card-body">
        <div className="pizza-card-head">
          <div>
            <div className="pizza-name">{pizza.name}</div>
            <div style={{ fontFamily: 'var(--font-hand)', color: 'var(--fg-muted)', fontSize: 16, marginTop: 2 }}>
              {pizza.italianName}
            </div>
          </div>
          <div className="pizza-price">{formatPrice(pizza.price)}</div>
        </div>
        {!pizza.photo && <p className="pizza-ingredients">{pizza.ingredients}</p>}
        {showSaucePicker ? (
          <div className="sauce-picker">
            <div className="sauce-picker-title">
              Choisissez vos sauces
              <span className="sauce-picker-hint">(plusieurs possibles)</span>
            </div>
            <div className="sauce-picker-grid">
              {SAUCES.map(s => {
                const on = pickedSauces.includes(s.id);
                return (
                  <button key={s.id} className={`sauce-chip ${on ? 'on' : ''}`} onClick={() => toggleSauce(s.id)}>
                    <span className="sauce-check">{on ? '✓' : '+'}</span>
                    {s.label}{s.price > 0 && <span className="sauce-extra"> +{formatPrice(s.price)}</span>}
                  </button>
                );
              })}
            </div>
            <div className="sauce-picker-footer">
              <button className="sauce-cancel" onClick={() => { setShowSaucePicker(false); setPickedSauces([]); }}>Annuler</button>
              <button className="sauce-confirm" onClick={confirmSauces}>
                Ajouter {pickedSauces.length > 0 && `— ${pickedSauces.length} sauce${pickedSauces.length > 1 ? 's' : ''}`}
                {sauceExtra > 0 && ` (+${formatPrice(sauceExtra)})`}
              </button>
            </div>
          </div>
        ) : (
          <button className={`pizza-add ${added ? 'added' : ''}`} onClick={handleAddDirect}>
            {added ? <>✓ Ajouté</> : <>+ Ajouter au panier</>}
          </button>
        )}
      </div>
    </article>
  );
}

function Header({ activePage, onCartOpen }) {
  const [cart] = useCart();
  const [navOpen, setNavOpen] = useState(false);
  const count = cartCount(cart);
  return (
    <header className="header">
      <div className="header-inner">
        <nav className={`nav ${navOpen ? 'open' : ''}`}>
          <a href="index.html" className={activePage === 'home' ? 'active' : ''}>Accueil</a>
          <a href="menu.html" className={activePage === 'menu' ? 'active' : ''}>Menu</a>
          <a href="#contact">Contact</a>
        </nav>
        <button className="menu-toggle" onClick={() => setNavOpen(o => !o)} aria-label="Menu">
          ☰
        </button>
        <a href="index.html" className="logo-wrap">
          <img src="assets/logo.png" alt="Pizzeria ILYES" />
        </a>
        <div className="header-right">
          <a href="tel:0675558095" className="header-phone">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.37 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.33 1.85.57 2.81.7A2 2 0 0 1 22 16.92z"/>
            </svg>
            <span className="header-phone-text">0675 55 80 95</span>
          </a>
          <button className="cart-btn" onClick={onCartOpen}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2">
              <path d="M3 3h2l2.4 12.4a2 2 0 0 0 2 1.6h8.2a2 2 0 0 0 2-1.6L21 8H6"/>
              <circle cx="9" cy="20" r="1.4" fill="currentColor"/>
              <circle cx="18" cy="20" r="1.4" fill="currentColor"/>
            </svg>
            <span className="cart-btn-text">Panier</span>
            {count > 0 && <span className="cart-badge">{count}</span>}
          </button>
        </div>
      </div>
    </header>
  );
}

function Footer() {
  return (
    <footer className="footer" id="contact">
      <div className="footer-inner">
        <div className="footer-brand">
          <img src="assets/logo.png" alt="Pizzeria ILYES" />
        </div>
        <div>
          <h4>Visiter</h4>
          <ul>
            <li><a href="index.html">Accueil</a></li>
            <li><a href="menu.html">Notre menu</a></li>
          </ul>
        </div>
        <div>
          <h4>Horaires</h4>
          <ul>
            <li>Sam – Jeu : 11h – 00h</li>
            <li>Vendredi : 14h – 00h</li>
          </ul>
        </div>
        <div>
          <h4>Nous trouver</h4>
          <ul>
            <li>61 rue Mustapha Ben Boulaïd</li>
            <li>Oran, Algérie</li>
            <li><a href="tel:0675558095">📞 0675 55 80 95</a></li>
          </ul>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© 2026 Pizzeria ILYES — Tutti i diritti riservati · Fait avec passione 🍕</span>
      </div>
    </footer>
  );
}

function CartDrawer({ open, onClose }) {
  const [cart] = useCart();
  const [serviceMode, setServiceMode] = useServiceMode();
  const [editingSauceUid, setEditingSauceUid] = useState(null);
  const [checkoutOpen, setCheckoutOpen] = useState(false);
  const [confirmed, setConfirmed] = useState(false);
  const [orderInfo, setOrderInfo] = useState({ name: '', phone: '', district: '', table: '', notes: '' });
  const [orderNumber, setOrderNumber] = useState(null);

  useEffect(() => {
    if (!open) return;
    const handler = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', handler);
    return () => document.removeEventListener('keydown', handler);
  }, [open, onClose]);

  useEffect(() => {
    if (open) document.body.style.overflow = 'hidden';
    else document.body.style.overflow = '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  const subtotal = cartSubtotal(cart);
  const fee = serviceFee(serviceMode);
  const total = subtotal + fee;

  const toggleLineSauce = (uid, sauceId) => {
    const line = cart.find(l => l.uid === uid);
    if (!line) return;
    const current = lineSauces(line);
    const next = current.includes(sauceId)
      ? current.filter(x => x !== sauceId)
      : [...current, sauceId];
    setLineSauces(uid, next);
  };

  return (
    <>
      <div className={`cart-overlay ${open ? 'open' : ''}`} onClick={onClose} />
      <aside className={`cart-drawer ${open ? 'open' : ''}`} aria-hidden={!open}>
        <div className="cart-header">
          <h3>Votre panier</h3>
          <button className="cart-close" onClick={onClose} aria-label="Fermer">✕</button>
        </div>
        <div className="cart-items">
          {cart.length === 0 ? (
            <div className="cart-empty">
              <span className="script">Mamma mia !</span>
              <p>Votre panier est vide.<br/>Ajoutez quelques bonnes choses 🍕</p>
            </div>
          ) : cart.map(line => {
            const item = ITEMS.find(i => i.id === line.itemId);
            if (!item) return null;
            const sauceIds = lineSauces(line);
            const unit = lineUnitPrice(line);
            return (
              <div key={line.uid} className="cart-item">
                <div className={`cart-item-img cat-${item.category}`} />
                <div className="cart-item-info">
                  <div className="cart-item-name">{item.name}</div>
                  {itemHasSauce(item) && (
                    editingSauceUid === line.uid ? (
                      <div className="cart-sauce-edit-multi">
                        <div className="cart-sauce-multi-grid">
                          {SAUCES.map(s => {
                            const on = sauceIds.includes(s.id);
                            return (
                              <button key={s.id}
                                className={`sauce-chip ${on ? 'on' : ''}`}
                                onClick={() => toggleLineSauce(line.uid, s.id)}>
                                <span className="sauce-check">{on ? '✓' : '+'}</span>
                                {s.label}{s.price > 0 && <span className="sauce-extra"> +{formatPrice(s.price)}</span>}
                              </button>
                            );
                          })}
                        </div>
                        <button className="cart-sauce-done" onClick={() => setEditingSauceUid(null)}>Terminer</button>
                      </div>
                    ) : (
                      <button className="cart-sauce-btn" onClick={() => setEditingSauceUid(line.uid)}>
                        {sauceIds.length > 0 ? (
                          <>🥫 Sauces : <strong>{sauceIds.map(sid => (SAUCES.find(s => s.id === sid) || {}).label).filter(Boolean).join(', ')}</strong> <span className="edit-link">modifier</span></>
                        ) : (
                          <>🥫 <span className="add-sauce-link">+ Ajouter des sauces</span></>
                        )}
                      </button>
                    )
                  )}
                  <div className="cart-item-price">{formatPrice(unit)} × {line.qty} = <strong>{formatPrice(unit * line.qty)}</strong></div>
                </div>
                <div className="cart-item-controls">
                  <div className="qty-control">
                    <button className="qty-btn" onClick={() => setLineQuantity(line.uid, line.qty - 1)} aria-label="Diminuer">−</button>
                    <span className="qty-val">{line.qty}</span>
                    <button className="qty-btn" onClick={() => setLineQuantity(line.uid, line.qty + 1)} aria-label="Augmenter">+</button>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
        <div className="cart-footer">
          {cart.length > 0 && (
            <>
              <div className="service-mode">
                <div className="service-mode-label">Mode de service</div>
                <div className="service-mode-options">
                  {SERVICE_MODES.map(m => (
                    <button key={m.id}
                      className={`service-opt ${serviceMode === m.id ? 'active' : ''}`}
                      onClick={() => setServiceMode(m.id)}>
                      <span className="service-icon">{m.icon}</span>
                      <span>{m.label}</span>
                      {m.fee > 0 && <span className="service-fee">+{formatPrice(m.fee)}</span>}
                    </button>
                  ))}
                </div>
              </div>
              <div className="cart-totals">
                <div className="cart-line">
                  <span>Sous-total</span>
                  <span>{formatPrice(subtotal)}</span>
                </div>
                {fee > 0 && (
                  <div className="cart-line">
                    <span>Frais de livraison</span>
                    <span>{formatPrice(fee)}</span>
                  </div>
                )}
              </div>
            </>
          )}
          <div className="cart-total">
            <span className="cart-total-label">Total</span>
            <span className="cart-total-amount">{formatPrice(total)}</span>
          </div>
          <button className="cart-checkout" disabled={cart.length === 0} onClick={() => setCheckoutOpen(true)}>
            {cart.length === 0 ? 'Panier vide' : 'Passer commande'}
          </button>
        </div>
      </aside>

      {checkoutOpen && (
        <div className="checkout-overlay" onClick={() => !confirmed && setCheckoutOpen(false)}>
          <div className="checkout-modal" onClick={(e) => e.stopPropagation()}>
            {confirmed ? (
              <div className="checkout-success">
                <div className="success-circle">✓</div>
                <h3>Grazie mille !</h3>
                <p className="script">Votre commande est enregistrée</p>
                <p className="success-text">
                  Numéro de commande : <strong>{orderNumber}</strong><br/>
                  {serviceMode === 'livraison' && <>Livraison estimée : <strong>30–40 min</strong><br/>Nous vous appelons en arrivant.</>}
                  {serviceMode === 'emporter' && <>Prête à emporter dans <strong>15–20 min</strong><br/>Présentez votre numéro au comptoir.</>}
                  {serviceMode === 'sur-place' && <>Commande envoyée pour la <strong>table {orderInfo.table}</strong>.<br/>Nos équipes vous l'apportent !</>}
                </p>
                <button className="cart-checkout" onClick={() => {
                  localStorage.removeItem('pizzeria-ilyes-cart');
                  window.dispatchEvent(new CustomEvent('cart-changed'));
                  setConfirmed(false);
                  setOrderNumber(null);
                  setCheckoutOpen(false);
                  onClose();
                }}>Fermer</button>
              </div>
            ) : (
              <>
                <div className="checkout-header">
                  <h3>Récapitulatif de commande</h3>
                  <button className="cart-close" onClick={() => setCheckoutOpen(false)}>✕</button>
                </div>
                <div className="checkout-body">
                  <div className="checkout-section">
                    <h4>Vos articles</h4>
                    <ul className="checkout-list">
                      {cart.map(line => {
                        const it = ITEMS.find(i => i.id === line.itemId);
                        if (!it) return null;
                        return (
                          <li key={line.uid}>
                            <span>{line.qty}× {it.name}{lineSauces(line).length > 0 ? ` — sauces : ${lineSauces(line).map(sid => (SAUCES.find(x => x.id === sid) || {}).label).filter(Boolean).join(', ')}` : ''}</span>
                            <span>{formatPrice(lineUnitPrice(line) * line.qty)}</span>
                          </li>
                        );
                      })}
                    </ul>
                  </div>
                  <div className="checkout-section">
                    <h4>Mode : <strong>{(SERVICE_MODES.find(m => m.id === serviceMode) || {}).label}</strong></h4>
                  </div>
                  <div className="checkout-section">
                    <h4>{serviceMode === 'sur-place' ? 'Votre table' : 'Vos coordonnées'}</h4>
                    <div className="checkout-form">
                      {serviceMode === 'sur-place' ? (
                        <>
                          <input type="number" inputMode="numeric" placeholder="N° de table *" value={orderInfo.table}
                            onChange={(e) => setOrderInfo({...orderInfo, table: e.target.value})} />
                          <input type="text" placeholder="Nom (optionnel)" value={orderInfo.name}
                            onChange={(e) => setOrderInfo({...orderInfo, name: e.target.value})} />
                        </>
                      ) : serviceMode === 'livraison' ? (
                        <>
                          <input type="text" placeholder="Nom *" value={orderInfo.name}
                            onChange={(e) => setOrderInfo({...orderInfo, name: e.target.value})} />
                          <input type="tel" placeholder="Téléphone *" value={orderInfo.phone}
                            onChange={(e) => setOrderInfo({...orderInfo, phone: e.target.value})} />
                          <input type="text" placeholder="Quartier / commune *" value={orderInfo.district}
                            onChange={(e) => setOrderInfo({...orderInfo, district: e.target.value})} />
                        </>
                      ) : (
                        <>
                          <input type="text" placeholder="Nom *" value={orderInfo.name}
                            onChange={(e) => setOrderInfo({...orderInfo, name: e.target.value})} />
                          <input type="tel" placeholder="Téléphone (optionnel)" value={orderInfo.phone}
                            onChange={(e) => setOrderInfo({...orderInfo, phone: e.target.value})} />
                        </>
                      )}
                      <textarea placeholder="Instructions spéciales (optionnel)" value={orderInfo.notes}
                        onChange={(e) => setOrderInfo({...orderInfo, notes: e.target.value})} rows="2" />
                    </div>
                  </div>
                  <div className="checkout-totals">
                    <div className="cart-line"><span>Sous-total</span><span>{formatPrice(subtotal)}</span></div>
                    {fee > 0 && <div className="cart-line"><span>Frais de livraison</span><span>{formatPrice(fee)}</span></div>}
                    <div className="cart-line cart-line-total"><span>Total</span><span>{formatPrice(total)}</span></div>
                  </div>
                </div>
                <button
                  className="cart-checkout"
                  disabled={
                    serviceMode === 'sur-place' ? !orderInfo.table :
                    serviceMode === 'livraison' ? (!orderInfo.name || !orderInfo.phone || !orderInfo.district) :
                    !orderInfo.name
                  }
                  onClick={() => {
                    const newOrderNumber = 'ILY-' + Math.floor(1000 + Math.random() * 9000);
                    setOrderNumber(newOrderNumber);
                    setConfirmed(true);

                    // Construction du message WhatsApp
                    const lines = [];
                    lines.push('🍕 *NOUVELLE COMMANDE — Pizzeria ILYES*');
                    lines.push('');
                    lines.push('📋 N° : *' + newOrderNumber + '*');
                    lines.push('');
                    lines.push('🛒 *Articles :*');
                    cart.forEach(line => {
                      const item = ITEMS.find(i => i.id === line.itemId);
                      if (!item) return;
                      const unit = lineUnitPrice(line);
                      lines.push('• ' + item.name + ' × ' + line.qty + ' — ' + formatPrice(unit * line.qty));
                      const sauceIds = lineSauces(line);
                      if (sauceIds.length > 0) {
                        const sauceNames = sauceIds.map(sid => (SAUCES.find(s => s.id === sid) || {}).label).filter(Boolean).join(', ');
                        lines.push('   Sauces : ' + sauceNames);
                      }
                    });
                    lines.push('');
                    if (serviceMode === 'sur-place') {
                      lines.push('🍽️ *Mode : Sur place*');
                      lines.push('Table : *' + orderInfo.table + '*');
                    } else if (serviceMode === 'a-emporter') {
                      lines.push('🥡 *Mode : À emporter*');
                      lines.push('Client : ' + orderInfo.name);
                      if (orderInfo.phone) lines.push('Téléphone : ' + orderInfo.phone);
                    } else if (serviceMode === 'livraison') {
                      lines.push('🛵 *Mode : Livraison*');
                      lines.push('Client : ' + orderInfo.name);
                      lines.push('Téléphone : ' + orderInfo.phone);
                      lines.push('Quartier : ' + orderInfo.district);
                    }
                    lines.push('');
                    lines.push('💰 Sous-total : ' + formatPrice(subtotal));
                    if (fee > 0) lines.push('🛵 Livraison : ' + formatPrice(fee));
                    lines.push('💰 *TOTAL : ' + formatPrice(total) + '*');
                    if (orderInfo.notes && orderInfo.notes.trim()) {
                      lines.push('');
                      lines.push('📝 Notes : ' + orderInfo.notes);
                    }

                    const message = encodeURIComponent(lines.join('\n'));
                    const whatsappURL = 'https://wa.me/213771787473?text=' + message;

                    // Ouvre WhatsApp dans un nouvel onglet (mobile = app, desktop = web)
                    window.open(whatsappURL, '_blank');
                  }}>
                  Confirmer la commande — {formatPrice(total)}
                </button>
              </>
            )}
          </div>
        </div>
      )}
    </>
  );
}

function Toast({ message, show }) {
  return (
    <div className={`toast ${show ? 'show' : ''}`}>
      <span>✓</span> {message}
    </div>
  );
}

function useToast() {
  const [toast, setToast] = useState({ message: '', show: false });
  const timerRef = useRef();
  const showToast = (message) => {
    setToast({ message, show: true });
    clearTimeout(timerRef.current);
    timerRef.current = setTimeout(() => setToast(t => ({ ...t, show: false })), 2200);
  };
  return [toast, showToast];
}

Object.assign(window, {
  PizzaCard, Header, Footer, CartDrawer, Toast, useToast,
});
