// pages-catalog.jsx — Hats, Hebillas, Correas, Product detail
const { useState, useEffect, useMemo } = React;

// ── Hats Page ────────────────────────────────────────────────────────────────
function HatsPage({ lang, navigate, initialFilter }) {
  const t = I18N[lang];
  const [filter, setFilter] = useState(initialFilter || 'all');
  const [sort, setSort] = useState(0);

  const filtered = useMemo(() => {
    let list = filter === 'all' ? HAT_PRODUCTS : HAT_PRODUCTS.filter(p => p.style === filter);
    if (sort === 1) list = [...list].reverse();
    if (sort === 2) list = [...list].sort((a, b) => a.id - b.id);
    return list;
  }, [filter, sort]);

  const styleList = Object.values(HAT_STYLES);

  return (
    <div className="page-enter">
      {/* Title band */}
      <section style={{ padding: '100px 0 40px', background: 'var(--parchment)' }}>
        <div className="container">
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: 20 }}>
            <Ornament />
            <div className="eyebrow">{t.catalog.count(filtered.length)}</div>
            <h1 style={{ fontSize: 'clamp(56px, 7vw, 96px)', fontStyle: 'italic', fontWeight: 400, lineHeight: 1 }}>
              {t.catalog.hatsTitle}
            </h1>
            <p style={{ color: 'var(--muted)', maxWidth: '56ch', fontSize: 18 }}>{t.catalog.hatsSub}</p>
          </div>
        </div>
      </section>

      {/* Style cards — quick nav */}
      {filter === 'all' && (
        <section className="cat-cards-section" style={{ background: 'var(--bone)', paddingBottom: 20 }}>
          <div className="category-cards-inline" style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 6 }}>
            {styleList.map((s, i) => (
              <button
                key={s.id}
                onClick={() => setFilter(s.id)}
                style={{
                  padding: 0,
                  border: 'none',
                  background: 'transparent', display: 'block',
                  overflow: 'hidden', position: 'relative',
                  cursor: 'pointer',
                }}
                onMouseEnter={e => {
                  e.currentTarget.querySelector('.sng-img').style.transform = 'scale(1.04)';
                  e.currentTarget.querySelector('.sng-overlay').style.background = 'linear-gradient(180deg, rgba(27,18,10,0.15) 0%, rgba(27,18,10,0.80) 100%)';
                }}
                onMouseLeave={e => {
                  e.currentTarget.querySelector('.sng-img').style.transform = 'scale(1)';
                  e.currentTarget.querySelector('.sng-overlay').style.background = 'linear-gradient(180deg, rgba(27,18,10,0.05) 0%, rgba(27,18,10,0.70) 100%)';
                }}
              >
                <div className="sng-img" style={{ transition: 'transform 400ms var(--ease)', background: 'var(--bone)' }}>
                  {s.hero ? (
                    <img
                      src={s.hero}
                      alt={s.name[lang]}
                      loading="lazy"
                      style={{
                        width: '100%',
                        aspectRatio: '1 / 1',
                        objectFit: 'contain',
                        objectPosition: 'center',
                        display: 'block',
                        padding: '12px',
                      }}
                    />
                  ) : (
                    <Placeholder label={s.name[lang]} ratio="1/1" />
                  )}
                </div>
                <div className="sng-overlay" style={{
                  position: 'absolute', inset: 0,
                  background: 'linear-gradient(180deg, rgba(27,18,10,0.05) 0%, rgba(27,18,10,0.70) 100%)',
                  display: 'flex', flexDirection: 'column', justifyContent: 'flex-end',
                  padding: '16px 14px',
                  transition: 'background 300ms var(--ease)',
                  pointerEvents: 'none',
                }}>
                  <div style={{
                    position: 'absolute', top: 8, left: 8, padding: '2px 6px',
                    background: 'rgba(42,22,10,0.65)', backdropFilter: 'blur(4px)',
                    fontFamily: 'var(--font-mono)', fontSize: 8, letterSpacing: '0.2em',
                    color: 'var(--gold-300)', textTransform: 'uppercase',
                  }}>{s.code}</div>
                  <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--gold-300)', letterSpacing: '0.2em', textTransform: 'uppercase', marginBottom: 4 }}>
                    {s.count}+ modelos
                  </div>
                  <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 'clamp(16px, 1.4vw, 24px)', color: 'var(--cream)', lineHeight: 1.1 }}>
                    {s.name[lang]}
                  </div>
                </div>
              </button>
            ))}
            {/* Decorative fill — only visible on mobile where 3-col grid leaves 1 empty cell */}
            <div className="catalog-decorative-fill">
              <div style={{ position: 'absolute', inset: 10, border: '1px solid rgba(212,169,74,0.25)', pointerEvents: 'none' }} />
              <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(ellipse at center, rgba(212,169,74,0.08) 0%, transparent 70%)' }} />
              <img src="/uploads/SS SensStyle.gif" alt="SensStyle" style={{ height: 60, opacity: 0.85, position: 'relative', zIndex: 1 }} onError={e => e.target.style.display='none'} />
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 7.5, letterSpacing: '0.22em', color: 'var(--gold-500)', textTransform: 'uppercase', textAlign: 'center', lineHeight: 2, position: 'relative', zIndex: 1 }}>
                {lang === 'fr' ? 'Artisanat' : lang === 'en' ? 'Craftsmanship' : 'Artesanía'}<br/>
                · {lang === 'en' ? 'Leather' : lang === 'fr' ? 'Cuir' : 'Cuero'} ·<br/>
                Canada
              </div>
            </div>
          </div>
        </section>
      )}

      {/* Filter bar */}
      <section className="filter-bar-section" style={{
        padding: '0', background: 'var(--parchment)', position: 'sticky', top: 'calc(var(--top-bar-h) - 7px)', zIndex: 20,
        borderBottom: '1px solid rgba(27,18,10,0.1)',
      }}>
        <div style={{ display: 'flex', alignItems: 'stretch' }}>
          {/* Scrollable filter buttons */}
          <div className="filter-bar-container" style={{ display: 'flex', flex: 1, overflowX: 'auto' }}>
            <button
              onClick={() => setFilter('all')}
              className={`style-filter-btn ${filter === 'all' ? 'active' : ''}`}
            >
              {t.catalog.all}
              <span style={{ fontSize: 9, marginLeft: 5, opacity: 0.6 }}>({HAT_PRODUCTS.length})</span>
            </button>
            {styleList.map(s => {
              const n = HAT_PRODUCTS.filter(p => p.style === s.id).length;
              return (
                <button
                  key={s.id}
                  onClick={() => setFilter(s.id)}
                  className={`style-filter-btn ${filter === s.id ? 'active' : ''}`}
                >
                  {s.name[lang]}
                  <span style={{ fontSize: 9, marginLeft: 5, opacity: 0.6 }}>({n})</span>
                </button>
              );
            })}
          </div>
          {/* Sort — always visible on right */}
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10, padding: '0 16px',
            borderLeft: '1px solid rgba(27,18,10,0.1)', flexShrink: 0,
            background: 'var(--parchment)',
          }}>
            <span className="eyebrow muted" style={{ fontSize: 9 }}>{t.catalog.sort}</span>
            <select
              value={sort}
              onChange={(e) => setSort(Number(e.target.value))}
              style={{ background: 'transparent', border: 0, fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--ink)', outline: 'none', cursor: 'pointer' }}
            >
              {t.catalog.sortOptions.map((opt, i) => <option key={i} value={i}>{opt}</option>)}
            </select>
          </div>
        </div>
      </section>

      {/* Style hero when filtered */}
      {filter !== 'all' && (() => {
        const s = HAT_STYLES[filter];
        return (
          <section className="category-style-section" style={{ background: 'var(--ink)', color: 'var(--cream)', padding: 'clamp(40px,5vw,64px) 0' }}>
            <div className="container category-filtered-hero" style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 'clamp(32px,4vw,56px)', alignItems: 'center' }}>
              <div>
                <div className="cat-hero-ornament" style={{ color: 'var(--gold-300)', marginBottom: 18 }}><Ornament color="var(--gold-300)" /></div>
                <div className="eyebrow light" style={{ marginBottom: 12 }}>{s.code} · {lang === 'es' ? 'Estilo' : 'Style'}</div>
                <h2 style={{
                  fontSize: 'clamp(36px,4vw,56px)', fontStyle: 'italic', fontWeight: 400,
                  color: 'var(--cream)', lineHeight: 1.05, marginBottom: 18,
                }}>
                  {s.name[lang]}
                </h2>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--gold-300)', letterSpacing: '0.22em', textTransform: 'uppercase' }}>
                  {s.count}+ {lang === 'es' ? 'MODELOS DISPONIBLES' : lang === 'fr' ? 'MODÈLES DISPONIBLES' : 'MODELS AVAILABLE'}
                </div>
              </div>
              <div>
                <p style={{ fontSize: 'clamp(16px,1.4vw,19px)', color: 'rgba(245,237,224,0.75)', lineHeight: 1.6 }}>
                  {s.desc[lang]}
                </p>
              </div>
            </div>
          </section>
        );
      })()}

      {/* Product grid */}
      <section style={{ background: 'var(--parchment)', padding: '60px 0 120px' }}>
        <div className="container">
          <div className="featured-grid" style={{ gap: 32 }}>
            {filtered.map(p => (
              <HatCard key={p.id} product={p} lang={lang} navigate={navigate} />
            ))}
          </div>
        </div>
      </section>
    </div>
  );
}

