/* global React, Icon, ProductArt, ProductCard, Stars, fmtMXN, TrustRow */
// Pages: Cart, Checkout, Login (page), Account, Wishlist, Search, About, Blog, Contact

const { useState: useStateP2, useEffect: useEffectP2, useMemo: useMemoP2 } = React;
const ProductRow = window.ProductRow;

// ============ CART (full page) ============
function PageCart({ items, onChangeQty, onRemove, navigate, dark }) {
  const subtotal = items.reduce((s, it) => s + it.price * it.qty, 0);
  const shipping = subtotal > 2000 || subtotal === 0 ? 0 : 199;
  const discount = 0;
  const total = subtotal + shipping - discount;

  if (items.length === 0) {
    return (
      <div className="wrap section" style={{ textAlign: 'center', padding: '100px 0' }}>
        <h1 className="display" style={{ fontSize: 72 }}>CARRITO VACÍO</h1>
        <p className="lead" style={{ color: 'var(--text-muted)', maxWidth: 380, margin: '0 auto 32px' }}>
          Ningún producto aquí todavía. Pero está bien — la tienda no se acaba.
        </p>
        <button className="btn primary lg" onClick={() => navigate('shop')}>Explorar la tienda →</button>
      </div>);

  }

  return (
    <div className="wrap section">
      <div className="mono" style={{ color: 'var(--text-muted)', marginBottom: 14 }}>
        <a onClick={() => navigate('home')} style={{ cursor: 'pointer' }}>Inicio</a>
        <span style={{ margin: '0 8px' }}>/</span>
        <span style={{ color: 'var(--text)' }}>Carrito</span>
      </div>
      <h1 className="display" style={{ fontSize: 'clamp(48px, 7vw, 96px)', margin: '0 0 32px' }}>TU CARRITO <span style={{ color: 'var(--blood)' }}>· {items.length}</span></h1>

      <div className="cart-layout">
        <div>
          <div style={{ borderTop: '1px solid var(--line-strong)' }}>
            <div className="row" style={{ padding: '12px 0', borderBottom: '1px solid var(--line)', fontFamily: 'var(--f-mono)', fontSize: 10, letterSpacing: '.16em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>
              <div style={{ flex: 1 }}>Producto</div>
              <div style={{ width: 140 }}>Cantidad</div>
              <div style={{ width: 120, textAlign: 'right' }}>Total</div>
            </div>
            {items.map((it) =>
            <div key={it.cartId} className="cart-row">
                <div style={{ width: 120, height: 120, background: 'var(--surface)', border: '1px solid var(--line)' }}>
                  <ProductArt product={it} dark={dark} />
                </div>
                <div>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--text-muted)', letterSpacing: '.14em' }}>{it.brand} · {it.id.toUpperCase()}</div>
                  <div style={{ fontSize: 16, fontWeight: 500, marginTop: 4 }}>{it.name}</div>
                  {(it.size || it.colorName) && <div className="mono" style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 6 }}>
                    {[it.size && `Talla ${it.size}`, it.colorName].filter(Boolean).join(' · ')}
                  </div>}
                  <a className="mono" style={{ display: 'inline-block', marginTop: 10, fontSize: 10, color: 'var(--text-muted)', textDecoration: 'underline', cursor: 'pointer' }} onClick={() => onRemove(it.cartId)}>
                    Quitar del carrito
                  </a>
                </div>
                <div className="qty">
                  <button onClick={() => onChangeQty(it.cartId, it.qty - 1)}>−</button>
                  <span className="val">{it.qty}</span>
                  <button onClick={() => onChangeQty(it.cartId, it.qty + 1)}>+</button>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div className="display" style={{ fontSize: 24 }}>{fmtMXN(it.price * it.qty)}</div>
                  {it.oldPrice && <div className="mono" style={{ fontSize: 10, textDecoration: 'line-through', color: 'var(--text-muted)' }}>{fmtMXN(it.oldPrice * it.qty)}</div>}
                </div>
              </div>
            )}
          </div>
          <div className="mt-24">
            <button className="btn ghost sm" onClick={() => navigate('shop')}>← Seguir comprando</button>
          </div>
        </div>

        <aside style={{ alignSelf: 'start', position: 'sticky', top: 100 }}>
          <div style={{ border: '1px solid var(--line-strong)', padding: '28px' }}>
            <h3 className="display" style={{ fontSize: 28, margin: '0 0 20px' }}>RESUMEN</h3>
            <div style={{ display: 'grid', gap: 12 }}>
              <div className="between" style={{ fontSize: 14 }}><span className="mono" style={{ color: 'var(--text-muted)' }}>Subtotal</span><span>{fmtMXN(subtotal)}</span></div>
              <div className="between" style={{ fontSize: 14 }}><span className="mono" style={{ color: 'var(--text-muted)' }}>Envío</span><span>{shipping === 0 ? <span style={{ color: 'var(--ok)' }}>GRATIS</span> : fmtMXN(shipping)}</span></div>
              <div className="between" style={{ fontSize: 14 }}><span className="mono" style={{ color: 'var(--text-muted)' }}>Descuento</span><span>—</span></div>
            </div>
            <div className="divider" style={{ margin: '20px 0' }} />
            <div className="between">
              <span className="mono">Total</span>
              <span className="display" style={{ fontSize: 32, color: 'var(--blood)' }}>{fmtMXN(total)}</span>
            </div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--text-muted)', marginTop: 6 }}>o 12 pagos de {fmtMXN(Math.round(total / 12))} con MSI</div>

            <div className="mt-24" style={{ display: 'flex' }}>
              <input className="field" placeholder="Código de cupón" style={{ borderRadius: 0 }} />
              <button className="btn ghost" style={{ borderRadius: 0 }}>Aplicar</button>
            </div>

            <button className="btn primary block lg mt-24" onClick={() => navigate('checkout')}>Finalizar compra →</button>

            <div className="mt-16" style={{ textAlign: 'center', fontSize: 11, fontFamily: 'var(--f-mono)', color: 'var(--text-muted)', letterSpacing: '.14em' }}>
              ● PAGO SEGURO · 🔒 SSL
            </div>
          </div>
        </aside>
      </div>
    </div>);

}

