/* Escala — Page components */

const { useState: useStateP, useEffect: useEffectP, useMemo: useMemoP } = React;

// ===================== HOME =====================
function HomePage({ navigate }) {
  const products = window.ESCALA_DATA.products;
  return (
    <main>
      {/* HERO with aurora */}
      <section className="hero">
        <div className="aurora"><div className="aurora-3"/><div className="aurora-4"/></div>
        <div className="container hero__inner">
          <p className="t-eyebrow" style={{ marginBottom: 32 }}>SS26 · Climbing essentials</p>
          <h1 className="t-display" style={{ fontSize: 'clamp(56px, 11vw, 168px)', margin: 0, marginBottom: 24 }}>
            Tu segunda<br/>muda de piel.
          </h1>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'end', gap: 32, flexWrap: 'wrap', marginTop: 48 }}>
            <p style={{ fontSize: 17, lineHeight: 1.5, maxWidth: 460, color: 'var(--ink-3)', margin: 0 }}>
              Cuatro cortes. Dos colores. Un bordado vertical
              que cambia de color según quién eres en la pared.
            </p>
            <div style={{ display: 'flex', gap: 12 }}>
              <button className="btn btn--lg" onClick={() => navigate('/shop')}>Comprar <Icon.Arrow/></button>
              <button className="btn btn--ghost btn--lg" onClick={() => navigate('/about')}>Sobre Escala</button>
            </div>
          </div>
        </div>
      </section>

      {/* Marquee */}
      <div className="marquee">
        <div className="marquee__track">
          <span>ENVÍO GRATIS &gt; 60€</span><span>·</span>
          <span>DEVOLUCIÓN 30 DÍAS</span><span>·</span>
          <span>HECHO EN PORTUGAL</span><span>·</span>
          <span>92% POLIÉSTER RECICLADO</span><span>·</span>
          <span>PAGO SEGURO STRIPE</span><span>·</span>
          <span>ENVÍO GRATIS &gt; 60€</span><span>·</span>
          <span>DEVOLUCIÓN 30 DÍAS</span><span>·</span>
          <span>HECHO EN PORTUGAL</span><span>·</span>
          <span>92% POLIÉSTER RECICLADO</span><span>·</span>
          <span>PAGO SEGURO STRIPE</span><span>·</span>
        </div>
      </div>

      {/* Editorial collage grid — clickable, lleva al PDP */}
      <section className="section--lg">
        <div className="container">
          <div className="section__head">
            <div>
              <p className="t-eyebrow" style={{ marginBottom: 12 }}>El catálogo</p>
              <h2>Cuatro camisetas.<br/>Cero ruido.</h2>
            </div>
            <button className="btn btn--ghost" onClick={() => navigate('/shop')}>Ver todo <Icon.Arrow/></button>
          </div>

          <div className="collage">
            {/* Tile 1 — large feature, T-01 */}
            <a className="tile tile--xl" onClick={() => navigate('/product/' + products[0].slug)}>
              <div className="tile__media">
                <img src="https://images.unsplash.com/photo-1522163182402-834f871fd851?w=1400&q=80" alt=""/>
              </div>
              <div className="tile__cap">
                <span className="t-mono">01 · {products[0].name}</span>
                <h3 className="t-display">{products[0].type.split('·')[1]?.trim() || products[0].type}</h3>
              </div>
            </a>

            {/* Tile 2 — tall, T-02 */}
            <a className="tile tile--tall" onClick={() => navigate('/product/' + products[1].slug)}>
              <div className="tile__media">
                <img src="https://images.unsplash.com/photo-1503342217505-b0a15ec3261c?w=1000&q=80" alt=""/>
              </div>
              <div className="tile__cap">
                <span className="t-mono">02 · {products[1].name}</span>
                <h3 className="t-display">{products[1].type.split('·')[1]?.trim() || products[1].type}</h3>
              </div>
            </a>

            {/* Tile 3 — wide, T-03 */}
            <a className="tile tile--wide" onClick={() => navigate('/product/' + products[2].slug)}>
              <div className="tile__media">
                <img src="https://images.unsplash.com/photo-1581655353564-df123a1eb820?w=1400&q=80" alt=""/>
              </div>
              <div className="tile__cap">
                <span className="t-mono">03 · {products[2].name}</span>
                <h3 className="t-display">{products[2].type.split('·')[1]?.trim() || products[2].type}</h3>
              </div>
            </a>

            {/* Tile 4 — square, T-04 */}
            <a className="tile tile--sq" onClick={() => navigate('/product/' + products[3].slug)}>
              <div className="tile__media">
                <img src="https://images.unsplash.com/photo-1618354691373-d851c5c3a990?w=1000&q=80" alt=""/>
              </div>
              <div className="tile__cap">
                <span className="t-mono">04 · {products[3].name}</span>
                <h3 className="t-display">{products[3].type.split('·')[1]?.trim() || products[3].type}</h3>
              </div>
            </a>
          </div>
        </div>

        <style>{`
          .collage {
            display: grid;
            grid-template-columns: repeat(6, 1fr);
            grid-auto-rows: 180px;
            gap: 16px;
          }
          .tile {
            position: relative; overflow: hidden;
            border-radius: var(--r-lg);
            background: var(--bg-muted);
            cursor: pointer;
            display: block;
          }
          .tile__media { position: absolute; inset: 0; }
          .tile__media img {
            width: 100%; height: 100%; object-fit: cover;
            transition: transform var(--t-slow) var(--ease);
          }
          .tile:hover .tile__media img { transform: scale(1.04); }
          .tile__cap {
            position: absolute; left: 20px; bottom: 18px; right: 20px;
            color: #fff; z-index: 2;
            text-shadow: 0 2px 12px rgba(0,0,0,0.35);
          }
          .tile__cap .t-mono { color: rgba(255,255,255,0.85); display: block; margin-bottom: 4px; }
          .tile__cap h3 { font-size: 22px; margin: 0; font-weight: 500; letter-spacing: -0.02em; }
          .tile::after {
            content: ""; position: absolute; inset: 0;
            background: linear-gradient(180deg, transparent 50%, rgba(0,0,0,0.45) 100%);
            z-index: 1;
          }
          .tile--xl   { grid-column: span 4; grid-row: span 3; }
          .tile--tall { grid-column: span 2; grid-row: span 3; }
          .tile--wide { grid-column: span 4; grid-row: span 2; }
          .tile--sq   { grid-column: span 2; grid-row: span 2; }
          @media (max-width: 860px) {
            .collage { grid-template-columns: repeat(2, 1fr); grid-auto-rows: 220px; }
            .tile--xl, .tile--tall, .tile--wide, .tile--sq { grid-column: span 2; grid-row: span 1; }
          }
        `}</style>
      </section>

      {/* Editorial split */}
      <section className="section--lg" style={{ background: 'var(--bg-soft)' }}>
        <div className="container" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 64, alignItems: 'center' }}>
          <div style={{ aspectRatio: '4/5', borderRadius: 'var(--r-lg)', overflow: 'hidden', background: 'var(--bg-muted)' }}>
            <img src="https://images.unsplash.com/photo-1522163182402-834f871fd851?w=900&q=80" alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
          </div>
          <div>
            <p className="t-eyebrow" style={{ marginBottom: 16 }}>Construcción</p>
            <h2 className="t-display" style={{ fontSize: 'clamp(32px, 5vw, 56px)', margin: 0, marginBottom: 20 }}>
              Pensada para moverse contigo.
            </h2>
            <p style={{ fontSize: 16, lineHeight: 1.6, color: 'var(--ink-3)', maxWidth: 480 }}>
              Tejido técnico de doble cara, costuras planas, secado rápido.
              Y un detalle: un bordado vertical en cuatro colores —
              tú eliges el que te define en la pared.
            </p>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 40 }}>
              {[
                ['128 g',  'Peso talla M'],
                ['92%',    'Material reciclado'],
                ['30 días','Devolución gratis'],
                ['Stripe', 'Pago protegido'],
              ].map(([k, v]) => (
                <div key={k} style={{ borderTop: '1px solid var(--line)', paddingTop: 14 }}>
                  <div className="t-display" style={{ fontSize: 28, letterSpacing: '-0.02em' }}>{k}</div>
                  <div className="t-mono" style={{ color: 'var(--ink-4)', marginTop: 6 }}>{v}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

// ===================== SHOP =====================
function ShopPage({ navigate, queryStr }) {
  const all = window.ESCALA_DATA.products;
  const params = new URLSearchParams(queryStr || '');
  const [color, setColor] = useStateP(params.get('color') || 'all');
  const [sort, setSort] = useStateP(params.get('sort') || 'featured');
  const [tag, setTag] = useStateP(params.get('tag') || 'all'); // all | new | best
  const [priceMax, setPriceMax] = useStateP(50);

  const items = useMemoP(() => {
    let r = all.slice();
    if (color !== 'all') r = r.filter(p => p.colors.includes(color));
    if (tag === 'new') r = r.filter(p => p.newIn);
    if (tag === 'best') r = r.filter(p => p.bestseller);
    r = r.filter(p => p.price <= priceMax);
    if (sort === 'price-asc') r.sort((a,b) => a.price - b.price);
    if (sort === 'price-desc') r.sort((a,b) => b.price - a.price);
    if (sort === 'new') r.sort((a,b) => Number(b.newIn) - Number(a.newIn));
    return r;
  }, [all, color, sort, tag, priceMax]);

  return (
    <main>
      <section style={{ padding: '64px 0 32px', borderBottom: '1px solid var(--line-soft)' }}>
        <div className="container">
          <p className="t-eyebrow" style={{ marginBottom: 12 }}>Catálogo · {items.length} productos</p>
          <h1 className="t-display" style={{ fontSize: 'clamp(40px, 7vw, 88px)', margin: 0 }}>Tienda</h1>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, marginTop: 32, flexWrap: 'wrap' }}>
            <div className="filters">
              <button className={'chip' + (tag === 'all' ? ' active' : '')} onClick={() => setTag('all')}>Todo</button>
              <button className={'chip' + (tag === 'new' ? ' active' : '')} onClick={() => setTag('new')}>Novedades</button>
              <button className={'chip' + (tag === 'best' ? ' active' : '')} onClick={() => setTag('best')}>Más vendidos</button>
              <span style={{ width: 1, height: 16, background: 'var(--line)', margin: '0 4px' }}/>
              <button className={'chip' + (color === 'all' ? ' active' : '')} onClick={() => setColor('all')}>Todos</button>
              <button className={'chip' + (color === 'white' ? ' active' : '')} onClick={() => setColor('white')}>
                <span className="swatch swatch--white" style={{ width: 10, height: 10 }}/> Blanco
              </button>
              <button className={'chip' + (color === 'black' ? ' active' : '')} onClick={() => setColor('black')}>
                <span className="swatch swatch--black" style={{ width: 10, height: 10 }}/> Negro
              </button>
            </div>
            <select className="input" style={{ width: 220, padding: '10px 14px' }} value={sort} onChange={e => setSort(e.target.value)}>
              <option value="featured">Destacados</option>
              <option value="new">Novedades</option>
              <option value="price-asc">Precio · menor</option>
              <option value="price-desc">Precio · mayor</option>
            </select>
          </div>
        </div>
      </section>

      <section className="section">
        <div className="container">
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 40 }}>
            {items.map(p => (
              <ProductCard key={p.id} product={p} onClick={() => navigate('/product/' + p.slug)}/>
            ))}
          </div>
          {items.length === 0 && (
            <p style={{ textAlign: 'center', color: 'var(--ink-4)', padding: '80px 0' }}>Sin resultados con esos filtros.</p>
          )}
        </div>
      </section>
    </main>
  );
}