// ── Hat Card ─────────────────────────────────────────────────────────────────
function HatCard({ product, lang, navigate, compact = false }) {
  const t = I18N[lang];
  const s = HAT_STYLES[product.style];
  const [hover, setHover] = useState(false);
  const displayName = lang === 'en' ? product.nameEn : lang === 'fr' ? product.nameFr : product.name;

  return (
    <button
      onClick={() => navigate({ page: 'product', id: product.slug })}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{ textAlign: 'left', background: 'transparent', width: '100%', display: 'flex', flexDirection: 'column', gap: 14 }}
    >
      <div style={{ position: 'relative', overflow: 'hidden' }}>
        <Placeholder label={displayName} ratio="1/1" src={product.hero} corner={product.sku} blend />
        <div style={{
          position: 'absolute', top: 10, right: 10,
          padding: '3px 8px', background: 'var(--ink)', color: 'var(--gold-300)',
          fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.22em', textTransform: 'uppercase',
        }}>{t.catalog.wholesale}</div>
        <div style={{
          position: 'absolute', left: 0, right: 0, bottom: 0, padding: '16px 18px',
          background: 'linear-gradient(transparent, rgba(27,18,10,0.75))',
          color: 'var(--cream)', fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase',
          transform: hover ? 'translateY(0)' : 'translateY(4px)',
          opacity: hover ? 1 : 0, transition: 'all 240ms var(--ease)',
        }}>{t.catalog.view} →</div>
      </div>
      <div>
        <div className="eyebrow muted" style={{ marginBottom: 6 }}>
          {s ? s.name[lang] : ''} · {product.sku}
        </div>
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: compact ? 20 : 24, fontWeight: 500, letterSpacing: '-0.005em' }}>
          {displayName}
        </h3>
        {!compact && (
          <div style={{ display: 'flex', gap: 6, marginTop: 10 }}>
            {product.finishes.slice(0, 4).map((f, i) => (
              <span key={i} style={{ width: 12, height: 12, background: f, border: '1px solid rgba(27,18,10,0.2)' }} />
            ))}
          </div>
        )}
      </div>
    </button>
  );
}

