/* cart.jsx — Carrito flotante, modal de carrito, detalle de producto, checkout */

// ── Floating cart pill ───────────────────────────────────────────
const FloatingCart = ({ count, total, onOpen }) => {
  if (count === 0) return null;
  return (
    <button className="floating-cart" onClick={onOpen}>
      <span className="floating-cart__icon">
        <svg width="18" height="18" viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="0.9">
          <path d="M3 5 H15 L13.5 13 H4.5 Z" />
          <path d="M6 5 V3.5 C6 2 7 1.5 9 1.5 C11 1.5 12 2 12 3.5 V5" />
        </svg>
      </span>
      <span>Mi pedido</span>
      <span className="floating-cart__count">{count}</span>
      <span className="floating-cart__divider" />
      <span className="floating-cart__total">{cop(total)}</span>
    </button>
  );
};

// ── Cart side modal ──────────────────────────────────────────────
const CartModal = ({ open, items, onClose, onUpdateQty, onRemove, onCheckout, total }) => (
  <>
    <div className={`modal-backdrop ${open ? 'is-open' : ''}`} onClick={onClose} />
    <aside className={`cart-modal ${open ? 'is-open' : ''}`}>
      <header className="cart-modal__head">
        <div>
          <span className="cart-modal__eyebrow">— Mon panier —</span>
          <h2 className="cart-modal__title">Mi pedido</h2>
        </div>
        <button className="cart-modal__close" onClick={onClose} aria-label="Cerrar">✕</button>
      </header>
      <div className="cart-modal__items">
        {items.length === 0 ? (
          <div className="cart-modal__empty">
            <Logo size={64} />
            <div className="display" style={{ marginTop: 32 }}>Tu carrito está vacío</div>
            <p>Pasa por la carta y elige algo. Te lo preparamos al momento.</p>
          </div>
        ) : items.map((item) => (
          <div key={item.uid} className="cart-modal__item">
            <div className="cart-modal__item-media">
              <ImgSlot tone={item.img} label="" icon={false} />
            </div>
            <div>
              <h4 className="cart-modal__item-title">{item.name}</h4>
              {item.variantLabel && <div className="cart-modal__item-mods">{item.variantLabel}</div>}
              {item.modLabels?.length > 0 && (
                <div className="cart-modal__item-mods">+ {item.modLabels.join(' · ')}</div>
              )}
              <div className="cart-modal__qty">
                <button onClick={() => onUpdateQty(item.uid, item.qty - 1)}>−</button>
                <span>{item.qty}</span>
                <button onClick={() => onUpdateQty(item.uid, item.qty + 1)}>+</button>
              </div>
            </div>
            <div>
              <div className="cart-modal__item-price">{cop(item.unitPrice * item.qty)}</div>
              <button className="cart-modal__remove" onClick={() => onRemove(item.uid)}>Eliminar</button>
            </div>
          </div>
        ))}
      </div>
      {items.length > 0 && (
        <footer className="cart-modal__foot">
          <div className="cart-modal__totals">
            <div className="cart-modal__totals-row">
              <span>Subtotal</span>
              <span>{cop(total)}</span>
            </div>
            <div className="cart-modal__totals-row">
              <span>Domicilio</span>
              <span>se calcula al finalizar</span>
            </div>
            <div className="cart-modal__totals-row cart-modal__totals-row--big">
              <span>Total</span>
              <span>{cop(total)}</span>
            </div>
          </div>
          <button className="btn btn--lg" style={{ width: '100%' }} onClick={onCheckout}>Finalizar pedido</button>
        </footer>
      )}
    </aside>
  </>
);

