// ─── Cart context + drawer + checkout ──────────────────────────────
// El flujo de "compra" no es realmente un pago: el cliente añade piezas,
// rellena sus datos, y María recibe el pedido para subir los artículos a
// Vinted o Wallapop a su nombre, donde el cliente completa el pago.

const { useState, useEffect, useMemo, createContext, useContext } = React;

const CartCtx = createContext(null);

function CartProvider({ children }) {
  const [items, setItems] = useState(() => {
    try { return JSON.parse(localStorage.getItem('blythe.cart') || '[]'); }
    catch { return []; }
  });
  const [open, setOpen] = useState(false);
  const [stage, setStage] = useState('cart'); // cart | checkout | done

  useEffect(() => {
    localStorage.setItem('blythe.cart', JSON.stringify(items));
  }, [items]);

  function add(product) {
    setItems(prev => prev.find(p => p.id === product.id) ? prev : [...prev, product]);
    setOpen(true); setStage('cart');
  }
  function remove(id) {
    setItems(prev => prev.filter(p => p.id !== id));
  }
  function clear() { setItems([]); }

  const subtotal = items.reduce((s, p) => s + p.precio, 0);
  const count = items.length;

  const value = { items, count, subtotal, add, remove, clear, open, setOpen, stage, setStage };
  return <CartCtx.Provider value={value}>{children}</CartCtx.Provider>;
}

function useCart() { return useContext(CartCtx); }

// ─── Cart floating button (only when items > 0) ────────────────────
function CartButton() {
  const c = useCart();
  if (!c.count) return null;
  return (
    <button onClick={() => { c.setOpen(true); c.setStage('cart'); }} style={{
      position: 'fixed', bottom: 28, right: 28, zIndex: 50,
      display: 'flex', alignItems: 'center', gap: 10,
      padding: '14px 22px', background: V.ink, color: V.cream,
      fontFamily: F.body, fontSize: 14, letterSpacing: 3, textTransform: 'uppercase',
      border: `1px solid ${V.gold}`, cursor: 'pointer',
      boxShadow: '0 16px 36px -16px rgba(45,36,25,0.65)',
    }}>
      <span style={{ fontSize: 18 }}>✦</span>
      <span>Tu cesta</span>
      <span style={{
        background: V.gold, color: V.ink, fontFamily: F.mono, fontSize: 11,
        padding: '2px 8px', letterSpacing: 1,
      }}>{c.count}</span>
    </button>
  );
}

// ─── Cart drawer ───────────────────────────────────────────────────
function CartDrawer() {
  const c = useCart();
  return (
    <>
      {/* Backdrop */}
      <div onClick={() => c.setOpen(false)} style={{
        position: 'fixed', inset: 0, background: 'rgba(45,36,25,0.55)',
        opacity: c.open ? 1 : 0, pointerEvents: c.open ? 'auto' : 'none',
        transition: 'opacity .28s', zIndex: 90,
      }}/>
      {/* Panel */}
      <aside style={{
        position: 'fixed', top: 0, right: 0, bottom: 0, width: 'min(560px, 92vw)',
        background: V.cream, zIndex: 100,
        transform: c.open ? 'translateX(0)' : 'translateX(100%)',
        transition: 'transform .35s cubic-bezier(.22,.61,.36,1)',
        display: 'flex', flexDirection: 'column',
        boxShadow: '-20px 0 60px -20px rgba(45,36,25,0.4)',
      }}>
        {c.stage === 'cart' && <CartStageList />}
        {c.stage === 'checkout' && <CartStageCheckout />}
        {c.stage === 'done' && <CartStageDone />}
      </aside>
    </>
  );
}