// ── Hebillas Page ─────────────────────────────────────────────────────────────
function HebillasPage({ lang }) {
  const t = I18N[lang];
  const [lb, setLb] = useState(null);
  const [showInquire, setShowInquire] = useState(null);

  return (
    <div className="page-enter">
      {/* Title */}
      <section style={{ padding: '100px 0 40px', background: 'var(--parchment)' }}>
        <div className="container">
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: 20 }}>
            <Ornament />
            <div className="eyebrow">{t.catalog.buckleCount(BUCKLE_IMAGES.length)}</div>
            <h1 style={{ fontSize: 'clamp(56px, 7vw, 96px)', fontStyle: 'italic', fontWeight: 400, lineHeight: 1 }}>
              {t.catalog.hebillasTitle}
            </h1>
            <p style={{ color: 'var(--muted)', maxWidth: '56ch', fontSize: 18 }}>{t.catalog.hebillasSub}</p>
          </div>
        </div>
      </section>

      {/* Buckle grid */}
      <section style={{ background: 'var(--parchment)', padding: '40px 0 120px' }}>
        <div className="container">
          <div className="featured-grid" style={{ gap: 16 }}>
            {BUCKLE_IMAGES.map((b, i) => (
              <div key={b.num} style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                <button
                  onClick={() => setLb(i)}
                  style={{
                    padding: 0, background: 'transparent', cursor: 'zoom-in',
                    position: 'relative', overflow: 'hidden',
                  }}
                  onMouseEnter={e => e.currentTarget.querySelector('.bk-overlay').style.opacity = '1'}
                  onMouseLeave={e => e.currentTarget.querySelector('.bk-overlay').style.opacity = '0'}
                >
                  <Placeholder label={`Hebilla No.${b.num}`} ratio="1/1" src={b.src} contain={true} />
                  <div className="bk-overlay" style={{
                    position: 'absolute', inset: 0,
                    background: 'rgba(27,18,10,0.4)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    opacity: 0, transition: 'opacity 220ms var(--ease)',
                  }}>
                    <span style={{ color: 'var(--cream)', fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase' }}>
                      Ver →
                    </span>
                  </div>
                  <div style={{
                    position: 'absolute', top: 8, left: 8, padding: '2px 6px',
                    background: 'rgba(27,18,10,0.6)', backdropFilter: 'blur(4px)',
                    fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.18em', color: 'var(--gold-300)', textTransform: 'uppercase',
                  }}>{b.sku}</div>
                </button>
                <button
                  className="btn"
                  style={{ padding: '8px 12px', fontSize: 11, letterSpacing: '0.15em' }}
                  onClick={() => setShowInquire(b)}
                >
                  {t.catalog.inquireBuckle}
                </button>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Lightbox */}
      {lb !== null && (
        <Lightbox
          images={BUCKLE_IMAGES.map(b => b.src)}
          index={lb}
          onClose={() => setLb(null)}
          onNav={d => setLb((lb + d + BUCKLE_IMAGES.length) % BUCKLE_IMAGES.length)}
        />
      )}

      {/* Inquire modal */}
      {showInquire && (
        <BuckleInquireModal lang={lang} buckle={showInquire} onClose={() => setShowInquire(null)} />
      )}
    </div>
  );
}

function BuckleInquireModal({ lang, buckle, onClose }) {
  const t = I18N[lang];
  const [sent, setSent] = useState(false);
  const [sending, setSending] = useState(false);
  const [form, setForm] = useState({ name: '', company: '', email: '', message: '' });
  const [captchaToken, setCaptchaToken] = useState('');
  const [error, setError] = useState('');

  const submit = async (e) => {
    e.preventDefault();
    setSending(true);
    setError('');
    try {
      const res = await fetch(API_BASE + '/api/public/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          subject: `Cotización Hebilla ${buckle.sku}`,
          message: `Empresa: ${form.company}\n${form.message}`,
          captchaToken,
        }),
      });
      const data = await res.json();
      if (data.ok) { setSent(true); }
      else { setError(data.error || 'Error al enviar'); }
    } catch { setError('Error de conexión'); }
    finally { setSending(false); }
  };

  return (
    <div className="lightbox" onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{ background: 'var(--parchment)', width: 'min(580px, 92vw)', padding: 48, position: 'relative' }}>
        <button onClick={onClose} style={{ position: 'absolute', top: 16, right: 16, fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--muted)' }}>✕</button>
        {!sent ? (
          <>
            <Ornament />
            <div className="eyebrow" style={{ margin: '16px 0 8px' }}>{t.catalog.hebillasTitle}</div>
            <h3 style={{ fontSize: 32, fontStyle: 'italic', fontWeight: 400, marginBottom: 6 }}>Hebilla {buckle.sku}</h3>
            <p style={{ color: 'var(--muted)', marginBottom: 28, fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.15em' }}>{t.catalog.moq}</p>
            <form onSubmit={submit}>
              <CaptchaField onCaptcha={setCaptchaToken} />
              <div className="form-grid">
                <div className="form-field"><label>{t.contact.form.name}</label><input required value={form.name} onChange={e => setForm({...form, name: e.target.value})} /></div>
                <div className="form-field"><label>{t.contact.form.company}</label><input value={form.company} onChange={e => setForm({...form, company: e.target.value})} /></div>
                <div className="form-field full"><label>{t.contact.form.email}</label><input type="email" required value={form.email} onChange={e => setForm({...form, email: e.target.value})} /></div>
                <div className="form-field full"><label>{t.contact.form.message}</label><textarea rows={3} value={form.message} onChange={e => setForm({...form, message: e.target.value})} /></div>
              </div>
              {error && <p style={{ color: 'var(--err)', fontFamily: 'var(--font-mono)', fontSize: 12, marginTop: 8, letterSpacing: '0.1em' }}>{error}</p>}
              <div style={{ marginTop: 24 }}>
                <button type="submit" className="btn btn-primary" disabled={sending}>{sending ? 'Enviando...' : `${t.contact.form.send}`} <span className="arrow"/></button>
              </div>
            </form>
          </>
        ) : (
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            <Ornament />
            <p style={{ fontSize: 20, color: 'var(--charcoal)', marginTop: 20 }}>{t.contact.form.sent}</p>
          </div>
        )}
      </div>
    </div>
  );
}

// ── Correas / Belts Page ──────────────────────────────────────────────────────
// COLECCIÓN NO DISPONIBLE PÚBLICAMENTE — para habilitar: cambiar BELTS_ENABLED a true
const BELTS_ENABLED = false;

function CoreasPage({ lang, navigate }) {
  const t = I18N[lang];

  /* ── LOCKED VIEW ── */
  if (!BELTS_ENABLED) {
    return (
      <div className="page-enter" style={{ minHeight: '100vh', background: 'var(--ink)', display: 'flex', flexDirection: 'column' }}>

        {/* Hero */}
        <section style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 'clamp(80px,10vw,140px) 0' }}>
          <div className="container" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: 28 }}>

            {/* Gold border frame */}
            <div style={{ border: '1px solid rgba(212,169,74,0.25)', padding: 'clamp(40px,6vw,72px) clamp(32px,6vw,80px)', maxWidth: 640, width: '100%', position: 'relative' }}>
              {/* Corner marks */}
              {['topLeft','topRight','bottomLeft','bottomRight'].map(pos => (
                <span key={pos} style={{
                  position: 'absolute', width: 14, height: 14,
                  borderColor: 'var(--gold-500)', borderStyle: 'solid', borderWidth: 0,
                  ...(pos === 'topLeft'     ? { top: -1, left: -1, borderTopWidth: 2, borderLeftWidth: 2 } : {}),
                  ...(pos === 'topRight'    ? { top: -1, right: -1, borderTopWidth: 2, borderRightWidth: 2 } : {}),
                  ...(pos === 'bottomLeft'  ? { bottom: -1, left: -1, borderBottomWidth: 2, borderLeftWidth: 2 } : {}),
                  ...(pos === 'bottomRight' ? { bottom: -1, right: -1, borderBottomWidth: 2, borderRightWidth: 2 } : {}),
                }} />
              ))}

              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 24 }}>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.3em', color: 'var(--gold-500)', textTransform: 'uppercase' }}>
                  {lang === 'en' ? 'Coming Soon' : lang === 'fr' ? 'Bientôt disponible' : 'Próximamente'}
                </div>

                <Ornament color="var(--gold-300)" />

                <h1 style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontWeight: 400, fontSize: 'clamp(48px,7vw,80px)', lineHeight: 1, color: 'var(--cream)', margin: 0 }}>
                  {t.catalog.correasTitle}
                </h1>

                <div style={{ width: 48, height: 1, background: 'var(--gold-700)' }} />

                <p style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--gold-400, var(--gold-300))', lineHeight: 2 }}>
                  {lang === 'en'
                    ? 'Exclusive access · Wholesale clients only'
                    : lang === 'fr'
                    ? 'Accès exclusif · Réservé aux grossistes'
                    : 'Acceso exclusivo · Solo clientes mayoristas'}
                </p>

                <p style={{ fontSize: 17, color: 'rgba(245,237,224,0.5)', maxWidth: '40ch', lineHeight: 1.65, margin: 0 }}>
                  {lang === 'en'
                    ? 'This collection is reserved for authorized wholesale distributors. Contact us to learn about access.'
                    : lang === 'fr'
                    ? 'Cette collection est réservée aux distributeurs grossistes autorisés. Contactez-nous pour obtenir un accès.'
                    : 'Esta colección está reservada para distribuidores mayoristas autorizados. Contáctanos para conocer el acceso.'}
                </p>

                <button
                  className="btn btn-gold"
                  style={{ marginTop: 8, fontSize: 11 }}
                  onClick={() => navigate({ page: 'contact' })}
                >
                  {lang === 'en' ? 'Contact us →' : lang === 'fr' ? 'Nous contacter →' : 'Contáctanos →'}
                </button>
              </div>
            </div>

          </div>
        </section>

      </div>
    );
  }

  /* ── ENABLED VIEW (restore when BELTS_ENABLED = true) ── */
  return (
    <div className="page-enter">
      {/* Title */}
      <section style={{ padding: '100px 0 40px', background: 'var(--parchment)' }}>
        <div className="container">
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: 20 }}>
            <Ornament />
            <div className="eyebrow">{t.catalog.count(BELT_PRODUCTS.length)}</div>
            <h1 style={{ fontSize: 'clamp(56px, 7vw, 96px)', fontStyle: 'italic', fontWeight: 400, lineHeight: 1 }}>
              {t.catalog.correasTitle}
            </h1>
            <p style={{ color: 'var(--muted)', maxWidth: '56ch', fontSize: 18 }}>{t.catalog.correasSub}</p>
          </div>
        </div>
      </section>
      {/* Belt grid */}
      <section style={{ background: 'var(--parchment)', padding: '40px 0 120px' }}>
        <div className="container">
          <div className="journal-grid" style={{ gap: 40 }}>
            {BELT_PRODUCTS.map(p => (
              <BeltCard key={p.id} product={p} lang={lang} navigate={navigate} />
            ))}
          </div>
        </div>
      </section>
    </div>
  );
}