// ===================== PRODUCT DETAIL =====================
function ProductPage({ navigate, slug, openCart }) {
  const product = window.ESCALA_DATA.products.find(p => p.slug === slug);
  const [color, setColor] = useStateP('white');
  const [line, setLine] = useStateP(product?.embroideryColors[0]?.id);
  const [size, setSize] = useStateP('M');
  const [imgIdx, setImgIdx] = useStateP(0);
  const [added, setAdded] = useStateP(false);

  if (!product) return <main className="container" style={{ padding: '120px 0' }}><p>Producto no encontrado.</p></main>;

  const lineObj = product.embroideryColors.find(l => l.id === line);

  const onAdd = () => {
    window.ESCALA_CART.add({
      productId: product.id,
      productName: product.name,
      color, line, lineLabel: lineObj.name, size,
      qty: 1, price: product.price,
      image: product.images[0],
    });
    setAdded(true);
    setTimeout(() => { setAdded(false); openCart(); }, 600);
  };

  return (
    <main style={{ paddingTop: 32 }}>
      <div className="container">
        <button onClick={() => navigate('/shop')} className="btn btn--ghost btn--sm" style={{ marginBottom: 24 }}>
          <Icon.ArrowLeft/> Catálogo
        </button>
        <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 64 }} className="pdp-grid">
          {/* Gallery */}
          <div>
            <div style={{ aspectRatio: '4/5', background: color === 'black' ? '#0a0a0a' : 'var(--bg-muted)', borderRadius: 'var(--r-lg)', position: 'relative', overflow: 'hidden' }}>
              {product.images[imgIdx]
                ? <img src={product.images[imgIdx]} alt={product.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
                : <div className="skeleton-img">{product.name} · {color}</div>}
            </div>
            <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
              {product.images.map((src, i) => (
                <button key={i} onClick={() => setImgIdx(i)}
                  style={{ flex: '0 0 80px', aspectRatio: '4/5', padding: 0, border: i === imgIdx ? '1px solid var(--ink)' : '1px solid var(--line)', borderRadius: 6, background: 'var(--bg-muted)', overflow: 'hidden', cursor: 'pointer' }}>
                  <img src={src} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
                </button>
              ))}
            </div>
          </div>

          {/* Info */}
          <div style={{ position: 'sticky', top: 90, alignSelf: 'flex-start' }}>
            <p className="t-eyebrow" style={{ marginBottom: 8 }}>{product.type}</p>
            <h1 className="t-display" style={{ fontSize: 48, margin: 0, marginBottom: 12 }}>{product.name}</h1>
            <p style={{ fontSize: 20, fontWeight: 500, margin: 0, marginBottom: 24 }}>{window.ESCALA_FORMAT(product.price)}</p>
            <p style={{ fontSize: 14, color: 'var(--ink-3)', lineHeight: 1.6, marginBottom: 32 }}>{product.description}</p>

            {/* Color */}
            <div style={{ marginBottom: 24 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10 }}>
                <span className="t-mono" style={{ color: 'var(--ink-3)' }}>Color</span>
                <span style={{ fontSize: 12, color: 'var(--ink-4)' }}>{color === 'white' ? 'Blanco' : 'Negro'}</span>
              </div>
              <div style={{ display: 'flex', gap: 8 }}>
                {product.colors.map(c => (
                  <button key={c} onClick={() => setColor(c)}
                    style={{
                      width: 40, height: 40, borderRadius: '50%',
                      background: c === 'white' ? '#ffffff' : '#0a0a0a',
                      border: color === c ? '2px solid var(--ink)' : '1px solid var(--line)',
                      outline: color === c ? '2px solid var(--bg)' : 'none',
                      outlineOffset: -4,
                      cursor: 'pointer',
                    }}/>
                ))}
              </div>
            </div>

            {/* Color del bordado */}
            <div style={{ marginBottom: 24 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10 }}>
                <span className="t-mono" style={{ color: 'var(--ink-3)' }}>Color del bordado</span>
                <span style={{ fontSize: 12, color: 'var(--ink-4)' }}>{lineObj?.name}</span>
              </div>
              <div style={{ display: 'flex', gap: 8 }}>
                {product.embroideryColors.map(l => (
                  <button key={l.id} onClick={() => setLine(l.id)} title={l.name}
                    style={{
                      width: 40, height: 40, borderRadius: '50%',
                      background: l.hex,
                      border: line === l.id ? '2px solid var(--ink)' : '1px solid var(--line)',
                      cursor: 'pointer',
                    }}/>
                ))}
              </div>
            </div>

            {/* Talla */}
            <div style={{ marginBottom: 32 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10 }}>
                <span className="t-mono" style={{ color: 'var(--ink-3)' }}>Talla</span>
                <a href="#" onClick={e => { e.preventDefault(); alert('Guía de tallas próximamente'); }} style={{ fontSize: 12, color: 'var(--ink-3)', textDecoration: 'underline' }}>Guía de tallas</a>
              </div>
              <div style={{ display: 'flex', gap: 8 }}>
                {product.sizes.map(s => (
                  <button key={s} onClick={() => setSize(s)}
                    style={{
                      flex: 1, padding: '14px 0',
                      border: size === s ? '1px solid var(--ink)' : '1px solid var(--line)',
                      background: size === s ? 'var(--ink)' : 'var(--bg)',
                      color: size === s ? 'var(--bg)' : 'var(--ink)',
                      borderRadius: 'var(--r-md)',
                      fontSize: 13, fontWeight: 500,
                      cursor: 'pointer',
                    }}>{s}</button>
                ))}
              </div>
            </div>

            <button className="btn btn--full btn--lg" onClick={onAdd}>
              {added ? <><Icon.Check/> Añadido</> : <>Añadir a la bolsa · {window.ESCALA_FORMAT(product.price)}</>}
            </button>

            <div style={{ marginTop: 16, fontSize: 12, color: 'var(--ink-4)', display: 'flex', gap: 16, alignItems: 'center', justifyContent: 'center' }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><Icon.Truck/> Envío gratis &gt; 60€</span>
              <span>·</span>
              <span>Devolución 30 días</span>
            </div>

            {/* Specs */}
            <div style={{ marginTop: 48, borderTop: '1px solid var(--line-soft)' }}>
              {Object.entries(product.specs).map(([k, v]) => (
                <div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '14px 0', borderBottom: '1px solid var(--line-soft)', fontSize: 13 }}>
                  <span style={{ color: 'var(--ink-4)' }}>{k}</span>
                  <span>{v}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      <style>{`
        @media (max-width: 860px) {
          .pdp-grid { grid-template-columns: 1fr !important; gap: 32px !important; }
        }
      `}</style>
    </main>
  );
}

Object.assign(window, { HomePage, ShopPage, ProductPage });