// ============ CHECKOUT ============
function PageCheckout({ items, navigate, dark, onClearCart }) {
  const [step, setStep] = useState(0);
  const steps = ['Envío', 'Pago', 'Confirmación'];
  const subtotal = items.reduce((s, it) => s + it.price * it.qty, 0);
  const shipping = subtotal > 2000 ? 0 : 199;
  const total = subtotal + shipping;

  const [shipForm, setShipForm] = useState({ name: '', email: '', phone: '', street: '', ext: '', int: '', col: '', city: '', state: 'CDMX', zip: '', method: 'standard' });
  const [payForm, setPayForm] = useState({ method: 'card', cardName: '', cardNum: '', exp: '', cvv: '' });
  const [errs, setErrs] = useState({});

  // Input formatters
  const formatPhone = (v) => {
    const d = v.replace(/\D/g, '').slice(0, 10);
    if (d.length <= 2) return d;
    if (d.length <= 6) return d.slice(0,2) + ' ' + d.slice(2);
    return d.slice(0,2) + ' ' + d.slice(2,6) + ' ' + d.slice(6);
  };
  const formatCardNum = (v) => v.replace(/\D/g, '').slice(0, 16).replace(/(.{4})/g, '$1 ').trim();
  const formatExp = (v) => {
    const d = v.replace(/\D/g, '').slice(0, 4);
    if (d.length <= 2) return d;
    return d.slice(0, 2) + '/' + d.slice(2);
  };
  const formatZip = (v) => v.replace(/\D/g, '').slice(0, 5);
  const formatCvv = (v) => v.replace(/\D/g, '').slice(0, 4);

  const validateShip = () => {
    const e = {};
    ['name', 'email', 'phone', 'street', 'col', 'city', 'zip'].forEach((k) => {if (!shipForm[k]) e[k] = 'Requerido';});
    if (shipForm.email && !shipForm.email.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) e.email = 'Email no válido';
    if (shipForm.zip && !/^\d{5}$/.test(shipForm.zip)) e.zip = '5 dígitos';
    setErrs(e);return Object.keys(e).length === 0;
  };
  const validatePay = () => {
    const e = {};
    if (payForm.method === 'card') {
      if (!payForm.cardName || payForm.cardName.trim().length < 3) e.cardName = 'Nombre completo del titular';
      if (!/^\d{16}$/.test(payForm.cardNum.replace(/\s/g, ''))) e.cardNum = '16 dígitos';
      if (!/^\d{2}\/\d{2}$/.test(payForm.exp)) {
        e.exp = 'Formato MM/AA';
      } else {
        const [mm, yy] = payForm.exp.split('/').map(n => parseInt(n, 10));
        const nowYear = new Date().getFullYear() % 100;
        const nowMonth = new Date().getMonth() + 1;
        if (mm < 1 || mm > 12) e.exp = 'Mes inválido';
        else if (yy < nowYear || (yy === nowYear && mm < nowMonth)) e.exp = 'Tarjeta vencida';
      }
      if (!/^\d{3,4}$/.test(payForm.cvv)) e.cvv = '3-4 dígitos';
    }
    setErrs(e);return Object.keys(e).length === 0;
  };

  const next = () => {
    if (step === 0 && !validateShip()) return;
    if (step === 1 && !validatePay()) return;
    setStep(step + 1);
    if (step === 1) onClearCart && setTimeout(onClearCart, 200);
  };

  if (items.length === 0 && step < 2) {
    return <div className="wrap section" style={{ textAlign: 'center', padding: '80px 0' }}>
      <h2 className="display" style={{ fontSize: 48 }}>SIN PRODUCTOS</h2>
      <button className="btn primary mt-16" onClick={() => navigate('shop')}>Ir a la tienda</button>
    </div>;
  }

  return (
    <div className="wrap section" style={{ paddingTop: 32 }}>
      <div className="mono" style={{ color: 'var(--text-muted)', marginBottom: 14 }}>
        <a onClick={() => navigate('cart')} style={{ cursor: 'pointer' }}>← Carrito</a>
      </div>
      <h1 className="display" style={{ fontSize: 'clamp(40px, 6vw, 72px)', margin: '0 0 24px' }}>CHECKOUT</h1>

      <div className="stepper">
        {steps.map((s, i) =>
        <div key={i} className={`step ${step === i ? 'on' : ''} ${step > i ? 'done' : ''}`}>
            <div className="n">{step > i ? Icon.check() : i + 1}</div>
            <div className="lab">{s}<span className="sub">{i === 0 ? 'Datos & dirección' : i === 1 ? 'Tarjeta o transferencia' : 'Pedido confirmado'}</span></div>
          </div>
        )}
      </div>

      {step < 2 ?
      <div className="checkout-layout">
          <div>
            {step === 0 &&
          <div style={{ display: 'grid', gap: 20 }}>
                <h2 className="display" style={{ fontSize: 28, margin: 0 }}>DATOS DE CONTACTO</h2>
                <div className="grid-2">
                  <div><label className="field-label">Nombre completo *</label><input className={`field ${errs.name ? 'error' : ''}`} value={shipForm.name} onChange={(e) => setShipForm({ ...shipForm, name: e.target.value })} />{errs.name && <span className="field-err">{errs.name}</span>}</div>
                  <div><label className="field-label">Teléfono *</label><input className={`field ${errs.phone ? 'error' : ''}`} value={shipForm.phone} onChange={(e) => setShipForm({ ...shipForm, phone: formatPhone(e.target.value) })} inputMode="tel" placeholder="55 1234 5678" />{errs.phone && <span className="field-err">{errs.phone}</span>}</div>
                </div>
                <div><label className="field-label">Email *</label><input className={`field ${errs.email ? 'error' : ''}`} type="email" value={shipForm.email} onChange={(e) => setShipForm({ ...shipForm, email: e.target.value })} />{errs.email && <span className="field-err">{errs.email}</span>}</div>

                <h2 className="display" style={{ fontSize: 28, margin: '16px 0 0' }}>DIRECCIÓN DE ENVÍO</h2>
                <div className="grid-2">
                  <div style={{ gridColumn: 'span 2' }}><label className="field-label">Calle *</label><input className={`field ${errs.street ? 'error' : ''}`} value={shipForm.street} onChange={(e) => setShipForm({ ...shipForm, street: e.target.value })} /></div>
                  <div><label className="field-label">N° exterior *</label><input className="field" value={shipForm.ext} onChange={(e) => setShipForm({ ...shipForm, ext: e.target.value })} /></div>
                  <div><label className="field-label">N° interior</label><input className="field" value={shipForm.int} onChange={(e) => setShipForm({ ...shipForm, int: e.target.value })} /></div>
                  <div><label className="field-label">Colonia *</label><input className={`field ${errs.col ? 'error' : ''}`} value={shipForm.col} onChange={(e) => setShipForm({ ...shipForm, col: e.target.value })} /></div>
                  <div><label className="field-label">Ciudad *</label><input className={`field ${errs.city ? 'error' : ''}`} value={shipForm.city} onChange={(e) => setShipForm({ ...shipForm, city: e.target.value })} /></div>
                  <div><label className="field-label">Estado *</label>
                    <select className="field" value={shipForm.state} onChange={(e) => setShipForm({ ...shipForm, state: e.target.value })}>
                      {['CDMX', 'MEX', 'JAL', 'NL', 'QRO', 'PUE', 'GTO', 'MOR', 'SLP', 'VER'].map((s) => <option key={s}>{s}</option>)}
                    </select>
                  </div>
                  <div><label className="field-label">CP *</label><input className={`field ${errs.zip ? 'error' : ''}`} value={shipForm.zip} onChange={(e) => setShipForm({ ...shipForm, zip: formatZip(e.target.value) })} inputMode="numeric" maxLength={5} placeholder="·····" />{errs.zip && <span className="field-err">{errs.zip}</span>}</div>
                </div>

                <h2 className="display" style={{ fontSize: 28, margin: '16px 0 0' }}>MÉTODO DE ENVÍO</h2>
                <div style={{ display: 'grid', gap: 10 }}>
                  {[
              { id: 'standard', name: 'Estándar', sub: '2–4 días hábiles · Estafeta', price: subtotal > 2000 ? 0 : 199 },
              { id: 'express', name: 'Express', sub: '1–2 días hábiles · DHL', price: 349 },
              { id: 'pickup', name: 'Recoger en tienda', sub: 'Lista en 2h · 6 sucursales', price: 0 }].
              map((m) =>
              <label key={m.id} className="between" style={{ padding: '16px 20px', border: `1px solid ${shipForm.method === m.id ? 'var(--line-strong)' : 'var(--line)'}`, cursor: 'pointer', background: shipForm.method === m.id ? 'var(--bg-2)' : 'transparent' }}>
                      <div className="row" style={{ gap: 12 }}>
                        <input type="radio" checked={shipForm.method === m.id} onChange={() => setShipForm({ ...shipForm, method: m.id })} style={{ accentColor: 'var(--blood)' }} />
                        <div>
                          <div style={{ fontWeight: 500 }}>{m.name}</div>
                          <div className="mono" style={{ fontSize: 11, color: 'var(--text-muted)' }}>{m.sub}</div>
                        </div>
                      </div>
                      <span className="display" style={{ fontSize: 20 }}>{m.price === 0 ? 'GRATIS' : fmtMXN(m.price)}</span>
                    </label>
              )}
                </div>
              </div>
          }

            {step === 1 &&
          <div style={{ display: 'grid', gap: 20 }}>
                <h2 className="display" style={{ fontSize: 28, margin: 0 }}>MÉTODO DE PAGO</h2>
                <div style={{ display: 'grid', gap: 10 }}>
                  {[
              { id: 'card', name: 'Tarjeta crédito/débito', sub: 'Visa, Mastercard, AMEX · 12 MSI' },
              { id: 'mp', name: 'Mercado Pago', sub: 'Saldo, OXXO, débito' },
              { id: 'oxxo', name: 'OXXO Pay', sub: 'Pago en efectivo · referencia 24h' },
              { id: 'kueski', name: 'Kueski Pay', sub: 'A meses sin tarjeta' }].
              map((m) =>
              <label key={m.id} className="between" style={{ padding: '16px 20px', border: `1px solid ${payForm.method === m.id ? 'var(--line-strong)' : 'var(--line)'}`, cursor: 'pointer', background: payForm.method === m.id ? 'var(--bg-2)' : 'transparent' }}>
                      <div className="row" style={{ gap: 12 }}>
                        <input type="radio" checked={payForm.method === m.id} onChange={() => setPayForm({ ...payForm, method: m.id })} style={{ accentColor: 'var(--blood)' }} />
                        <div>
                          <div style={{ fontWeight: 500 }}>{m.name}</div>
                          <div className="mono" style={{ fontSize: 11, color: 'var(--text-muted)' }}>{m.sub}</div>
                        </div>
                      </div>
                    </label>
              )}
                </div>
                {payForm.method === 'card' &&
            <div style={{ padding: 24, background: 'var(--bg-2)', display: 'grid', gap: 16 }}>
                    <div><label className="field-label">Titular *</label><input className={`field ${errs.cardName ? 'error' : ''}`} value={payForm.cardName} onChange={(e) => setPayForm({ ...payForm, cardName: e.target.value.toUpperCase() })} placeholder="COMO APARECE EN LA TARJETA" autoComplete="cc-name" />{errs.cardName && <span className="field-err">{errs.cardName}</span>}</div>
                    <div><label className="field-label">Número de tarjeta *</label><input className={`field ${errs.cardNum ? 'error' : ''}`} value={payForm.cardNum} onChange={(e) => setPayForm({ ...payForm, cardNum: formatCardNum(e.target.value) })} inputMode="numeric" maxLength={19} placeholder="•••• •••• •••• ••••" autoComplete="cc-number" />{errs.cardNum && <span className="field-err">{errs.cardNum}</span>}</div>
                    <div className="grid-2">
                      <div><label className="field-label">Expira *</label><input className={`field ${errs.exp ? 'error' : ''}`} value={payForm.exp} onChange={(e) => setPayForm({ ...payForm, exp: formatExp(e.target.value) })} inputMode="numeric" maxLength={5} placeholder="MM/AA" autoComplete="cc-exp" />{errs.exp && <span className="field-err">{errs.exp}</span>}</div>
                      <div><label className="field-label">CVV *</label><input className={`field ${errs.cvv ? 'error' : ''}`} value={payForm.cvv} onChange={(e) => setPayForm({ ...payForm, cvv: formatCvv(e.target.value) })} inputMode="numeric" maxLength={4} placeholder="•••" autoComplete="cc-csc" />{errs.cvv && <span className="field-err">{errs.cvv}</span>}</div>
                    </div>
                    <label className="row" style={{ gap: 10, fontSize: 13 }}><input type="checkbox" defaultChecked style={{ accentColor: 'var(--blood)' }} /> Guardar tarjeta para próximas compras</label>
                  </div>
            }
                <h2 className="display" style={{ fontSize: 28, margin: '16px 0 0' }}>DIRECCIÓN DE FACTURACIÓN</h2>
                <label className="row" style={{ gap: 10, fontSize: 14 }}><input type="checkbox" defaultChecked style={{ accentColor: 'var(--blood)' }} /> Usar la misma dirección de envío</label>
              </div>
          }

            <div className="row mt-32" style={{ gap: 12, justifyContent: 'space-between' }}>
              {step > 0 ? <button className="btn ghost" onClick={() => setStep(step - 1)}>← Atrás</button> : <span />}
              <button className="btn primary lg" onClick={next}>
                {step === 0 ? 'Continuar al pago →' : 'Confirmar pedido →'}
              </button>
            </div>
          </div>

          <aside style={{ alignSelf: 'start', position: 'sticky', top: 100 }}>
            <div style={{ border: '1px solid var(--line-strong)', padding: 24 }}>
              <h3 className="display" style={{ fontSize: 22, margin: '0 0 16px' }}>TU PEDIDO ({items.length})</h3>
              <div style={{ maxHeight: 300, overflow: 'auto', display: 'grid', gap: 12 }}>
                {items.map((it) =>
              <div key={it.cartId} className="row" style={{ gap: 12 }}>
                    <div style={{ width: 56, height: 56, background: 'var(--surface)', border: '1px solid var(--line)', position: 'relative' }}>
                      <ProductArt product={it} dark={dark} />
                      <span style={{ position: 'absolute', top: -6, right: -6, width: 20, height: 20, background: 'var(--ink)', color: 'var(--bone)', borderRadius: '50%', fontFamily: 'var(--f-mono)', fontSize: 10, display: 'grid', placeItems: 'center' }}>{it.qty}</span>
                    </div>
                    <div style={{ flex: 1, fontSize: 12 }}>
                      <div style={{ fontWeight: 500 }}>{it.name}</div>
                      <div className="mono" style={{ fontSize: 10, color: 'var(--text-muted)' }}>{[it.size, it.colorName].filter(Boolean).join(' · ')}</div>
                    </div>
                    <div className="display" style={{ fontSize: 16 }}>{fmtMXN(it.price * it.qty)}</div>
                  </div>
              )}
              </div>
              <div className="divider" style={{ margin: '20px 0 12px' }} />
              <div className="between" style={{ fontSize: 13 }}><span className="mono" style={{ color: 'var(--text-muted)' }}>Subtotal</span><span>{fmtMXN(subtotal)}</span></div>
              <div className="between" style={{ fontSize: 13, marginTop: 8 }}><span className="mono" style={{ color: 'var(--text-muted)' }}>Envío</span><span>{shipping === 0 ? 'GRATIS' : fmtMXN(shipping)}</span></div>
              <div className="divider" style={{ margin: '12px 0' }} />
              <div className="between"><span className="mono">Total</span><span className="display" style={{ fontSize: 28, color: 'var(--blood)' }}>{fmtMXN(total)}</span></div>
            </div>
          </aside>
        </div> :

      // confirmation
      <div style={{ textAlign: 'center', padding: '40px 0', maxWidth: 680, margin: '0 auto' }}>
          <div style={{ width: 96, height: 96, borderRadius: '50%', background: 'var(--ok)', color: '#fff', display: 'grid', placeItems: 'center', margin: '0 auto 24px' }}>
            {Icon.check({ width: 48, height: 48 })}
          </div>
          <div className="eyebrow" style={{ color: 'var(--ok)' }}>Pedido confirmado</div>
          <h2 className="display" style={{ fontSize: 56, margin: '12px 0' }}>¡A RODAR!</h2>
          <p className="lead" style={{ color: 'var(--text-muted)', maxWidth: 480, margin: '0 auto 32px' }}>
            Tu pedido <strong style={{ color: 'var(--text)' }}>#BKM-{Math.floor(Math.random() * 900000 + 100000)}</strong> está en preparación. Te llegará confirmación a <strong style={{ color: 'var(--text)' }}>{shipForm.email || 'tu correo'}</strong>.
          </p>
          <div style={{ padding: 24, border: '1px solid var(--line)', textAlign: 'left', display: 'grid', gap: 14 }}>
            <div className="between"><span className="mono" style={{ color: 'var(--text-muted)', fontSize: 11 }}>Total cobrado</span><span className="display" style={{ fontSize: 24 }}>{fmtMXN(total)}</span></div>
            <div className="between"><span className="mono" style={{ color: 'var(--text-muted)', fontSize: 11 }}>Entrega estimada</span><span>22–25 MAY 2026</span></div>
            <div className="between"><span className="mono" style={{ color: 'var(--text-muted)', fontSize: 11 }}>Paquetería</span><span>{shipForm.method === 'express' ? 'DHL Express' : shipForm.method === 'pickup' ? 'Recoger en sucursal' : 'Estafeta'}</span></div>
          </div>
          <div className="row mt-32" style={{ gap: 12, justifyContent: 'center' }}>
            <button className="btn primary lg" onClick={() => navigate('account', { tab: 'orders' })}>Ver mis pedidos</button>
            <button className="btn ghost lg" onClick={() => navigate('home')}>Volver al inicio</button>
          </div>
        </div>
      }
    </div>);

}