function BeltCard({ product, lang, navigate }) {
  const t = I18N[lang];
  const [hover, setHover] = useState(false);
  const [showQuote, setShowQuote] = useState(false);
  const displayName = lang === 'en' ? product.nameEn : lang === 'fr' ? product.nameFr : product.name;

  return (
    <div
      style={{ display: 'flex', flexDirection: 'column', gap: 20 }}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
    >
      <div style={{ position: 'relative', overflow: 'hidden' }}>
        <Placeholder label={displayName} ratio="4/3" tone="gold" corner={product.sku} />
        <div style={{
          position: 'absolute', top: 10, right: 10, padding: '3px 8px',
          background: 'var(--ink)', color: 'var(--gold-300)',
          fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.22em', textTransform: 'uppercase',
        }}>{t.catalog.wholesale}</div>
      </div>
      <div>
        <div className="eyebrow muted" style={{ marginBottom: 8 }}>{t.catalog.correasTitle} · {product.sku}</div>
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 500, letterSpacing: '-0.005em', marginBottom: 12 }}>
          {displayName}
        </h3>
        <p style={{ fontSize: 17, color: 'var(--charcoal)', lineHeight: 1.55, marginBottom: 18 }}>
          {product.desc[lang]}
        </p>
        <div style={{ display: 'flex', gap: 8, marginBottom: 20 }}>
          {product.finishes.map((f, i) => (
            <span key={i} style={{ width: 16, height: 16, background: f, border: '1px solid rgba(27,18,10,0.25)' }} />
          ))}
        </div>
        <dl style={{ margin: '0 0 22px', borderTop: '1px solid rgba(27,18,10,0.12)' }}>
          {Object.entries(product.specs).filter(([k]) => k !== 'crown').map(([k, v]) => (
            <div key={k} style={{ display: 'grid', gridTemplateColumns: '100px 1fr', gap: 12, padding: '10px 0', borderBottom: '1px solid rgba(27,18,10,0.1)' }}>
              <dt style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--muted)' }}>
                {I18N[lang].product.specsData[k] || k}
              </dt>
              <dd style={{ margin: 0, fontSize: 15, color: 'var(--ink)' }}>{v}</dd>
            </div>
          ))}
        </dl>
        <button className="btn btn-primary" onClick={() => setShowQuote(true)}>
          {t.product.inquire} <span className="arrow"/>
        </button>
      </div>
      {showQuote && <QuoteModal lang={lang} product={product} onClose={() => setShowQuote(false)} />}
    </div>
  );
}