function DrawerHeader({ title, eyebrow }) {
  const c = useCart();
  const { mobile } = useResponsive();
  return (
    <div style={{ padding: mobile ? '22px 20px 16px' : '28px 32px 20px', borderBottom: `1px solid ${V.inkSoft}33`, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
      <div>
        <div style={{ fontFamily: F.mono, fontSize: 11, letterSpacing: 3, textTransform: 'uppercase', color: V.inkSoft, marginBottom: 6 }}>
          {eyebrow}
        </div>
        <div style={{ fontFamily: F.display, fontSize: mobile ? 30 : 38, color: V.ink, lineHeight: 1, fontStyle: 'italic' }}>
          {title}
        </div>
      </div>
      <button onClick={() => c.setOpen(false)} style={{
        width: 36, height: 36, border: `1px solid ${V.ink}`, background: 'transparent',
        fontSize: 18, color: V.ink, cursor: 'pointer', fontFamily: F.mono,
      }}>✕</button>
    </div>
  );
}

function CartStageList() {
  const c = useCart();
  return (
    <>
      <DrawerHeader eyebrow={`${c.count} ${c.count === 1 ? 'pieza reservada' : 'piezas reservadas'}`} title="Tu cesta" />
      <div style={{ flex: 1, overflow: 'auto', padding: '20px 32px' }}>
        {c.items.length === 0 ? (
          <div style={{ padding: '60px 0', textAlign: 'center', fontFamily: F.body, fontSize: 17, color: V.inkSoft, fontStyle: 'italic' }}>
            Aún no has elegido ninguna pieza.
          </div>
        ) : c.items.map(p => (
          <div key={p.id} style={{ display: 'flex', gap: 16, padding: '16px 0', borderBottom: `1px dashed ${V.inkSoft}33` }}>
            <div style={{ width: 80, height: 100, overflow: 'hidden', flexShrink: 0, background: V.paper }}>
              <img src={p.img} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: F.mono, fontSize: 10, letterSpacing: 2, textTransform: 'uppercase', color: V.inkSoft, marginBottom: 4 }}>
                № {String(p.id).padStart(3,'0')} · {p.cat}
              </div>
              <div style={{ fontFamily: F.display, fontSize: 22, fontStyle: 'italic', color: V.ink, lineHeight: 1.05, marginBottom: 8 }}>
                {p.nombre}
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div style={{ fontFamily: F.mono, fontSize: 14, color: V.roseDeep, fontWeight: 600 }}>{p.precio} €</div>
                <button onClick={() => c.remove(p.id)} style={{
                  background: 'transparent', border: 'none', cursor: 'pointer',
                  fontFamily: F.mono, fontSize: 10, letterSpacing: 2, color: V.inkSoft, textTransform: 'uppercase',
                  textDecoration: 'underline', textUnderlineOffset: 3,
                }}>Quitar</button>
              </div>
            </div>
          </div>
        ))}

        {c.items.length > 0 && (
          <div style={{
            marginTop: 24, padding: 20, background: V.paper,
            fontFamily: F.body, fontSize: 14, lineHeight: 1.55, color: V.inkSoft,
            borderLeft: `3px solid ${V.gold}`,
          }}>
            <strong style={{ color: V.roseDeep, fontFamily: F.display, fontStyle: 'italic', fontSize: 17 }}>Cómo funciona la reserva</strong><br/>
            Cuando completes tus datos, recibiré tu pedido y publicaré cada pieza en Vinted o Wallapop a tu nombre. Te enviaré el enlace en menos de 24h para que finalices el pago en la plataforma. <em>Las piezas quedan reservadas para ti durante 48h.</em>
          </div>
        )}
      </div>

      {c.items.length > 0 && (
        <div style={{ padding: '20px 32px 28px', borderTop: `1px solid ${V.inkSoft}33`, background: V.paperDk }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16, fontFamily: F.body, fontSize: 15, color: V.ink }}>
            <span>Subtotal · {c.count} {c.count === 1 ? 'pieza' : 'piezas'}</span>
            <span style={{ fontFamily: F.mono, fontSize: 18, color: V.ink, fontWeight: 700 }}>{c.subtotal.toFixed(2)} €</span>
          </div>
          <div style={{ fontFamily: F.mono, fontSize: 11, letterSpacing: 1, color: V.inkSoft, marginBottom: 16, textAlign: 'right' }}>
            * El envío depende del método de pago que elijas
          </div>
          <button onClick={() => c.setStage('checkout')} style={{
            width: '100%', padding: '18px', background: V.ink, color: V.cream, border: 'none',
            fontFamily: F.body, fontSize: 14, letterSpacing: 4, textTransform: 'uppercase', cursor: 'pointer',
          }}>Tramitar reserva →</button>
        </div>
      )}
    </>
  );
}

