// Cart page, Checkout, Search results, Brand/About pages

function PageCart({ mobile }) {
  const { cart, updateQty, removeFromCart, go } = useApp();
  const subtotal = cart.reduce((a, b) => a + b.price * b.qty, 0);
  const shipping = subtotal > 2500 ? 0 : 180;

  return (
    <main>
      <section style={{ padding: mobile ? '24px 16px' : '40px 40px 0' }}>
        <div className="eyebrow eyebrow-accent" style={{ marginBottom: 12 }}>— Il Carrello</div>
        <h1 className="font-display" style={{ fontSize: mobile ? 44 : 72, margin: 0, fontWeight: 400, letterSpacing: '-0.02em', lineHeight: 1 }}>
          Tu <em>carrito</em>
        </h1>
        <div className="eyebrow" style={{ marginTop: 10 }}>{cart.length} ARTÍCULOS · {fmtMXN(subtotal)}</div>
      </section>

      <section style={{ padding: mobile ? '24px 16px 40px' : '48px 40px 40px', display: 'grid', gridTemplateColumns: mobile ? '1fr' : '1.5fr 1fr', gap: mobile ? 32 : 56 }}>
        <div>
          <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : '2fr 1fr 1fr 1fr', padding: '12px 0', borderBottom: '1px solid var(--rule)' }}>
            <span className="eyebrow">PRODUCTO</span>
            {!mobile && <><span className="eyebrow" style={{ textAlign: 'center' }}>CANTIDAD</span><span className="eyebrow" style={{ textAlign: 'center' }}>PRECIO</span><span className="eyebrow" style={{ textAlign: 'right' }}>TOTAL</span></>}
          </div>
          {cart.map((it, i) => (
            <div key={i} style={{ display: 'grid', gridTemplateColumns: mobile ? '100px 1fr' : '2fr 1fr 1fr 1fr', gap: 16, padding: '24px 0', borderBottom: '1px solid var(--rule)', alignItems: 'center' }}>
              <div style={{ display: 'grid', gridTemplateColumns: '100px 1fr', gap: 16, gridColumn: mobile ? 'span 2' : 'auto' }}>
                <PH ratio="4/5" style={{ border: '1px solid var(--rule)' }}/>
                <div>
                  <div className="eyebrow" style={{ fontSize: 10 }}>{it.sku}</div>
                  <div className="font-serif" style={{ fontSize: 18, fontWeight: 500, marginTop: 4 }}>{it.name}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{it.variant}</div>
                  <button onClick={() => removeFromCart(it.id, it.variant)} style={{ marginTop: 8, fontSize: 11, color: 'var(--ink-3)', textDecoration: 'underline' }}>Eliminar</button>
                </div>
              </div>
              {!mobile && <>
                <div style={{ display: 'flex', border: '1px solid var(--rule)', justifySelf: 'center' }}>
                  <button onClick={() => updateQty(it.id, it.variant, it.qty - 1)} style={{ padding: '8px 12px' }}>−</button>
                  <span style={{ padding: '8px 14px', fontFamily: 'var(--font-mono)', fontSize: 13, borderLeft: '1px solid var(--rule)', borderRight: '1px solid var(--rule)' }}>{it.qty}</span>
                  <button onClick={() => updateQty(it.id, it.variant, it.qty + 1)} style={{ padding: '8px 12px' }}>+</button>
                </div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 14, textAlign: 'center' }}>{fmtMXN(it.price)}</div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 14, textAlign: 'right' }}>{fmtMXN(it.price * it.qty)}</div>
              </>}
              {mobile && (
                <div style={{ gridColumn: 'span 2', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div style={{ display: 'flex', border: '1px solid var(--rule)' }}>
                    <button onClick={() => updateQty(it.id, it.variant, it.qty - 1)} style={{ padding: '6px 12px' }}>−</button>
                    <span style={{ padding: '6px 12px', fontFamily: 'var(--font-mono)', fontSize: 12 }}>{it.qty}</span>
                    <button onClick={() => updateQty(it.id, it.variant, it.qty + 1)} style={{ padding: '6px 12px' }}>+</button>
                  </div>
                  <div className="font-mono" style={{ fontSize: 14 }}>{fmtMXN(it.price * it.qty)}</div>
                </div>
              )}
            </div>
          ))}
        </div>

        <aside style={{ position: mobile ? 'static' : 'sticky', top: 140, height: 'fit-content' }}>
          <div style={{ background: 'var(--bg-sunk)', padding: 28, border: '1px solid var(--rule)' }}>
            <div className="font-display" style={{ fontSize: 24, fontStyle: 'italic', marginBottom: 20 }}>Resumen del pedido</div>
            <div style={{ display: 'grid', gap: 10 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
                <span style={{ color: 'var(--ink-2)' }}>Subtotal</span>
                <span className="font-mono">{fmtMXN(subtotal)}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
                <span style={{ color: 'var(--ink-2)' }}>Envío</span>
                <span className="font-mono">{shipping === 0 ? 'Gratis' : fmtMXN(shipping)}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
                <span style={{ color: 'var(--ink-2)' }}>IVA incluido</span>
                <span className="font-mono" style={{ color: 'var(--ink-3)' }}>—</span>
              </div>
            </div>
            <div style={{ borderTop: '1px solid var(--rule)', margin: '20px 0', paddingTop: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
              <span className="font-display" style={{ fontSize: 24, fontStyle: 'italic' }}>Total</span>
              <span className="font-mono" style={{ fontSize: 22 }}>{fmtMXN(subtotal + shipping)}</span>
            </div>
            <input placeholder="Código de descuento" style={{ width: '100%', padding: 12, border: '1px solid var(--rule)', background: 'var(--bg)', outline: 'none', marginBottom: 12 }}/>
            <button onClick={() => go('checkout')} className="btn btn-primary btn-block btn-lg">Ir al checkout</button>
            <div className="eyebrow" style={{ textAlign: 'center', marginTop: 14, fontSize: 10 }}>PAGO SEGURO · VISA · MC · AMEX · OXXO</div>
          </div>
        </aside>
      </section>

      <Footer/>
    </main>
  );
}

function PageCheckout({ mobile }) {
  const { cart, go } = useApp();
  const subtotal = cart.reduce((a, b) => a + b.price * b.qty, 0);
  const [step, setStep] = useState(2);

  return (
    <main style={{ background: 'var(--bg)' }}>
      {/* Minimal header */}
      <div style={{ borderBottom: '1px solid var(--rule)', padding: mobile ? '14px 16px' : '20px 40px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <button onClick={() => go('home')}><Logo size={20}/></button>
        <div className="eyebrow">CHECKOUT SEGURO · SSL 🔒</div>
      </div>

      <section style={{ padding: mobile ? '24px 16px' : '40px 40px', display: 'grid', gridTemplateColumns: mobile ? '1fr' : '1.3fr 1fr', gap: mobile ? 32 : 80, maxWidth: 1440, margin: '0 auto' }}>
        <div>
          {/* Progress */}
          <div style={{ display: 'flex', gap: 4, marginBottom: 32 }}>
            {['Carrito', 'Envío', 'Pago'].map((s, i) => (
              <div key={i} style={{ flex: 1 }}>
                <div style={{ height: 2, background: i <= step - 1 ? 'var(--ink)' : 'var(--rule)', marginBottom: 6 }}/>
                <div className="eyebrow" style={{ color: i <= step - 1 ? 'var(--ink)' : 'var(--ink-3)' }}>0{i+1} · {s}</div>
              </div>
            ))}
          </div>

          {/* Contact */}
          <div style={{ marginBottom: 32 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 14 }}>
              <h2 className="font-display" style={{ fontSize: 24, fontStyle: 'italic', margin: 0 }}>Contacto</h2>
              <button className="eyebrow" style={{ textDecoration: 'underline' }}>Iniciar sesión</button>
            </div>
            <Field label="Email" value="carlos@ejemplo.com"/>
            <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, marginTop: 10, color: 'var(--ink-2)' }}>
              <input type="checkbox" defaultChecked/> Enviarme ofertas y novedades
            </label>
          </div>

          {/* Shipping */}
          <div>
            <h2 className="font-display" style={{ fontSize: 24, fontStyle: 'italic', margin: 0, marginBottom: 14 }}>Envío</h2>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <Field label="Nombre" value="Carlos"/>
              <Field label="Apellido" value="Ramírez"/>
              <Field label="Dirección" value="Av. Horacio 1234" span/>
              <Field label="Depto / Interior" value="Piso 4"/>
              <Field label="Colonia" value="Polanco IV"/>
              <Field label="Ciudad" value="Ciudad de México"/>
              <Field label="Código postal" value="11550"/>
              <Field label="Estado" value="CDMX"/>
              <Field label="Teléfono" value="+52 55 1234 5678" span/>
            </div>

            <h3 className="eyebrow" style={{ marginTop: 28, marginBottom: 12 }}>MÉTODO DE ENVÍO</h3>
            {[
              ['Express · 24h', 'CDMX · mismo día antes de 14:00', 180],
              ['Estándar · 2–4 días', 'Resto de la república', 0],
              ['Recoger en boutique', 'Polanco · sin costo', 0],
            ].map((o, i) => (
              <label key={i} style={{ display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 12, alignItems: 'center', padding: '14px 16px', border: i === 1 ? '1px solid var(--ink)' : '1px solid var(--rule)', marginBottom: 6, cursor: 'pointer' }}>
                <input type="radio" name="ship" defaultChecked={i === 1}/>
                <div>
                  <div style={{ fontSize: 14, fontWeight: 500 }}>{o[0]}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{o[1]}</div>
                </div>
                <div className="font-mono" style={{ fontSize: 13 }}>{o[2] === 0 ? 'Gratis' : fmtMXN(o[2])}</div>
              </label>
            ))}
          </div>

          {/* Payment */}
          <div style={{ marginTop: 32 }}>
            <h2 className="font-display" style={{ fontSize: 24, fontStyle: 'italic', margin: 0, marginBottom: 14 }}>Pago</h2>
            {['Tarjeta de crédito / débito', 'PayPal', 'Mercado Pago', 'OXXO Pay'].map((o, i) => (
              <label key={i} style={{ display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 12, alignItems: 'center', padding: '14px 16px', border: i === 0 ? '1px solid var(--ink)' : '1px solid var(--rule)', marginBottom: 6, cursor: 'pointer' }}>
                <input type="radio" name="pay" defaultChecked={i === 0}/>
                <div style={{ fontSize: 14, fontWeight: 500 }}>{o}</div>
                {i === 0 && <div style={{ display: 'flex', gap: 4 }}>{['VISA','MC','AMEX'].map(c => <span key={c} className="font-mono" style={{ fontSize: 9, border: '1px solid var(--rule)', padding: '2px 4px' }}>{c}</span>)}</div>}
              </label>
            ))}

            <div style={{ marginTop: 16, padding: 16, background: 'var(--bg-sunk)', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <Field label="Número de tarjeta" value="4242 4242 •••• 4242" span/>
              <Field label="MM / AA" value="12 / 28"/>
              <Field label="CVV" value="•••"/>
              <label style={{ gridColumn: 'span 2', display: 'flex', gap: 8, fontSize: 12, color: 'var(--ink-2)', marginTop: 4 }}>
                <input type="checkbox" defaultChecked/> Pagar en 12 MSI
              </label>
            </div>
          </div>

          <button className="btn btn-primary btn-block btn-lg" style={{ marginTop: 28 }}>Completar compra · {fmtMXN(subtotal)}</button>
        </div>

        {/* Summary */}
        <aside style={{ position: mobile ? 'static' : 'sticky', top: 100, height: 'fit-content' }}>
          <div style={{ padding: 28, background: 'var(--bg-sunk)', border: '1px solid var(--rule)' }}>
            <div className="eyebrow" style={{ marginBottom: 16 }}>— Tu pedido</div>
            {cart.map((it, i) => (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '64px 1fr auto', gap: 12, padding: '12px 0', borderBottom: '1px solid var(--rule)', alignItems: 'center' }}>
                <div style={{ position: 'relative' }}>
                  <PH ratio="1/1" style={{ border: '1px solid var(--rule)' }}/>
                  <span style={{ position: 'absolute', top: -6, right: -6, background: 'var(--ink)', color: 'var(--bg)', fontFamily: 'var(--font-mono)', fontSize: 9, width: 18, height: 18, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{it.qty}</span>
                </div>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{it.name}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{it.variant}</div>
                </div>
                <div className="font-mono" style={{ fontSize: 13 }}>{fmtMXN(it.price * it.qty)}</div>
              </div>
            ))}
            <div style={{ padding: '16px 0 8px', display: 'grid', gap: 8 }}>
              <Row l="Subtotal" r={fmtMXN(subtotal)}/>
              <Row l="Envío" r="Gratis"/>
            </div>
            <div style={{ borderTop: '1px solid var(--rule)', paddingTop: 14, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
              <span className="font-display" style={{ fontSize: 22, fontStyle: 'italic' }}>Total</span>
              <span className="font-mono" style={{ fontSize: 20 }}>{fmtMXN(subtotal)}</span>
            </div>
          </div>
        </aside>
      </section>
    </main>
  );
}

function Field({ label, value, span }) {
  return (
    <div style={{ gridColumn: span ? 'span 2' : 'auto', marginBottom: 2 }}>
      <div className="eyebrow" style={{ fontSize: 10, marginBottom: 4 }}>{label}</div>
      <input defaultValue={value} style={{ width: '100%', padding: 12, border: '1px solid var(--rule)', background: 'var(--bg)', outline: 'none', fontSize: 14 }}/>
    </div>
  );
}
function Row({ l, r }) {
  return <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}><span style={{ color: 'var(--ink-2)' }}>{l}</span><span className="font-mono">{r}</span></div>;
}

// ============ Search Results Page ============
function PageSearch({ mobile }) {
  const all = [...PRODUCTS, ...PRODUCTS.slice(0, 4)];
  return (
    <main>
      <section style={{ padding: mobile ? '24px 16px' : '40px 40px 0' }}>
        <div className="eyebrow" style={{ marginBottom: 12 }}>— Resultados para</div>
        <h1 className="font-display" style={{ fontSize: mobile ? 44 : 72, margin: 0, fontWeight: 400, letterSpacing: '-0.02em', fontStyle: 'italic', lineHeight: 1 }}>"casco agv"</h1>
        <div className="eyebrow" style={{ marginTop: 10 }}>{all.length} productos · 3 marcas · 2 categorías</div>

        <div style={{ display: 'flex', gap: 8, marginTop: 28, flexWrap: 'wrap' }}>
          {['Todos (16)', 'Cascos (14)', 'Accesorios (2)', 'AGV (12)', 'Shoei (3)', 'HJC (1)'].map((c, i) => (
            <button key={c} className="btn btn-sm" style={{ border: i === 0 ? '1px solid var(--ink)' : '1px solid var(--rule)', color: i === 0 ? 'var(--ink)' : 'var(--ink-2)', background: i === 0 ? 'var(--bg-sunk)' : 'transparent' }}>{c}</button>
          ))}
        </div>
      </section>

      <section style={{ padding: mobile ? '24px 16px 40px' : '40px 40px', display: 'grid', gridTemplateColumns: mobile ? '1fr 1fr' : 'repeat(4, 1fr)', gap: mobile ? 12 : 24, rowGap: mobile ? 28 : 48 }}>
        {all.map((p, i) => <ProductCard key={i} product={p} mobile={mobile}/>)}
      </section>

      <Footer/>
    </main>
  );
}

// ============ Brand / About Page ============
function PageBrand({ mobile }) {
  return (
    <main>
      <section style={{ padding: mobile ? '24px 16px 48px' : '48px 40px 80px', position: 'relative' }}>
        <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr', gap: mobile ? 32 : 64, alignItems: 'end', minHeight: mobile ? 'auto' : 560 }}>
          <div>
            <div className="eyebrow eyebrow-accent" style={{ marginBottom: 20 }}>— Dal 1998</div>
            <h1 className="font-display" style={{ fontSize: mobile ? 56 : 120, margin: 0, fontWeight: 400, letterSpacing: '-0.03em', lineHeight: 0.9 }}>
              Made in<br/><em>Italia.</em>
            </h1>
            <p style={{ marginTop: 28, fontSize: 17, lineHeight: 1.6, color: 'var(--ink-2)', maxWidth: 480 }}>
              Una casa importadora mexicana obsesionada con el equipo italiano de alta performance. Moto, ciclismo, y todo lo que se fabrica a mano en Italia.
            </p>
          </div>
          <PH ratio="4/5" tag="BRAND · 01" label="Fundadores · Milano · 1998"/>
        </div>
      </section>

      <section style={{ padding: mobile ? '0 16px' : '0 40px' }}>
        <div style={{ borderTop: '1px solid var(--rule)', borderBottom: '1px solid var(--rule)', padding: mobile ? '32px 0' : '56px 0', display: 'grid', gridTemplateColumns: mobile ? '1fr 1fr' : 'repeat(4, 1fr)', gap: 32 }}>
          {[['28','AÑOS'],['1,633','REFERENCIAS'],['12','MARCAS OFICIALES'],['48k+','PILOTOS']].map((s, i) => (
            <div key={i}>
              <div className="font-display" style={{ fontSize: mobile ? 48 : 72, lineHeight: 1, letterSpacing: '-0.02em' }}>{s[0]}</div>
              <div className="eyebrow" style={{ marginTop: 6 }}>{s[1]}</div>
            </div>
          ))}
        </div>
      </section>

      <section style={{ padding: mobile ? '48px 16px' : '96px 40px', display: 'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1.2fr', gap: mobile ? 32 : 80 }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 14 }}>— Manifiesto</div>
          <h2 className="font-display" style={{ fontSize: mobile ? 36 : 48, margin: 0, fontWeight: 400, letterSpacing: '-0.01em', lineHeight: 1.05 }}>
            Traer lo mejor de Italia, sin intermediarios.
          </h2>
        </div>
        <div style={{ fontSize: 15, lineHeight: 1.8, color: 'var(--ink-2)' }}>
          <p style={{ margin: 0 }}>
            Empezamos en 1998 con una sola tienda en Polanco y un solo objetivo: ofrecer a los pilotos mexicanos acceso directo al mismo equipo que usan los profesionales en Europa. Sin máscaras. Sin falsificaciones. Producto oficial con garantía y servicio técnico local.
          </p>
          <p>
            Hoy somos importador oficial de AGV, Dainese, Sidi, Rudy Project, Alpinestars y más. Nuestro showroom en CDMX alberga más de 1,600 productos con asesoría personalizada por especialistas que pilotean y pedalean cada semana.
          </p>
          <p>
            El nombre "Ciao Italia" es nuestro saludo diario a la casa que tanto admiramos. <em>Ogni giorno, ciao Italia.</em>
          </p>
        </div>
      </section>

      {/* Timeline */}
      <section style={{ padding: mobile ? '0 16px 48px' : '0 40px 96px' }}>
        <div className="eyebrow" style={{ marginBottom: 32 }}>— Nostra Storia</div>
        <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : 'repeat(4, 1fr)', gap: mobile ? 24 : 32 }}>
          {[
            ['1998', 'Fundación', 'Se abre la primera boutique en Polanco con 3 marcas italianas.'],
            ['2008', 'Ciclismo', 'Expansión a ciclismo de ruta y MTB con Sidi y Santini.'],
            ['2018', '20 años', 'Showroom flagship de 420 m² con simulador de conducción.'],
            ['2026', 'Online', 'Migración a Shopify con envío 24h en CDMX y 48h nacional.'],
          ].map((t, i) => (
            <div key={i} style={{ borderTop: '1px solid var(--rule)', paddingTop: 20 }}>
              <div className="font-mono" style={{ fontSize: 11, color: 'var(--it-red-ink)', letterSpacing: '0.1em', marginBottom: 10 }}>{t[0]}</div>
              <div className="font-display" style={{ fontSize: 26, fontStyle: 'italic', marginBottom: 10 }}>{t[1]}</div>
              <div style={{ fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.6 }}>{t[2]}</div>
            </div>
          ))}
        </div>
      </section>

      {/* Boutique */}
      <section style={{ padding: mobile ? '0 16px 48px' : '0 40px 96px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : '2fr 1fr', gap: 12 }}>
          <PH ratio={mobile ? '4/3' : '16/9'} tag="BOUTIQUE" label="Interior · Polanco · 420 m²"/>
          <div style={{ display: 'grid', gridTemplateRows: '1fr 1fr', gap: 12 }}>
            <PH ratio="1/1" tag="DETALLE" label="Wall of helmets"/>
            <PH ratio="1/1" tag="DETALLE" label="Fitting area"/>
          </div>
        </div>
      </section>

      <Footer/>
    </main>
  );
}

window.PageCart = PageCart;
window.PageCheckout = PageCheckout;
window.PageSearch = PageSearch;
window.PageBrand = PageBrand;