// ============ LOGIN PAGE (also accessible as full page) ============
function PageLogin({ onLogin, navigate }) {
  return (
    <div className="login-layout">
      <div style={{ background: 'var(--ink)', color: 'var(--bone)', padding: '80px 60px', position: 'relative', overflow: 'hidden', display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
        <div>
          <div className="eyebrow" style={{ color: '#ffffff90' }}>BK MOTO · BIENVENIDO</div>
          <h2 className="display" style={{ fontSize: 64, lineHeight: .92, margin: '16px 0', color: 'var(--bone)' }}>
            Tu garage<br />en la nube.
          </h2>
          <p style={{ color: '#ffffffa0', maxWidth: 380, fontSize: 16 }}>
            Guarda direcciones, sigue tus pedidos, accede a precios exclusivos y obtén soporte directo del taller.
          </p>
        </div>
        <svg viewBox="0 0 300 200" style={{ maxWidth: 300 }}>
          <circle cx="150" cy="100" r="70" fill="none" stroke="var(--blood)" strokeWidth="18" strokeDasharray="220 30" transform="rotate(-20 150 100)" />
        </svg>
      </div>
      <div style={{ padding: '80px 60px', display: 'grid', placeContent: 'center' }}>
        <LoginInner onLogin={onLogin} navigate={navigate} />
      </div>
    </div>);

}

function LoginInner({ onLogin, navigate }) {
  const [tab, setTab] = useState('login');
  const [email, setEmail] = useState('');
  const [pass, setPass] = useState('');
  const [name, setName] = useState('');
  const [err, setErr] = useState({});
  const [loading, setLoading] = useState(false);
  const submit = (e) => {
    e.preventDefault();
    const errs = {};
    if (!email.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) errs.email = 'Email no válido';
    if (pass.length < 6) errs.pass = 'Mínimo 6 caracteres';
    if (tab === 'register' && name.length < 2) errs.name = 'Nombre requerido';
    setErr(errs);if (Object.keys(errs).length) return;
    setLoading(true);
    setTimeout(() => {setLoading(false);onLogin({ name: tab === 'register' ? name : email.split('@')[0].replace(/[._]/g, ' '), email });navigate('account');}, 600);
  };
  return (
    <div className="auth-form-wrap">
      <h1 className="display" style={{ fontSize: 'clamp(36px, 5vw, 48px)', margin: '0 0 8px', lineHeight: .95 }}>{tab === 'login' ? 'Hola de nuevo' : 'Crea tu cuenta'}</h1>
      <p className="lead" style={{ color: 'var(--text-muted)', margin: 0, marginBottom: 28 }}>{tab === 'login' ? 'Entra y sigue donde te quedaste.' : 'Es gratis. Es rápido. Tu siguiente pedido te lo agradece.'}</p>
      <div className="tabs" style={{ marginBottom: 24 }}>
        <a className={`tab ${tab === 'login' ? 'on' : ''}`} onClick={() => setTab('login')}>Iniciar sesión</a>
        <a className={`tab ${tab === 'register' ? 'on' : ''}`} onClick={() => setTab('register')}>Crear cuenta</a>
      </div>
      <form onSubmit={submit}>
        <div><label className="field-label">Nombre completo {tab==='register' && '*'}</label>
          <input className={`field ${err.name ? 'error' : ''}`} value={name} onChange={(e) => setName(e.target.value)} placeholder={tab==='login' ? 'Opcional para login' : 'Tu nombre'} disabled={tab==='login'} style={tab==='login' ? {opacity:.5} : {}}/>
          {err.name && <span className="field-err">{err.name}</span>}
        </div>
        <div><label className="field-label">Email *</label><input className={`field ${err.email ? 'error' : ''}`} type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="tu@email.com" />{err.email && <span className="field-err">{err.email}</span>}</div>
        <div><label className="field-label">Contraseña *</label><input className={`field ${err.pass ? 'error' : ''}`} type="password" value={pass} onChange={(e) => setPass(e.target.value)} placeholder="Mínimo 6 caracteres" />{err.pass && <span className="field-err">{err.pass}</span>}</div>
        {tab === 'login' && <a className="mono" style={{ fontSize: 11, color: 'var(--blood)', cursor: 'pointer' }}>¿Olvidaste tu contraseña?</a>}
        <button className="btn primary block lg" disabled={loading}>{loading ? 'Procesando…' : tab === 'login' ? 'Entrar →' : 'Crear cuenta →'}</button>
        <div className="mono center" style={{ color: 'var(--text-muted)', fontSize: 11 }}>o continúa con</div>
        <div className="grid-2"><button type="button" className="btn ghost">Google</button><button type="button" className="btn ghost">Apple</button></div>
      </form>
    </div>);

}

// ============ ACCOUNT ============
function PageAccount({ user, onLogout, navigate, favs, dark, route }) {
  const tab = route.tab || 'dashboard';
  const setTab = (t) => navigate('account', { tab: t });

  const navItems = [
    { id:'dashboard', label:'Dashboard' },
    { id:'orders', label:'Mis pedidos' },
    { id:'addresses', label:'Direcciones' },
    { id:'wishlist', label:`Wishlist (${favs.size})` },
    { id:'garage', label:'Mi garage' },
    { id:'settings', label:'Configuración' },
  ];
  const data = window.BK_DATA;
  const favProducts = data.PRODUCTS.filter((p) => favs.has(p.id));

  // Mock orders
  const orders = [
  { id: 'BKM-928410', date: '02 MAY 2026', total: 14580, status: 'delivered', items: [data.PRODUCTS[0], data.PRODUCTS[15]] },
  { id: 'BKM-927103', date: '18 ABR 2026', total: 8490, status: 'transit', items: [data.PRODUCTS[27]] },
  { id: 'BKM-925821', date: '04 ABR 2026', total: 3290, status: 'delivered', items: [data.PRODUCTS[11]] },
  { id: 'BKM-924592', date: '22 MAR 2026', total: 6890, status: 'delivered', items: [data.PRODUCTS[8]] }];


  return (
    <div className="wrap acc-layout">
      <aside className="acc-nav">
        <div style={{ padding: '12px 14px', borderBottom: '1px solid var(--line)', marginBottom: 14 }}>
          <div className="eyebrow">Hola</div>
          <div className="display" style={{ fontSize: 22, marginTop: 4, textTransform: 'capitalize' }}>{user?.name || 'Rider'}</div>
          <div className="mono" style={{ fontSize: 10, color: 'var(--text-muted)' }}>{user?.email || 'rider@bkmoto.mx'}</div>
        </div>

        <div className="acc-nav-mobile">
          <label className="field-label" style={{marginBottom:8}}>Sección de la cuenta</label>
          <select className="field acc-nav-select" value={tab} onChange={(e)=>setTab(e.target.value)}>
            {navItems.map(it => <option key={it.id} value={it.id}>{it.label}</option>)}
          </select>
        </div>

        <div className="acc-nav-list">
          {navItems.map(it => (
            <button key={it.id} onClick={() => setTab(it.id)} className={tab === it.id ? 'on' : ''}>{it.label}</button>
          ))}
          <div className="divider" />
          <button onClick={onLogout} style={{ color: 'var(--blood)' }}>Cerrar sesión</button>
        </div>
      </aside>

      <div>
        {tab === 'dashboard' &&
        <div>
            <div className="eyebrow">PANEL</div>
            <h1 className="display" style={{ fontSize: 'clamp(40px, 6vw, 64px)', margin: '8px 0 24px', textTransform: 'none', letterSpacing: '-0.005em' }}>Bienvenido, {user?.name?.split(' ')[0] || 'Rider'}.</h1>
            <div className="grid-3" style={{ marginBottom: 40 }}>
              {[
            { lab: 'Pedidos totales', val: '12', sub: 'desde 2024' },
            { lab: 'En tránsito', val: '1', sub: 'BKM-927103' },
            { lab: 'Puntos BK', val: '2,840', sub: '$284 MXN de saldo' }].
            map((s, i) =>
            <div key={i} style={{ padding: 24, border: '1px solid var(--line)' }}>
                  <div className="eyebrow">{s.lab}</div>
                  <div className="display" style={{ fontSize: 48, color: 'var(--blood)', margin: '8px 0' }}>{s.val}</div>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--text-muted)' }}>{s.sub}</div>
                </div>
            )}
            </div>
            <h2 className="display" style={{ fontSize: 32 }}>Pedidos recientes</h2>
            <div style={{ display: 'grid', gap: 14, marginTop: 16 }}>
              {orders.slice(0, 2).map((o) => <OrderCard key={o.id} order={o} dark={dark} navigate={navigate} />)}
            </div>
            <a className="mono mt-16" style={{ display: 'inline-block', cursor: 'pointer', color: 'var(--blood)', textDecoration: 'underline' }} onClick={() => setTab('orders')}>Ver todos los pedidos →</a>
          </div>
        }

        {tab === 'orders' &&
        <div>
            <div className="between" style={{ marginBottom: 24 }}>
              <h1 className="display" style={{ fontSize: 48, margin: 0 }}>MIS PEDIDOS</h1>
              <select className="field" style={{ width: 'auto' }}>
                <option>Todos los pedidos</option><option>Últimos 6 meses</option><option>2026</option><option>2025</option>
              </select>
            </div>
            <div style={{ display: 'grid', gap: 14 }}>
              {orders.map((o) => <OrderCard key={o.id} order={o} dark={dark} navigate={navigate} expanded />)}
            </div>
          </div>
        }

        {tab === 'wishlist' &&
        <div>
            <h1 className="display" style={{ fontSize: 48, margin: '0 0 24px' }}>WISHLIST <span style={{ color: 'var(--blood)' }}>· {favProducts.length}</span></h1>
            {favProducts.length === 0 ?
          <div style={{ padding: '60px 0', textAlign: 'center' }}>
                <div style={{ fontSize: 48, color: 'var(--blood)', opacity: .3 }}>{Icon.heart({ width: 64, height: 64 })}</div>
                <p style={{ color: 'var(--text-muted)' }} className="mt-16">No has guardado nada todavía.</p>
                <button className="btn primary mt-16" onClick={() => navigate('shop')}>Explorar tienda</button>
              </div> :

          <div className="product-list">
                {favProducts.map((p) =>
            <ProductRow key={p.id} product={p} dark={dark}
              isFav={true}
              onAddToCart={(prod, btn) => window.BK_APP?.addToCart(prod, btn)}
              onToggleFav={(id) => window.BK_APP?.toggleFav(id)}
              onQuickView={(prod) => window.BK_APP?.openQuick(prod)}
              navigate={navigate} />

            )}
              </div>
          }
          </div>
        }

        {tab === 'addresses' &&
        <div>
            <div className="between" style={{ marginBottom: 24 }}>
              <h1 className="display" style={{ fontSize: 48, margin: 0 }}>DIRECCIONES</h1>
              <button className="btn primary">+ Nueva dirección</button>
            </div>
            <div className="grid-2">
              {[
            { name: 'Casa', addr: 'Av. Álvaro Obregón 152, Roma Nte., CDMX 06700', tel: '(55) 1234 5678', def: true },
            { name: 'Oficina', addr: 'Insurgentes Sur 1898, Florida, CDMX 01030', tel: '(55) 9876 5432' },
            { name: 'Casa de mis papás', addr: 'Av. Niños Héroes 2531, Chapalita, GDL 44500', tel: '(33) 5555 5555' }].
            map((a, i) =>
            <div key={i} style={{ padding: 24, border: '1px solid var(--line)', position: 'relative' }}>
                  {a.def && <span className="pcard-badge blood" style={{ position: 'absolute', top: -1, right: -1 }}>Predeterminada</span>}
                  <h3 className="display" style={{ fontSize: 24, margin: '0 0 8px' }}>{a.name.toUpperCase()}</h3>
                  <p style={{ margin: 0, fontSize: 14 }}>{a.addr}</p>
                  <p style={{ margin: '4px 0 16px', fontSize: 13, color: 'var(--text-muted)' }}>{a.tel}</p>
                  <div className="row" style={{ gap: 8 }}>
                    <button className="btn ghost sm">Editar</button>
                    <button className="btn ghost sm" style={{ color: 'var(--blood)', borderColor: 'var(--blood)' }}>Eliminar</button>
                  </div>
                </div>
            )}
            </div>
          </div>
        }

        {tab === 'garage' &&
        <div>
            <div className="between" style={{ marginBottom: 24 }}>
              <div>
                <h1 className="display" style={{ fontSize: 48, margin: 0 }}>MI GARAGE</h1>
                <p className="lead" style={{ color: 'var(--text-muted)' }}>Tus motos y vehículos guardados para filtrar refacciones compatibles.</p>
              </div>
              <button className="btn primary">+ Agregar vehículo</button>
            </div>
            <div className="grid-2">
              {[
            { make: 'YAMAHA MT-07', year: '2023', cc: '689cc', plate: 'GFA-823' },
            { make: 'KAWASAKI Z400', year: '2022', cc: '399cc', plate: 'NHB-491' }].
            map((v, i) =>
            <div key={i} style={{ padding: 24, border: '1px solid var(--line)', display: 'grid', gap: 14 }}>
                  <div className="eyebrow">VEHÍCULO {String(i + 1).padStart(2, '0')}</div>
                  <h3 className="display" style={{ fontSize: 36, margin: 0 }}>{v.make}</h3>
                  <div className="grid-3" style={{ gap: 14 }}>
                    <div><div className="mono" style={{ fontSize: 10, color: 'var(--text-muted)' }}>AÑO</div><div className="display" style={{ fontSize: 22 }}>{v.year}</div></div>
                    <div><div className="mono" style={{ fontSize: 10, color: 'var(--text-muted)' }}>CILINDRADA</div><div className="display" style={{ fontSize: 22 }}>{v.cc}</div></div>
                    <div><div className="mono" style={{ fontSize: 10, color: 'var(--text-muted)' }}>PLACA</div><div className="display" style={{ fontSize: 22 }}>{v.plate}</div></div>
                  </div>
                  <button className="btn ghost sm" style={{ justifySelf: 'start' }}>Ver refacciones compatibles →</button>
                </div>
            )}
            </div>
          </div>
        }

        {tab === 'settings' &&
        <div>
            <h1 className="display" style={{ fontSize: 48, margin: '0 0 24px' }}>CONFIGURACIÓN</h1>
            <div style={{ display: 'grid', gap: 24, maxWidth: 600 }}>
              <div><label className="field-label">Nombre</label><input className="field" defaultValue={user?.name} /></div>
              <div><label className="field-label">Email</label><input className="field" defaultValue={user?.email} /></div>
              <div><label className="field-label">Teléfono</label><input className="field" placeholder="55 1234 5678" /></div>
              <div className="divider" />
              <h3 className="display" style={{ fontSize: 24, margin: 0 }}>NOTIFICACIONES</h3>
              {['Confirmaciones de pedido', 'Promociones y descuentos', 'Nuevos productos en mi categoría', 'Newsletter mensual'].map((n) =>
            <label key={n} className="between" style={{ padding: '12px 0', borderBottom: '1px solid var(--line)' }}>
                  <span>{n}</span>
                  <input type="checkbox" defaultChecked style={{ accentColor: 'var(--blood)', transform: 'scale(1.3)' }} />
                </label>
            )}
              <button className="btn primary lg" style={{ justifySelf: 'start' }}>Guardar cambios</button>
            </div>
          </div>
        }
      </div>
    </div>);

}

function OrderCard({ order, dark, navigate, expanded }) {
  const data = window.BK_DATA;
  const statusLabel = { delivered: 'Entregado', transit: 'En tránsito', pending: 'Procesando' };
  return (
    <div className="order">
      <div className="order-head">
        <div className="row" style={{ gap: 14 }}>
          <span className={`order-status ${order.status}`}>{statusLabel[order.status]}</span>
          <div>
            <div className="mono" style={{ fontSize: 11 }}>#{order.id}</div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--text-muted)' }}>{order.date}</div>
          </div>
        </div>
        <div className="row" style={{ gap: 14 }}>
          <div className="display" style={{ fontSize: 24 }}>{fmtMXN(order.total)}</div>
          <button className="btn ghost sm">Ver detalle</button>
        </div>
      </div>
      {expanded &&
      <div className="row" style={{ gap: 12, paddingTop: 12, borderTop: '1px solid var(--line)', flexWrap: 'wrap' }}>
          {order.items.map((it) =>
        <div key={it.id} className="row" style={{ gap: 10 }}>
              <div style={{ width: 48, height: 48, background: 'var(--surface)', border: '1px solid var(--line)' }}><ProductArt product={it} dark={dark} /></div>
              <div style={{ fontSize: 12 }}>
                <div style={{ fontWeight: 500 }}>{it.name}</div>
                <div className="mono" style={{ fontSize: 10, color: 'var(--text-muted)' }}>{it.brand}</div>
              </div>
            </div>
        )}
        </div>
      }
    </div>);

}

// ============ WISHLIST page ============
function PageWishlist({ favs, navigate, onAddToCart, onToggleFav, onQuickView, dark, accent, cardVariant, density }) {
  const products = window.BK_DATA.PRODUCTS.filter((p) => favs.has(p.id));
  return (
    <div className="wrap section">
      <div className="mono" style={{ color: 'var(--text-muted)', marginBottom: 14 }}>
        <a onClick={() => navigate('home')} style={{ cursor: 'pointer' }}>Inicio</a><span style={{ margin: '0 8px' }}>/</span><span style={{ color: 'var(--text)' }}>Wishlist</span>
      </div>
      <header className="page-header">
        <div>
          <div className="eyebrow">Tus favoritos</div>
          <h1 className="display page-title">WISHLIST</h1>
        </div>
        <div className="display" style={{ fontSize: 'clamp(36px, 5vw, 56px)', color: 'var(--blood)' }}>{products.length}</div>
      </header>
      {products.length === 0 ?
      <div style={{ padding: '80px 0', textAlign: 'center' }} data-comment-anchor="0ebfb9fa33-div-600-9">
          <div style={{ color: 'var(--blood)', opacity: .3, marginBottom: 20 }}>{Icon.heart({ width: 96, height: 96 })}</div>
          <h2 className="display" style={{ fontSize: 32 }}>SIN FAVORITOS AÚN</h2>
          <p style={{ color: 'var(--text-muted)', maxWidth: 380, margin: '0 auto 24px' }}>Mientras navegas, presiona el corazón en cualquier producto para guardarlo aquí.</p>
          <button className="btn primary lg" onClick={() => navigate('shop')}>Explorar tienda →</button>
        </div> :

      <div className="product-list">
          {products.map((p) =>
        <ProductRow key={p.id} product={p} dark={dark} accent={accent}
          isFav={true} onAddToCart={onAddToCart} onToggleFav={onToggleFav} onQuickView={onQuickView}
          navigate={navigate} />
        )}
        </div>
      }
    </div>);

}

// ============ SEARCH ============
function PageSearch({ route, navigate, onAddToCart, onToggleFav, onQuickView, favs, dark, accent, cardVariant, density }) {
  const q = route.q || '';
  const data = window.BK_DATA;
  const norm = (s) => s.toLowerCase();
  const results = data.PRODUCTS.filter((p) =>
  norm(p.name).includes(norm(q)) ||
  norm(p.brand).includes(norm(q)) ||
  p.tags.some((t) => norm(t).includes(norm(q))) ||
  norm(data.CATEGORIES.find((c) => c.slug === p.cat)?.name || '').includes(norm(q))
  );
  return (
    <div className="wrap section">
      <div className="eyebrow">Búsqueda</div>
      <h1 className="display" style={{ fontSize: 'clamp(40px, 5vw, 64px)', margin: '8px 0' }}>"{q}"</h1>
      <p style={{ color: 'var(--text-muted)', marginBottom: 32 }}><strong style={{ color: 'var(--blood)' }}>{results.length}</strong> resultados encontrados</p>

      {results.length === 0 ?
      <div style={{ padding: '40px 0' }}>
          <h2 className="display" style={{ fontSize: 32 }}>NO ENCONTRAMOS NADA</h2>
          <p style={{ color: 'var(--text-muted)' }}>Pero quizá te interese alguno de estos:</p>
          <div className="card-grid mt-24" style={{ '--cols': density }}>
            {data.PRODUCTS.filter((p) => p.badge === 'top').slice(0, 4).map((p) =>
          <ProductCard key={p.id} product={p} variant={cardVariant} dark={dark} accent={accent}
          isFav={favs.has(p.id)} onAddToCart={onAddToCart} onToggleFav={onToggleFav} onQuickView={onQuickView} />
          )}
          </div>
        </div> :

      <div className="card-grid" style={{ '--cols': density }}>
          {results.map((p) =>
        <ProductCard key={p.id} product={p} variant={cardVariant} dark={dark} accent={accent}
        isFav={favs.has(p.id)} onAddToCart={onAddToCart} onToggleFav={onToggleFav} onQuickView={onQuickView} />
        )}
        </div>
      }
    </div>);

}

Object.assign(window, { PageCart, PageCheckout, PageLogin, PageAccount, PageWishlist, PageSearch });