// ─── Checkout stage ────────────────────────────────────────────────
function CartStageCheckout() {
  const c = useCart();
  const { mobile } = useResponsive();
  const [form, setForm] = useState(() => {
    try { return JSON.parse(localStorage.getItem('blythe.checkout') || '{}'); }
    catch { return {}; }
  });
  const [zona, setZona] = useState(form.zona || 'espana');
  const [plataforma, setPlataforma] = useState(form.plataforma || 'vinted');
  const [sending, setSending] = useState(false);
  const [error, setError] = useState(null);

  // El envío solo lo gestiona María cuando el pago es por transferencia.
  // En Vinted/Wallapop lo fija la plataforma cuando el cliente compra.
  const aplicaEnvio = plataforma === 'transferencia';
  const envio = ENVIOS[zona];
  const envioCoste = aplicaEnvio && c.subtotal < envio.gratisDesde ? envio.coste : 0;
  const total = c.subtotal + envioCoste;

  function set(k, v) {
    const next = { ...form, [k]: v };
    setForm(next);
    localStorage.setItem('blythe.checkout', JSON.stringify(next));
  }

  async function submit(e) {
    e.preventDefault();
    setSending(true);
    setError(null);
    const payload = {
      nombre: form.nombre, telefono: form.telefono, email: form.email,
      direccion: form.direccion, cp: form.cp, ciudad: form.ciudad,
      zona, plataforma, notas: form.notas || '',
      items: c.items.map(p => ({ id: p.id, nombre: p.nombre, cat: p.cat, precio: p.precio })),
      subtotal: c.subtotal,
      envio: aplicaEnvio
        ? { zona, label: envio.label, coste: envioCoste }
        : { zona: null, label: `Lo fija ${plataforma === 'vinted' ? 'Vinted' : 'Wallapop'} al comprar`, coste: 0 },
      total,
    };
    try {
      const r = await fetch('/api/reserva', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      if (!r.ok) throw new Error('envío fallido');
      c.setStage('done');
    } catch (err) {
      setError('No hemos podido enviar tu reserva. Revisa la conexión e inténtalo de nuevo en un momento.');
    } finally {
      setSending(false);
    }
  }

  return (
    <>
      <DrawerHeader eyebrow="Paso 2 de 3" title="Tus datos" />
      <form onSubmit={submit} style={{ flex: 1, overflow: 'auto', padding: mobile ? '20px' : '24px 32px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr', gap: 14 }}>
          <Field label="Nombre y apellidos *"><Input required value={form.nombre || ''} onChange={e => set('nombre', e.target.value)} /></Field>
          <Field label="Teléfono *"><Input required type="tel" value={form.telefono || ''} onChange={e => set('telefono', e.target.value)} /></Field>
        </div>
        <Field label="Correo electrónico *"><Input required type="email" value={form.email || ''} onChange={e => set('email', e.target.value)} /></Field>
        <Field label="Dirección *"><Input required value={form.direccion || ''} onChange={e => set('direccion', e.target.value)} /></Field>
        <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr 2fr' : '1fr 2fr', gap: 14 }}>
          <Field label="Código postal *"><Input required value={form.cp || ''} onChange={e => set('cp', e.target.value)} /></Field>
          <Field label="Ciudad / país *"><Input required value={form.ciudad || ''} onChange={e => set('ciudad', e.target.value)} /></Field>
        </div>

        {/* Método de pago */}
        <Field label="¿Cómo prefieres pagar?">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {[
              { k: 'vinted',        l: 'Vinted',                 sub: 'Pago protegido · ideal si estás fuera de España' },
              { k: 'wallapop',      l: 'Wallapop',               sub: 'Pago protegido · muy popular en España' },
              { k: 'transferencia', l: 'Transferencia bancaria', sub: 'Pago por adelantado · te doy los datos' },
            ].map(o => (
              <label key={o.k} style={{
                display: 'block', padding: '14px 16px',
                background: plataforma === o.k ? V.paperDk : V.cream,
                border: `1px solid ${plataforma === o.k ? V.ink : V.inkSoft + '44'}`,
                cursor: 'pointer',
              }}>
                <input type="radio" name="plat" checked={plataforma === o.k} onChange={() => { setPlataforma(o.k); set('plataforma', o.k); }} style={{ accentColor: V.roseDeep, marginRight: 8 }} />
                <span style={{ fontFamily: F.display, fontStyle: 'italic', fontSize: 20, color: V.ink }}>{o.l}</span>
                <div style={{ fontFamily: F.body, fontSize: 12, color: V.inkSoft, marginTop: 4 }}>{o.sub}</div>
              </label>
            ))}
          </div>
          <div style={{
            marginTop: 12, padding: '10px 14px', background: V.paper, borderLeft: `3px solid ${V.gold}`,
            fontFamily: F.body, fontSize: 13, color: V.inkSoft, lineHeight: 1.55, fontStyle: 'italic',
          }}>
            En cualquier caso, me pondré en contacto contigo para confirmar y concretar el pedido antes de realizar ningún pago.
          </div>
        </Field>

        {/* Zona de envío: solo con transferencia. En Vinted/Wallapop el envío lo fija la plataforma al comprar. */}
        {aplicaEnvio && (
          <Field label="Zona de envío">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {Object.entries(ENVIOS).map(([k, e]) => (
                <label key={k} style={{
                  display: 'flex', alignItems: 'center', gap: 12, padding: '10px 14px',
                  background: zona === k ? V.paperDk : V.cream,
                  border: `1px solid ${zona === k ? V.ink : V.inkSoft + '44'}`,
                  cursor: 'pointer', fontFamily: F.body, fontSize: 15,
                }}>
                  <input type="radio" name="zona" checked={zona === k} onChange={() => { setZona(k); set('zona', k); }} style={{ accentColor: V.roseDeep }} />
                  <span style={{ flex: 1 }}>{e.label}</span>
                  <span style={{ fontFamily: F.mono, fontSize: 12, color: V.inkSoft }}>{e.plazo}</span>
                  <span style={{ fontFamily: F.mono, fontSize: 13, color: V.roseDeep, fontWeight: 600 }}>
                    {c.subtotal >= e.gratisDesde ? 'GRATIS' : `${e.coste.toFixed(2)} €`}
                  </span>
                </label>
              ))}
            </div>
            <div style={{ fontFamily: F.body, fontSize: 13, color: V.inkSoft, marginTop: 8, fontStyle: 'italic' }}>
              Envío gratis a partir de {envio.gratisDesde} € · te faltan {Math.max(0, envio.gratisDesde - c.subtotal).toFixed(2)} €
            </div>
          </Field>
        )}

        <Field label="Notas (opcional)">
          <textarea rows="2" value={form.notas || ''} onChange={e => set('notas', e.target.value)} style={inputStyle} />
        </Field>

        {/* Totales */}
        <div style={{ marginTop: 20, padding: '18px 20px', background: V.paperDk, fontFamily: F.body, color: V.ink }}>
          <Row k={`Subtotal (${c.count} piezas)`} v={`${c.subtotal.toFixed(2)} €`} />
          {aplicaEnvio
            ? <Row k={`Envío · ${envio.label}`} v={envioCoste === 0 ? 'GRATIS' : `${envioCoste.toFixed(2)} €`} />
            : <Row k="Envío" v={`Lo fija ${plataforma === 'vinted' ? 'Vinted' : 'Wallapop'}`} />}
          <div style={{ borderTop: `1px solid ${V.inkSoft}55`, marginTop: 10, paddingTop: 10 }}>
            <Row k={aplicaEnvio ? 'Total a pagar' : 'Total piezas'} v={`${total.toFixed(2)} €`} big />
          </div>
          <div style={{ fontFamily: F.mono, fontSize: 11, color: V.inkSoft, marginTop: 10, lineHeight: 1.55 }}>
            {plataforma === 'transferencia'
              ? 'Pagarás por transferencia bancaria por adelantado; te enviaré los datos al confirmar. No se realiza ningún cargo desde esta web.'
              : `Pagarás en ${plataforma === 'vinted' ? 'Vinted' : 'Wallapop'} cuando publique tu pedido. No se realiza ningún cargo desde esta web.`}
          </div>
        </div>

        {error && (
          <div style={{
            marginTop: 16, padding: '12px 16px', background: '#efdcd9',
            border: `1px solid ${V.roseDeep}`, color: V.roseDeep,
            fontFamily: F.body, fontSize: 14, lineHeight: 1.5,
          }}>{error}</div>
        )}
        <div style={{ display: 'flex', gap: 12, marginTop: 24 }}>
          <button type="button" onClick={() => c.setStage('cart')} disabled={sending} style={{
            flex: '0 0 auto', padding: '16px 24px', background: 'transparent', color: V.ink,
            border: `1px solid ${V.ink}`, fontFamily: F.body, fontSize: 13, letterSpacing: 3, textTransform: 'uppercase',
            cursor: sending ? 'default' : 'pointer', opacity: sending ? 0.5 : 1,
          }}>← Volver</button>
          <button type="submit" disabled={sending} style={{
            flex: 1, padding: '16px', background: V.ink, color: V.cream, border: 'none',
            fontFamily: F.body, fontSize: 13, letterSpacing: 3, textTransform: 'uppercase',
            cursor: sending ? 'default' : 'pointer', opacity: sending ? 0.7 : 1,
          }}>{sending ? 'Enviando…' : 'Enviar reserva a María →'}</button>
        </div>
      </form>
    </>
  );
}

const inputStyle = {
  width: '100%', padding: '10px 12px', border: `1px solid ${V.inkSoft}55`,
  background: V.cream, fontFamily: F.body, fontSize: 15, color: V.ink, outline: 'none',
  borderRadius: 0,
};
function Input(props) { return <input {...props} style={inputStyle} />; }
function Field({ label, children }) {
  return (
    <label style={{ display: 'block', marginBottom: 14 }}>
      <div style={{ fontFamily: F.mono, fontSize: 10, letterSpacing: 2, textTransform: 'uppercase', color: V.inkSoft, marginBottom: 6 }}>{label}</div>
      {children}
    </label>
  );
}
function Row({ k, v, big }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '4px 0', fontSize: big ? 16 : 14 }}>
      <span style={{ fontFamily: F.body, color: V.ink }}>{k}</span>
      <span style={{ fontFamily: F.mono, fontWeight: big ? 700 : 500, fontSize: big ? 22 : 15, color: big ? V.roseDeep : V.ink }}>{v}</span>
    </div>
  );
}