// ── Detail modal ─────────────────────────────────────────────────
const DetailModal = ({ product, open, onClose, onAdd }) => {
  const [variantId, setVariantId] = React.useState(null);
  const [modIds, setModIds] = React.useState([]);
  const [qty, setQty] = React.useState(1);
  const [mods, setMods] = React.useState([]);

  React.useEffect(() => {
    if (product) {
      setVariantId(product.variants[0]?.id || null);
      setModIds([]);
      setQty(1);
      setMods([]);
      // Carga perezosa de modificadores reales (leche de avena, salsa extra, etc.)
      if (product.hasMods && window.loadProductMods) {
        window.loadProductMods(product.id).then((m) => setMods(m || []));
      }
    }
  }, [product]);

  if (!product) return null;
  const sello = product.sellos[0];
  const variant = product.variants.find((v) => v.id === variantId);
  const basePrice = variant ? variant.price : product.price;
  const modsTotal = mods.filter((m) => modIds.includes(m.id)).reduce((s, m) => s + m.price, 0);
  const unitPrice = basePrice + modsTotal;
  const lineTotal = unitPrice * qty;

  const toggleMod = (id) => setModIds((prev) => prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]);

  const handleAdd = () => {
    onAdd({
      productId: product.id,
      name: product.name,
      img: product.img,
      variantId,
      variantLabel: variant?.label || null,
      modIds,
      modLabels: mods.filter((m) => modIds.includes(m.id)).map((m) => m.label),
      unitPrice,
      qty,
    });
    onClose();
  };

  return (
    <>
      <div className={`modal-backdrop ${open ? 'is-open' : ''}`} onClick={onClose} />
      <div className={`detail-modal ${open ? 'is-open' : ''}`}>
        <div className="detail-modal__media">
          <ImgSlot tone={product.img} label={product.name} sub="Foto del producto · 1:1" icon={false} />
        </div>
        <div className="detail-modal__body">
          <button className="detail-modal__close" onClick={onClose} aria-label="Cerrar">✕</button>
          {sello && <Sello solo>— {SELLOS[sello].fr || SELLOS[sello].label} —</Sello>}
          <h2 className="detail-modal__title">{product.name}</h2>
          <p className="detail-modal__desc">{product.desc}</p>
          <div className="detail-modal__price">{cop(basePrice)}</div>

          {product.variants.length > 0 && (
            <>
              <h4>Presentación</h4>
              <div className="detail-modal__variants">
                {product.variants.map((v) => (
                  <button
                    key={v.id}
                    className={`detail-variant ${variantId === v.id ? 'is-on' : ''}`}
                    onClick={() => setVariantId(v.id)}
                  >
                    {v.label} · {cop(v.price)}
                  </button>
                ))}
              </div>
            </>
          )}

          {mods.length > 0 && (
            <>
              <h4>Acompañar con</h4>
              <div className="detail-modal__mods">
                {mods.map((m) => (
                  <label key={m.id}>
                    <input
                      type="checkbox"
                      checked={modIds.includes(m.id)}
                      onChange={() => toggleMod(m.id)}
                    />
                    <span>{m.label}</span>
                    <span className="price">+ {cop(m.price)}</span>
                  </label>
                ))}
              </div>
            </>
          )}

          <div className="detail-modal__actions">
            <div className="detail-modal__qty">
              <button onClick={() => setQty(Math.max(1, qty - 1))}>−</button>
              <span>{qty}</span>
              <button onClick={() => setQty(qty + 1)}>+</button>
            </div>
            <button className="btn" onClick={handleAdd}>
              Añadir · {cop(lineTotal)}
            </button>
          </div>
        </div>
      </div>
    </>
  );
};

// ── Checkout modal (cableado al backend real) ───────────────────
const ORDER_TYPES = [
  { id: 'delivery', label: 'A Domicilio',       sub: 'Te lo llevamos' },
  { id: 'eat_in',   label: 'En el Restaurante', sub: 'Consumo en el local' },
  { id: 'takeaway', label: 'Para Recoger',      sub: 'Pasas por él' },
];
const PAY_METHODS = ['Efectivo', 'Tarjeta de Crédito', 'Tarjeta de Débito', 'Nequi / Daviplata', 'Transferencia Bancaria'];
const ID_TYPES = [
  { v: 'CC', l: 'Cédula de Ciudadanía' }, { v: 'CE', l: 'Cédula de Extranjería' },
  { v: 'NIT', l: 'NIT' }, { v: 'PAS', l: 'Pasaporte' }, { v: 'TI', l: 'Tarjeta de Identidad' },
];