// ── Product Detail Page ───────────────────────────────────────────────────────
function ProductDetailPage({ lang, navigate, id }) {
  const t = I18N[lang];
  const product = PRODUCTS.find(p => p.slug === id) || HAT_PRODUCTS[0];
  const s = HAT_STYLES[product.style] || null;
  const displayName = lang === 'en' ? product.nameEn : lang === 'fr' ? product.nameFr : product.name;

  const rawGallery = product.gallery && product.gallery.length > 0 ? product.gallery : [];
  const heroFallback = product.hero && !rawGallery.includes(product.hero) ? [product.hero] : [];
  const galleryImgs = rawGallery.length > 0 ? rawGallery : heroFallback.length > 0 ? heroFallback : [null, null, null, null];
  
  const [activeImg, setActiveImg] = useState(0);
  const [finish, setFinish] = useState(0);
  const [lb, setLb] = useState(null);
  const [showQuote, setShowQuote] = useState(false);
  let modelLifestyle = (new Set([1,2,3,4,5,6,7,8,9,10,45,50,51,52,53,54,55,56,57,97,98,99,100,101,102,103,104,149,151,152,153,154,155,156])).has(product.id) ? [
    `products/lifestyle/${String(product.id).padStart(3,'0')}-${product.style}/model.webp`,
    `products/lifestyle/${String(product.id).padStart(3,'0')}-${product.style}/product.webp`,
    `products/lifestyle/${String(product.id).padStart(3,'0')}-${product.style}/lifestyle.webp`
  ] : [];

  return (
    <div className="page-enter" style={{ background: 'var(--parchment)' }}>
      {/* Breadcrumb */}
      <div className="container product-breadcrumb" style={{ paddingTop: 24, paddingBottom: 10, fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--muted)' }}>
        <a onClick={() => navigate({ page: 'sombreros' })} style={{ cursor: 'pointer' }}>{t.catalog.hatsTitle}</a>
        {s && (
          <>
            <span style={{ margin: '0 10px', opacity: 0.5 }}>/</span>
            <a onClick={() => navigate({ page: 'sombreros', filter: s.id })} style={{ cursor: 'pointer' }}>{s.name[lang]}</a>
          </>
        )}
        <span style={{ margin: '0 10px', opacity: 0.5 }}>/</span>
        <span style={{ color: 'var(--ink)' }}>{displayName}</span>
      </div>

      {/* Gallery + Info */}
      <section className="product-detail-section" style={{ padding: 'clamp(32px,4vw,64px) 0' }}>
        <div className="container product-detail-grid-inline" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'clamp(32px,5vw,64px)', alignItems: 'center' }}>
          {/* Gallery column */}
          <div className="product-gallery-col" style={{ position: 'relative' }}>
            {/* Imagen principal */}
            <div
              onClick={() => galleryImgs[activeImg] && setLb({ images: galleryImgs, index: activeImg })}
              style={{
                background: 'var(--saddle-900)',
                cursor: galleryImgs[activeImg] ? 'zoom-in' : 'default',
                position: 'relative',
                aspectRatio: '1 / 1',
                overflow: 'hidden',
              }}
            >
              {galleryImgs[activeImg] ? (
                <img
                  src={galleryImgs[activeImg]}
                  alt={displayName}
                  style={{ width: '100%', height: '100%', objectFit: 'contain', objectPosition: 'center', display: 'block', padding: 'clamp(16px,3vw,32px)' }}
                />
              ) : (
                <Placeholder
                  label={`${displayName} · ${String(activeImg + 1).padStart(2,'0')}`}
                  ratio="1/1" tone="default"
                  corner={`${String(activeImg + 1).padStart(2,'0')} / ${String(galleryImgs.length).padStart(2,'0')}`}
                />
              )}
              {/* Counter badge */}
              <div style={{
                position: 'absolute', top: 12, right: 12, padding: '3px 8px',
                background: 'rgba(27,18,10,0.6)', backdropFilter: 'blur(4px)',
                fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.2em',
                color: 'var(--gold-300)', textTransform: 'uppercase',
              }}>
                {String(activeImg + 1).padStart(2,'0')} / {String(galleryImgs.length).padStart(2,'0')}
              </div>
            </div>
            {/* Thumbnails */}
            <div className="product-thumb-strip" style={{ display: 'flex', gap: 6, marginTop: 8, flexWrap: 'nowrap' }}>
              {galleryImgs.map((src, i) => (
                <button key={i} onClick={() => setActiveImg(i)} style={{
                  padding: 0, width: 56, height: 56,
                  outline: i === activeImg ? '2px solid var(--gold-300)' : '1px solid rgba(27,18,10,0.15)',
                  outlineOffset: 0, overflow: 'hidden', flexShrink: 0,
                }}>
                  <Placeholder label={`${i + 1}`} ratio="1/1" src={src} />
                </button>
              ))}
            </div>
          </div>

          {/* Info column */}
          <div className="product-info-col" style={{ padding: '0', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
            <div className="eyebrow" style={{ marginBottom: 16 }}>
              {s ? s.name[lang] : ''} · {t.product.sku} {product.sku}
            </div>
            <h1 style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 'clamp(40px, 5vw, 64px)', fontWeight: 400, lineHeight: 1.05, marginBottom: 26 }}>
              {displayName}
            </h1>
            <p style={{ fontSize: 19, color: 'var(--charcoal)', lineHeight: 1.55, marginBottom: 32 }}>
              {product.desc[lang]}
            </p>

            {/* Finishes */}
            <div className="product-finishes" style={{ marginBottom: 24 }}>
              <div className="eyebrow muted" style={{ marginBottom: 10 }}>{t.product.colors}</div>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {product.finishes.map((f, i) => (
                  <span key={i} title={f} style={{ width: 30, height: 30, background: f, border: '1px solid rgba(27,18,10,0.3)', display: 'inline-block', flexShrink: 0 }} />
                ))}
              </div>
            </div>

            {/* Specs */}
            <div className="product-specs" style={{ marginBottom: 28 }}>
              <div className="eyebrow muted" style={{ marginBottom: 10 }}>{t.product.specs}</div>
              <dl style={{ margin: 0, borderTop: '1px solid rgba(27,18,10,0.12)' }}>
                {Object.entries(product.specs).map(([k, val]) => (
                  <div key={k} style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 12, padding: '10px 0', borderBottom: '1px solid rgba(27,18,10,0.1)' }}>
                    <dt style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--muted)' }}>
                      {t.product.specsData[k] || k}
                    </dt>
                    <dd style={{ margin: 0, fontSize: 15, color: 'var(--ink)' }}>{val}</dd>
                  </div>
                ))}
              </dl>
            </div>

            <div className="product-actions" style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
              <button className="btn btn-primary" onClick={() => setShowQuote(true)}>
                {t.product.inquire} <span className="arrow"/>
              </button>
              <button className="btn" onClick={() => navigate({ page: 'sombreros', filter: product.style })}>
                {t.product.back}
              </button>
              <span className="eyebrow" style={{ color: 'var(--gold-600)' }}>{t.product.moq}</span>
            </div>
          </div>
        </div>
      </section>


      {lb && (
        <Lightbox
          images={lb.images}
          index={lb.index}
          onClose={() => setLb(null)}
          onNav={d => setLb({ ...lb, index: (lb.index + d + lb.images.length) % lb.images.length })}
        />
      )}
      {showQuote && <QuoteModal lang={lang} product={product} onClose={() => setShowQuote(false)} />}
    </div>
  );
}