// ─── Confirmación ──────────────────────────────────────────────────
function CartStageDone() {
  const c = useCart();
  let plataforma = 'vinted';
  try { plataforma = JSON.parse(localStorage.getItem('blythe.checkout') || '{}').plataforma || 'vinted'; } catch {}
  const pasos = plataforma === 'transferencia'
    ? [
        ['1', 'Me pondré en contacto contigo para confirmar el pedido y darte los datos de la transferencia.'],
        ['2', 'Haces la transferencia por adelantado.'],
        ['3', 'Tu pedido sale de mi taller en 48h con seguimiento.'],
      ]
    : [
        ['1', 'Publico tus piezas en Vinted o Wallapop a tu nombre.'],
        ['2', 'Te llega un correo con el enlace a la publicación (máximo 24h).'],
        ['3', 'Completas el pago en la plataforma elegida.'],
        ['4', 'Tu pedido sale de mi taller en 48h con seguimiento.'],
      ];
  return (
    <>
      <DrawerHeader eyebrow="Paso 3 de 3" title="¡Reserva enviada!" />
      <div style={{ flex: 1, overflow: 'auto', padding: '32px 40px' }}>
        <div style={{ textAlign: 'center', marginBottom: 24 }}>
          <Stamp size={120} text="RESERVA · RECIBIDA · " center="✓" />
        </div>
        <p style={{ fontFamily: F.body, fontSize: 18, color: V.ink, lineHeight: 1.6, textAlign: 'center', marginBottom: 28 }}>
          Gracias. He recibido tu pedido y me pondré en contacto contigo en menos de 24h.
        </p>

        <div style={{ borderTop: `1px solid ${V.inkSoft}33`, paddingTop: 24 }}>
          <div style={{ fontFamily: F.mono, fontSize: 11, letterSpacing: 3, textTransform: 'uppercase', color: V.inkSoft, marginBottom: 14 }}>
            Qué pasa ahora
          </div>
          {pasos.map(([n, t]) => (
            <div key={n} style={{ display: 'flex', gap: 16, marginBottom: 16 }}>
              <div style={{
                width: 32, height: 32, flexShrink: 0, border: `1px solid ${V.ink}`,
                fontFamily: F.display, fontStyle: 'italic', fontSize: 18, color: V.ink,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>{n}</div>
              <div style={{ fontFamily: F.body, fontSize: 16, color: V.ink, lineHeight: 1.5, paddingTop: 4 }}>{t}</div>
            </div>
          ))}
        </div>

        <div style={{ marginTop: 32, padding: 18, background: V.paper, fontFamily: F.body, fontSize: 14, color: V.inkSoft, fontStyle: 'italic', lineHeight: 1.55 }}>
          ¿Prefieres hablar antes? Escríbeme por DM en{' '}
          <a href="https://www.instagram.com/el_armario_de_blythe/" target="_blank" rel="noreferrer" style={{ color: V.roseDeep, fontWeight: 600 }}>@el_armario_de_blythe</a>.
        </div>

        <button onClick={() => { c.clear(); c.setOpen(false); }} style={{
          width: '100%', marginTop: 28, padding: '16px', background: V.ink, color: V.cream, border: 'none',
          fontFamily: F.body, fontSize: 13, letterSpacing: 3, textTransform: 'uppercase', cursor: 'pointer',
        }}>Seguir mirando piezas</button>
      </div>
    </>
  );
}

Object.assign(window, { CartProvider, useCart, CartButton, CartDrawer });
