// cart.jsx — Cart drawer with checkout form
const { useState: useStateCart } = React;

function CartLine({ item, onMinus, onPlus, onRemove }) {
  const total = (item.price * item.qty).toFixed(2).replace('.', ',');
  return (
    <div className="fp-cart__line">
      <div className="fp-cart__line-name">
        <b>{item.name}</b>
        {item.size && <span> · {item.size}</span>}
        <em>{item.price.toFixed(2).replace('.', ',')}€ / unité</em>
      </div>
      <div className="fp-cart__qty">
        <button onClick={onMinus} aria-label="moins">−</button>
        <span>{item.qty}</span>
        <button onClick={onPlus} aria-label="plus">+</button>
      </div>
      <div className="fp-cart__line-tot">
        {total}€
      </div>
      <button className="fp-cart__line-x" onClick={onRemove} aria-label="retirer">×</button>
    </div>
  );
}

function CheckoutForm({ total, submitting, onSubmit }) {
  const [name, setName] = useStateCart('');
  const [phone, setPhone] = useStateCart('');
  const [type, setType] = useStateCart('takeaway');
  const [address, setAddress] = useStateCart('');
  const [notes, setNotes] = useStateCart('');

  const handle = (e) => {
    e.preventDefault();
    if (!name.trim() || !phone.trim()) return;
    if (type === 'delivery' && !address.trim()) return;
    onSubmit({
      type,
      customerName: name.trim(),
      customerPhone: phone.trim(),
      customerAddress: type === 'delivery' ? address.trim() : null,
      notes: notes.trim() || null,
    });
  };

  const inputStyle = {
    width: '100%',
    padding: '10px 12px',
    border: '1px solid var(--dim, #6b5d4f)',
    borderRadius: 8,
    fontSize: 14,
    fontFamily: 'inherit',
    background: 'var(--paper, #fdfaf3)',
    color: 'var(--ink, #1a1410)',
    boxSizing: 'border-box',
  };
  const labelStyle = {
    display: 'block',
    fontSize: 12,
    fontWeight: 600,
    marginBottom: 4,
    color: 'var(--ink, #1a1410)',
  };

  return (
    <form onSubmit={handle} style={{ padding: '0 16px 16px', display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div>
        <label style={labelStyle}>Nom *</label>
        <input
          style={inputStyle}
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          required
          disabled={submitting}
        />
      </div>
      <div>
        <label style={labelStyle}>Téléphone *</label>
        <input
          style={inputStyle}
          type="tel"
          value={phone}
          onChange={(e) => setPhone(e.target.value)}
          required
          disabled={submitting}
        />
      </div>
      <div>
        <label style={labelStyle}>Mode</label>
        <div style={{ display: 'flex', gap: 8 }}>
          <label style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 6, padding: '8px 12px', border: '1px solid var(--dim, #6b5d4f)', borderRadius: 8, cursor: 'pointer', background: type === 'takeaway' ? 'var(--cream, #f6efe4)' : 'transparent' }}>
            <input type="radio" name="fp-type" value="takeaway" checked={type === 'takeaway'} onChange={() => setType('takeaway')} disabled={submitting} />
            <span style={{ fontSize: 13 }}>À emporter</span>
          </label>
          <label style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 6, padding: '8px 12px', border: '1px solid var(--dim, #6b5d4f)', borderRadius: 8, cursor: 'pointer', background: type === 'delivery' ? 'var(--cream, #f6efe4)' : 'transparent' }}>
            <input type="radio" name="fp-type" value="delivery" checked={type === 'delivery'} onChange={() => setType('delivery')} disabled={submitting} />
            <span style={{ fontSize: 13 }}>Livraison</span>
          </label>
        </div>
      </div>
      {type === 'delivery' && (
        <div>
          <label style={labelStyle}>Adresse *</label>
          <input
            style={inputStyle}
            type="text"
            value={address}
            onChange={(e) => setAddress(e.target.value)}
            required
            disabled={submitting}
          />
        </div>
      )}
      <div>
        <label style={labelStyle}>Notes (optionnel)</label>
        <textarea
          style={{ ...inputStyle, minHeight: 60, resize: 'vertical' }}
          value={notes}
          onChange={(e) => setNotes(e.target.value)}
          disabled={submitting}
        />
      </div>
      <button
        type="submit"
        className="fp-btn fp-btn--primary fp-btn--full fp-btn--lg"
        disabled={submitting}
        style={submitting ? { opacity: 0.6, cursor: 'wait' } : undefined}
      >
        {submitting ? 'Envoi…' : `Commander · ${total.toFixed(2).replace('.', ',')}€`}
      </button>
    </form>
  );
}