const CheckoutModal = ({ open, onClose, items, total, onComplete }) => {
  const [f, setF] = React.useState({
    name: '', idType: 'CC', idNumber: '', cc: '+57', phone: '', email: '',
    orderType: 'delivery', address: '', notes: '', payment: 'Efectivo',
  });
  const [proof, setProof] = React.useState(null);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');
  if (!open) return null;

  const set = (k) => (e) => setF((p) => ({ ...p, [k]: e.target.value }));
  const isDelivery = f.orderType === 'delivery';
  const isTransfer = f.payment === 'Transferencia Bancaria';

  const submit = async (e) => {
    e.preventDefault();
    setErr('');
    if (!f.name || !f.idNumber || !f.phone || !f.email) { setErr('Completa nombre, documento, teléfono y correo.'); return; }
    if (isDelivery && !f.address.trim()) { setErr('Indica la dirección de entrega.'); return; }
    if (isTransfer && !proof) { setErr('Para transferencia debes adjuntar el comprobante.'); return; }

    const address = isDelivery ? f.address.trim()
      : (f.orderType === 'eat_in' ? 'Consumo en el restaurante' : 'Recoger en local');

    const fd = new FormData();
    fd.append('customer', JSON.stringify({
      name: f.name, idType: f.idType, idNumber: f.idNumber,
      phone: f.cc + f.phone, email: f.email, address, payment: f.payment,
    }));
    fd.append('items', JSON.stringify(items.map((i) => ({
      id: i.productId,
      title: i.name + (i.variantLabel ? ` (${i.variantLabel})` : ''),
      price: i.unitPrice,
      qty: i.qty,
      modifiers: (i.modLabels || []).map((l) => ({ title: l })),
    }))));
    fd.append('total', String(total));
    fd.append('order_type', f.orderType);
    if (f.notes) fd.append('notes', f.notes);
    if (proof) fd.append('payment_proof', proof);

    setBusy(true);
    try {
      const r = await fetch('/api/create-order', { method: 'POST', body: fd });
      const j = await r.json().catch(() => ({}));
      if (r.ok && j.success) {
        onComplete({
          orderId: j.orderId,
          orderType: f.orderType,
          name: f.name,
          email: f.email,
          phone: f.cc + f.phone,
          total,
        });
      } else {
        setErr(j.error || 'No se pudo registrar el pedido. Intenta de nuevo.');
      }
    } catch (e2) {
      setErr('Error de conexión. Revisa tu internet e intenta de nuevo.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <>
      <div className={`modal-backdrop ${open ? 'is-open' : ''}`} onClick={onClose} />
      <div className={`detail-modal detail-modal--scroll ${open ? 'is-open' : ''}`}>
        <div className="detail-modal__body">
          <button className="detail-modal__close" onClick={onClose} aria-label="Cerrar">✕</button>
          <span className="eyebrow" style={{ display: 'block', marginBottom: 14 }}>— Finaliser la commande —</span>
          <h2 className="detail-modal__title">Finalizar pedido</h2>
          <p className="detail-modal__desc">
            Total a pagar: <strong style={{ fontStyle: 'normal', color: 'var(--ink)' }}>{cop(total)}</strong> · {items.length} {items.length === 1 ? 'producto' : 'productos'}
          </p>

          <form className="checkout-form" onSubmit={submit}>
            <fieldset className="form-fieldset" style={{ border: 0, padding: 0, margin: '24px 0 28px' }}>
              <legend>Tipo de pedido</legend>
              <div className="checkout-ordertypes">
                {ORDER_TYPES.map((o) => (
                  <label key={o.id} className={`pay-option ${f.orderType === o.id ? 'is-on' : ''}`}>
                    <input type="radio" name="otype" value={o.id}
                      checked={f.orderType === o.id}
                      onChange={() => setF((p) => ({ ...p, orderType: o.id }))} />
                    <div>
                      <h4 className="pay-option__title">{o.label}</h4>
                      <p className="pay-option__sub">{o.sub}</p>
                    </div>
                  </label>
                ))}
              </div>
            </fieldset>

            <fieldset className="form-fieldset" style={{ border: 0, padding: 0, margin: '0 0 28px' }}>
              <legend>Tus datos</legend>
              <div className="form-row">
                <div className="form-field">
                  <label className="form-label">Nombre *</label>
                  <input className="form-input" placeholder="Nombre completo" value={f.name} onChange={set('name')} required />
                </div>
                <div className="form-field">
                  <label className="form-label">Correo *</label>
                  <input className="form-input" type="email" placeholder="tu@correo.com" value={f.email} onChange={set('email')} required />
                </div>
              </div>
              <div className="form-row">
                <div className="form-field" style={{ flex: '0 0 42%' }}>
                  <label className="form-label">Documento *</label>
                  <select className="form-input" value={f.idType} onChange={set('idType')}>
                    {ID_TYPES.map((d) => <option key={d.v} value={d.v}>{d.l}</option>)}
                  </select>
                </div>
                <div className="form-field">
                  <label className="form-label">Número *</label>
                  <input className="form-input" placeholder="Número de documento" value={f.idNumber} onChange={set('idNumber')} required />
                </div>
              </div>
              <div className="form-row">
                <div className="form-field" style={{ flex: '0 0 90px' }}>
                  <label className="form-label">Indic.</label>
                  <input className="form-input" value={f.cc} onChange={set('cc')} />
                </div>
                <div className="form-field">
                  <label className="form-label">Teléfono / WhatsApp *</label>
                  <input className="form-input" type="tel" placeholder="300 000 0000" value={f.phone} onChange={set('phone')} required />
                </div>
              </div>
              {isDelivery && (
                <div className="form-field">
                  <label className="form-label">Dirección de entrega *</label>
                  <input className="form-input" placeholder="Carrera, número, barrio, indicaciones" value={f.address} onChange={set('address')} required />
                </div>
              )}
              <div className="form-field">
                <label className="form-label">Notas especiales</label>
                <textarea className="form-textarea" placeholder="Sin azúcar, alergias, dedicatoria, etc." value={f.notes} onChange={set('notes')}></textarea>
              </div>
            </fieldset>

            <fieldset className="form-fieldset" style={{ border: 0, padding: 0 }}>
              <legend>Método de pago</legend>
              <div className="form-field">
                <select className="form-input" value={f.payment} onChange={set('payment')}>
                  {PAY_METHODS.map((m) => <option key={m} value={m}>{m}</option>)}
                </select>
              </div>
              {isTransfer && (
                <div className="form-field" style={{ marginTop: 14 }}>
                  <label className="form-label">Comprobante de pago * (foto / PDF)</label>
                  <input className="form-input" type="file" accept="image/*,application/pdf"
                    onChange={(e) => setProof(e.target.files[0] || null)} required />
                  <p className="pay-option__sub" style={{ marginTop: 6 }}>Bancolombia / Nequi / Daviplata — adjunta el soporte de la transferencia.</p>
                </div>
              )}
            </fieldset>

            {err && (
              <p style={{ color: '#b3261e', fontFamily: 'var(--sans)', fontSize: 13, margin: '18px 0 0' }}>{err}</p>
            )}

            <button type="submit" className="btn btn--lg" style={{ width: '100%', marginTop: 22 }} disabled={busy}>
              {busy ? 'Enviando…' : `Confirmar pedido · ${cop(total)}`}
            </button>
          </form>
        </div>
      </div>
    </>
  );
};

// ── Sticky mobile footer ─────────────────────────────────────────
const StickyMobileFooter = ({ onCartOpen, cartCount, onMenu, route, setRoute }) => (
  <div className="sticky-mobile-footer">
    <button className="sticky-mobile-footer__btn" onClick={() => setRoute('landing')}>
      <svg width="18" height="18" viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="0.9"><path d="M2.5 8 L9 2.5 L15.5 8 V15 H11 V11 H7 V15 H2.5 Z" /></svg>
      Pastelería
    </button>
    <button className="sticky-mobile-footer__btn" onClick={() => setRoute('menu')}>
      <svg width="18" height="18" viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="0.9"><line x1="3" y1="4" x2="15" y2="4"/><line x1="3" y1="9" x2="15" y2="9"/><line x1="3" y1="14" x2="11" y2="14"/></svg>
      La carta
    </button>
    <button
      className="sticky-mobile-footer__btn sticky-mobile-footer__btn--primary"
      onClick={onCartOpen}
    >
      <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="0.9"><path d="M3 5 H17 L15 14 H5 Z" /><path d="M7 5 V3.5 C7 2 8 1.5 10 1.5 C12 1.5 13 2 13 3.5 V5" /></svg>
      {cartCount > 0 ? `Mi pedido · ${cartCount}` : 'Mi pedido'}
    </button>
  </div>
);

const WhatsAppFab = () => (
  <a className="wa-fab" href={window.waLink('Hola, quisiera hacer un pedido / consulta en Alexandra Castro Pastelería.')} target="_blank" rel="noopener noreferrer" aria-label="WhatsApp">
    <svg viewBox="0 0 22 22" fill="currentColor"><path d="M11 1.5c-5.2 0-9.5 4.2-9.5 9.5 0 1.7.5 3.3 1.3 4.7L1.5 20.5l5-1.3c1.4.8 2.9 1.2 4.5 1.2 5.2 0 9.5-4.2 9.5-9.5S16.2 1.5 11 1.5zm5.1 13.7c-.2.6-1.2 1.1-1.7 1.2-.5.1-1 .1-1.6-.1-.4-.1-.9-.3-1.5-.5-2.5-1.1-4.2-3.6-4.3-3.7-.1-.2-1-1.4-1-2.6 0-1.3.7-1.9 1-2.2.2-.3.5-.3.7-.3h.5c.2 0 .4 0 .6.5.2.5.7 1.8.8 1.9 0 .1.1.2 0 .4-.1.2-.1.3-.3.4-.1.2-.3.4-.4.5-.1.1-.3.3-.1.5.1.3.7 1.1 1.5 1.8 1 .9 1.9 1.2 2.1 1.3.2.1.3.1.5-.1.1-.1.5-.6.7-.8.2-.2.4-.2.6-.1.2.1 1.4.7 1.6.8.2.1.4.2.5.3.1.1.1.6-.2 1.1z"/></svg>
  </a>
);

// ── Confirmación de pedido (pantalla clara, no un toast fugaz) ────
const ORDER_TYPE_INFO = {
  delivery: { label: 'A domicilio',       time: '30 – 50 min', detail: 'Te escribiremos por WhatsApp para confirmar y coordinar la entrega.' },
  eat_in:   { label: 'En el restaurante', time: '15 – 25 min', detail: 'Tu pedido se prepara para tu mesa. Cualquier cosa, te contactamos por WhatsApp.' },
  takeaway: { label: 'Para recoger',      time: '20 – 30 min', detail: 'Te avisamos por WhatsApp cuando esté listo para recoger.' },
};

const OrderConfirmModal = ({ info, onClose }) => {
  if (!info) return null;
  const t = ORDER_TYPE_INFO[info.orderType] || ORDER_TYPE_INFO.delivery;
  const firstName = info.name ? String(info.name).trim().split(' ')[0] : '';
  const wa = window.waLink(`Hola, acabo de hacer el pedido #${info.orderId} en la web de Alexandra Castro. Quisiera confirmar los detalles.`);
  const row = { display: 'flex', gap: 12, alignItems: 'flex-start', textAlign: 'left',
                padding: '14px 0', borderBottom: '1px solid var(--hairline)' };
  const ic = { flex: '0 0 auto', width: 22, textAlign: 'center', fontSize: 16, lineHeight: '24px' };
  return (
    <>
      <div className="modal-backdrop is-open" onClick={onClose} />
      <div className="detail-modal detail-modal--scroll is-open">
        <div className="detail-modal__body">
          <button className="detail-modal__close" onClick={onClose} aria-label="Cerrar">✕</button>

          <div style={{ textAlign: 'center', marginBottom: 8 }}>
            <div style={{ width: 64, height: 64, margin: '0 auto 20px', borderRadius: '50%',
                          border: '1px solid var(--gold)', display: 'flex', alignItems: 'center',
                          justifyContent: 'center', color: 'var(--plum)' }} aria-hidden="true">
              <svg width="30" height="30" viewBox="0 0 30 30" fill="none" stroke="currentColor" strokeWidth="1.4">
                <path d="M7 15.5 L12.5 21 L23 9" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </div>
            <span className="eyebrow" style={{ display: 'block', marginBottom: 12 }}>— Pedido confirmado —</span>
            <h2 className="detail-modal__title" style={{ marginBottom: 10 }}>
              ¡Gracias{firstName ? `, ${firstName}` : ''}!
            </h2>
            <p className="detail-modal__desc" style={{ margin: '0 0 24px' }}>
              Tu pedido <strong style={{ fontStyle: 'normal', color: 'var(--ink)' }}>#{info.orderId}</strong> quedó registrado.
            </p>
          </div>

          <div style={{ borderTop: '1px solid var(--hairline)' }}>
            <div style={row}>
              <span style={ic}>✉️</span>
              <span>Te enviamos la confirmación a <strong style={{ color: 'var(--ink)' }}>{info.email}</strong>. Si no la ves, revisa la carpeta de <em>spam</em>.</span>
            </div>
            <div style={row}>
              <span style={ic}>⏱️</span>
              <span>Tiempo estimado: <strong style={{ color: 'var(--ink)' }}>{t.time}</strong> · {t.label}.</span>
            </div>
            <div style={{ ...row, borderBottom: 'none' }}>
              <span style={ic}>📲</span>
              <span>{t.detail}{info.phone ? <> Te contactamos al <strong style={{ color: 'var(--ink)' }}>{info.phone}</strong>.</> : null}</span>
            </div>
          </div>

          <div className="detail-modal__actions" style={{ marginTop: 28 }}>
            <a className="btn" href={wa} target="_blank" rel="noopener noreferrer" style={{ textAlign: 'center', textDecoration: 'none' }}>Escríbenos por WhatsApp</a>
            <button className="btn btn--outline" onClick={onClose}>Seguir en la carta</button>
          </div>
        </div>
      </div>
    </>
  );
};

window.FloatingCart = FloatingCart;
window.CartModal = CartModal;
window.DetailModal = DetailModal;
window.CheckoutModal = CheckoutModal;
window.OrderConfirmModal = OrderConfirmModal;
window.StickyMobileFooter = StickyMobileFooter;
window.WhatsAppFab = WhatsAppFab;