// ── Quote Modal ───────────────────────────────────────────────────────────────
function QuoteModal({ lang, product, onClose }) {
  const t = I18N[lang];
  const [sent, setSent] = useState(false);
  const [sending, setSending] = useState(false);
  const [form, setForm] = useState({ name: '', company: '', email: '', message: '' });
  const [captchaToken, setCaptchaToken] = useState('');
  const [error, setError] = useState('');
  const displayName = lang === 'en' ? product.nameEn : lang === 'fr' ? product.nameFr : product.name;

  const submit = async (e) => {
    e.preventDefault();
    setSending(true);
    setError('');
    try {
      const res = await fetch(API_BASE + '/api/public/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          subject: `Cotización ${displayName} (${product.sku})`,
          message: `Empresa: ${form.company}\n${form.message}`,
          captchaToken,
        }),
      });
      const data = await res.json();
      if (data.ok) { setSent(true); }
      else { setError(data.error || 'Error al enviar'); }
    } catch { setError('Error de conexión'); }
    finally { setSending(false); }
  };

  return (
    <div className="lightbox" onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{ background: 'var(--parchment)', width: 'min(640px, 92vw)', padding: 48, position: 'relative' }}>
        <button onClick={onClose} style={{ position: 'absolute', top: 16, right: 16, fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--muted)' }}>✕</button>
        {!sent ? (
          <>
            <Ornament />
            <div className="eyebrow" style={{ margin: '16px 0' }}>{t.product.inquire}</div>
            <h3 style={{ fontSize: 36, fontStyle: 'italic', fontWeight: 400, marginBottom: 8 }}>{displayName}</h3>
            <p style={{ color: 'var(--muted)', marginBottom: 28 }}>{product.sku} · {t.product.moq}</p>
            <form onSubmit={submit}>
              <CaptchaField onCaptcha={setCaptchaToken} />
              <div className="form-grid">
                <div className="form-field"><label>{t.contact.form.name}</label><input required value={form.name} onChange={e => setForm({...form, name: e.target.value})} /></div>
                <div className="form-field"><label>{t.contact.form.company}</label><input value={form.company} onChange={e => setForm({...form, company: e.target.value})} /></div>
                <div className="form-field full"><label>{t.contact.form.email}</label><input type="email" required value={form.email} onChange={e => setForm({...form, email: e.target.value})} /></div>
                <div className="form-field full"><label>{t.contact.form.message}</label><textarea rows={4} value={form.message} onChange={e => setForm({...form, message: e.target.value})} /></div>
              </div>
              {error && <p style={{ color: 'var(--err)', fontFamily: 'var(--font-mono)', fontSize: 12, marginTop: 8, letterSpacing: '0.1em' }}>{error}</p>}
              <div style={{ marginTop: 28 }}>
                <button type="submit" className="btn btn-primary" disabled={sending}>{sending ? 'Enviando...' : `${t.contact.form.send}`} <span className="arrow"/></button>
              </div>
            </form>
          </>
        ) : (
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            <Ornament />
            <h3 style={{ fontSize: 32, fontStyle: 'italic', fontWeight: 400, margin: '20px 0 12px' }}>✦</h3>
            <p style={{ fontSize: 20, color: 'var(--charcoal)' }}>{t.contact.form.sent}</p>
          </div>
        )}
      </div>
    </div>
  );
}

// Keep old CatalogPage as alias for backwards compat
function CatalogPage({ lang, navigate, initialFilter }) {
  return <HatsPage lang={lang} navigate={navigate} initialFilter={initialFilter} />;
}

// Keep old ProductCard as alias used in pages-home.jsx
function ProductCard({ product, lang, navigate, compact = false }) {
  return <HatCard product={product} lang={lang} navigate={navigate} compact={compact} />;
}

Object.assign(window, { HatsPage, HatCard, HebillasPage, CoreasPage, ProductDetailPage, QuoteModal, CatalogPage, ProductCard });