function CartDrawer({ open, items, onClose, onMinus, onPlus, onRemove, onCheckout, submitting, lastResult }) {
  const subtotal = items.reduce((s, i) => s + i.price * i.qty, 0);
  const delivery = subtotal >= 20 || subtotal === 0 ? 0 : 3;
  const total = subtotal + delivery;
  const toFree = Math.max(0, 20 - subtotal);
  const pct = subtotal === 0 ? 0 : Math.min(100, (subtotal / 20) * 100);

  return (
    <>
      <div className={`fp-cart__scrim ${open ? 'is-open' : ''}`} onClick={onClose} />
      <aside className={`fp-cart ${open ? 'is-open' : ''}`} aria-hidden={!open}>
        <header className="fp-cart__hd">
          <span className="fp-eyebrow">Ta commande</span>
          <h2 className="fp-cart__title">
            {items.length === 0 ? <>Encore <em>vide.</em></> : <>{items.length} article{items.length > 1 ? 's' : ''}<em>, prêt·e ?</em></>}
          </h2>
          <button className="fp-cart__close" onClick={onClose} aria-label="fermer">×</button>
        </header>

        {lastResult && lastResult.kind === 'success' && (
          <div style={{ margin: 16, padding: 16, background: '#d4edda', color: '#155724', borderRadius: 8, border: '1px solid #c3e6cb' }}>
            <b>Commande envoyée ! 🎉</b>
            <div style={{ fontSize: 13, marginTop: 4 }}>
              Numéro #{lastResult.orderId.slice(-6).toUpperCase()} · {lastResult.total.toFixed(2).replace('.', ',')}€
            </div>
            <div style={{ fontSize: 12, marginTop: 6, opacity: 0.85 }}>
              Tu peux fermer cette fenêtre. Le restaurant l'a reçue.
            </div>
          </div>
        )}

        {lastResult && lastResult.kind === 'error' && (
          <div style={{ margin: 16, padding: 12, background: '#f8d7da', color: '#721c24', borderRadius: 8, border: '1px solid #f5c6cb', fontSize: 13 }}>
            <b>Erreur :</b> {lastResult.message}
          </div>
        )}

        {items.length === 0 ? (
          <div className="fp-cart__empty">
            <p>Ton panier est encore tout chaud<br/>(parce qu'il est vide).</p>
            <button className="fp-btn fp-btn--dark" onClick={onClose}>Choisir une pizza →</button>
          </div>
        ) : (
          <>
            <div className="fp-cart__progress">
              <div className="fp-cart__progress-bar" style={{ width: `${pct}%` }} />
              <span className="fp-cart__progress-lbl">
                {toFree > 0
                  ? <>Plus que <b>{toFree.toFixed(2).replace('.', ',')}€</b> pour la livraison gratuite.</>
                  : <><b>Livraison gratuite</b> activée 🎉</>}
              </span>
            </div>

            <div className="fp-cart__lines">
              {items.map(item => (
                <CartLine
                  key={item.id}
                  item={item}
                  onMinus={() => onMinus(item.id)}
                  onPlus={() => onPlus(item.id)}
                  onRemove={() => onRemove(item.id)}
                />
              ))}
            </div>

            <div className="fp-cart__totals" style={{ padding: '0 16px' }}>
              <div><span>Sous-total</span><span>{subtotal.toFixed(2).replace('.', ',')}€</span></div>
              <div><span>Livraison</span><span>{delivery === 0 ? 'Gratuite' : `${delivery.toFixed(2).replace('.', ',')}€`}</span></div>
              <div className="fp-cart__totals-grand"><span>Total</span><span>{total.toFixed(2).replace('.', ',')}€</span></div>
            </div>

            <CheckoutForm
              total={total}
              submitting={submitting}
              onSubmit={onCheckout}
            />
          </>
        )}
      </aside>
    </>
  );
}

window.CartDrawer = CartDrawer;
