// pages-home.jsx — Home page
const { useState, useEffect, useRef, useMemo } = React;

function HomePage({ lang, navigate, onHeaderDark }) {
  const t = I18N[lang];
  const videoRef = useRef(null);

  useEffect(() => {
    const v = videoRef.current;
    if (!v) return;

    v.muted = true;
    v.setAttribute('muted', '');

    const isMobile = window.innerWidth <= 640;
    v.src = isMobile
      ? 'products/video-mobile.mp4'
      : 'products/video%20hero2.0.mp4';

    // Resume video on any real user gesture — keeps listening until video plays
    var cleanup = null;
    var resumeOnGesture = function () {
      var played = false;
      var tryResume = function () {
        if (played) return;
        v.play().then(function () { played = true; }).catch(function () {});
      };
      document.addEventListener('touchstart', tryResume, { passive: true });
      document.addEventListener('touchend', tryResume, { passive: true });
      document.addEventListener('click', tryResume);
      document.addEventListener('keydown', tryResume);
      cleanup = function () {
        document.removeEventListener('touchstart', tryResume);
        document.removeEventListener('touchend', tryResume);
        document.removeEventListener('click', tryResume);
        document.removeEventListener('keydown', tryResume);
      };
    };

    // Once video actually plays, stop listening for gestures
    var onPlaying = function () {
      if (cleanup) { cleanup(); cleanup = null; }
    };
    v.addEventListener('playing', onPlaying);

    // Try autoplay after data is ready
    var tryPlay = function () {
      v.play().catch(function () {
        // Autoplay blocked — listen for any user interaction
        resumeOnGesture();
      });
    };

    if (v.readyState >= 3) {
      tryPlay();
    } else {
      v.addEventListener('canplay', tryPlay, { once: true });
    }
    v.load();

    return function () {
      v.removeEventListener('canplay', tryPlay);
      v.removeEventListener('playing', onPlaying);
      if (cleanup) cleanup();
    };
  }, []);

  // Track scroll to toggle header darkness over hero
  useEffect(() => {
    const onScroll = () => {
      const y = window.scrollY;
      onHeaderDark(y < 520);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [onHeaderDark]);

  const featured = HAT_PRODUCTS.slice(0, 8);

  return (
    <div className="page-enter">
      {/* HERO — video */}
      <section className="hero-video-section" style={{ padding: 0, margin: 0, position: 'relative', background: '#000' }}>
        <div style={{ position: 'relative', height: 'min(96vh, 960px)', minHeight: 640, overflow: 'hidden' }}>
          <video
            ref={videoRef}
            autoPlay
            muted
            loop
            playsInline
            preload="auto"
            poster="products/video-poster.webp"
            disablePictureInPicture
            style={{
              position: 'absolute', inset: 0,
              width: '100%', height: '100%',
              objectFit: 'cover', objectPosition: 'center',
              zIndex: 0, pointerEvents: 'none',
            }}
          />
          {/* Vignette overlay */}
          <div style={{
            position: 'absolute', inset: 0, pointerEvents: 'none',
            background: 'linear-gradient(180deg, rgba(15,10,5,0.3) 0%, rgba(15,10,5,0.1) 35%, rgba(15,10,5,0.88) 100%)',
          }} />
          {/* Content */}
          <div className="container" style={{
            position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
            justifyContent: 'flex-end', paddingBottom: 'clamp(60px, 10vw, 140px)', color: 'var(--cream)',
          }}>
            <div style={{ maxWidth: 880 }}>
              <div style={{ marginBottom: 22 }}>
                <Ornament color="var(--gold-300)" />
              </div>
              <div className="eyebrow light" style={{ marginBottom: 22 }}>{t.hero.eyebrow}</div>
              <h1 style={{
                fontSize: 'clamp(56px, 9vw, 132px)',
                fontStyle: 'italic', fontWeight: 400, lineHeight: 0.95,
                letterSpacing: '-0.02em', color: 'var(--cream)',
                whiteSpace: 'pre-line', marginBottom: 32,
              }}>{t.hero.title}</h1>
              <p style={{
                fontSize: 'clamp(19px, 1.6vw, 22px)', maxWidth: '56ch',
                color: 'rgba(245,237,224,0.85)', marginBottom: 44, lineHeight: 1.55,
              }}>{t.hero.body}</p>
              <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
                <button className="btn btn-gold" onClick={() => window.location.href = '/portal'}>
                  {t.hero.ctaPrimary} <span className="arrow"/>
                </button>
                <button className="btn btn-ghost-light" onClick={() => navigate({ page: 'sombreros' })}>
                  {t.hero.ctaSecondary}
                </button>
              </div>
            </div>
          </div>
          {/* Scroll hint */}
          <div style={{
            position: 'absolute', bottom: 32, right: 'var(--gutter)',
            color: 'var(--gold-300)', fontFamily: 'var(--font-mono)',
            fontSize: 10, letterSpacing: '0.3em', textTransform: 'uppercase',
            display: 'flex', alignItems: 'center', gap: 14, writingMode: 'vertical-rl',
          }}>
            <span>{t.hero.scroll}</span>
            <span style={{ width: 1, height: 50, background: 'var(--gold-300)' }} />
          </div>
        </div>
      </section>

      {/* STATS */}
      <section style={{ padding: '0', margin: 0, background: 'var(--ink)', color: 'var(--cream)' }}>
        <div className="container stats-grid">
          {t.stats.map((s, i) => (
            <div key={i} style={{
              display: 'flex', flexDirection: 'column', gap: 8,
              borderLeft: i === 0 ? 'none' : '1px solid rgba(245,237,224,0.15)',
              paddingLeft: i === 0 ? 0 : 32,
            }}>
              <div style={{
                fontFamily: 'var(--font-display)', fontStyle: 'italic',
                fontSize: 52, color: 'var(--gold-300)', lineHeight: 1,
              }}>{s.k}</div>
              <div style={{
                fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.22em',
                textTransform: 'uppercase', color: 'rgba(245,237,224,0.6)',
              }}>{s.v}</div>
            </div>
          ))}
        </div>
      </section>

      {/* CUSTOM COLLECTIONS GRID — 7 category panels */}
      <section style={{ background: 'var(--parchment)', padding: '20px 0 100px' }}>
        <div className="container">
          <div className="section-head">
            <div className="eyebrow">{t.collections.eyebrow}</div>
            <h2>{t.collections.title}</h2>
            <p className="sub">{t.collections.body}</p>
          </div>
          
          <div className="cats-grid">
            {[
              { title: lang === 'es' ? '8 Segundos' : 'Brick', subtitle: 'SERIE I', page: 'sombreros', filter: 'brick', img: MODEL_PHOTOS[0] },
              { title: lang === 'es' ? 'Rebelde' : 'Dakota', subtitle: 'SERIE II', page: 'sombreros', filter: 'dakota', img: MODEL_PHOTOS[1] },
              { title: lang === 'es' ? 'Llanero' : 'Cattleman', subtitle: 'SERIE III', page: 'sombreros', filter: 'cattleman', img: MODEL_PHOTOS[2] },
              { title: lang === 'es' ? 'Randao' : 'Pinched Front', subtitle: 'SERIE IV', page: 'sombreros', filter: 'pinched-front', img: MODEL_PHOTOS[3] },
              { title: lang === 'es' ? 'Frontier' : 'Gus', subtitle: 'SERIE V', page: 'sombreros', filter: 'gus', img: MODEL_PHOTOS[4] },
              { title: lang === 'es' ? 'Hebillas' : 'Buckles', subtitle: 'COLECCIÓN', page: 'hebillas', filter: undefined, img: WEB_IMAGES[3] },
              { title: lang === 'es' ? 'Correas' : 'Belts', subtitle: 'COLECCIÓN', page: 'correas', filter: undefined, img: WEB_IMAGES[4] },
            ].map((c, i) => (
              <button
                key={i}
                onClick={() => navigate({ page: c.page, filter: c.filter })}
                className={`cat-card item-${i}`}
                style={{
                  position: 'relative', overflow: 'hidden',
                  padding: 0, border: 'none', background: 'var(--saddle-900)',
                  textAlign: 'left'
                }}
              >
                <img 
                  src={c.img} 
                  alt={c.title} 
                  loading="lazy"
                  style={{
                    position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'top center',
                    transition: 'transform 600ms var(--ease)'
                  }} 
                  className="cat-img"
                />
                <div style={{
                  position: 'absolute', inset: 0,
                  background: 'linear-gradient(180deg, rgba(0,0,0,0) 40%, rgba(15,10,5,0.85) 100%)',
                  pointerEvents: 'none'
                }} />
                
                <div style={{
                  position: 'absolute', inset: 0,
                  display: 'flex', flexDirection: 'column',
                  justifyContent: 'flex-end', alignItems: 'flex-start',
                  padding: 'clamp(20px, 3vw, 36px)'
                }}>
                  <div className="eyebrow light" style={{ marginBottom: 6 }}>
                    {c.subtitle}
                  </div>
                  <div style={{
                    fontFamily: 'var(--font-display)', fontWeight: 400, fontStyle: 'italic',
                    fontSize: 'clamp(28px, 3.5vw, 48px)', lineHeight: 1.05,
                    color: 'var(--cream)'
                  }}>
                    {c.title}
                  </div>
                </div>
              </button>
            ))}
          </div>
        </div>
      </section>

      {/* FEATURED PRODUCTS */}
      <section style={{ background: 'var(--cream)', padding: '100px 0' }}>
        <div className="container">
          <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 48, flexWrap: 'wrap', gap: 20 }}>
            <div>
              <div className="eyebrow" style={{ marginBottom: 16 }}>
                {lang === 'es' ? 'Selección · Destacados' : lang === 'fr' ? 'Sélection · Vedette' : 'Selection · Featured'}
              </div>
              <h2 style={{ fontSize: 'clamp(36px, 4.5vw, 56px)', fontStyle: 'italic', fontWeight: 400 }}>
                {lang === 'es' ? 'Piezas destacadas' : lang === 'fr' ? 'Pièces vedettes' : 'Featured pieces'}
              </h2>
            </div>
            <button className="link-inline" onClick={() => navigate({ page: 'sombreros' })}>
              {t.collections.viewAll} →
            </button>
          </div>
          <div className="featured-grid">
            {featured.map(p => (
              <HatCard key={p.id} product={p} lang={lang} navigate={navigate} compact />
            ))}
          </div>
        </div>
      </section>

      {/* ABOUT strip */}
      <section style={{ background: 'var(--saddle-900)', color: 'var(--cream)', padding: '120px 0' }}>
        <div className="container about-grid">
          <div>
            <Placeholder
              label="LEATHER · SensStyle"
              ratio="4/5"
              src="products/IMAGENES%20PARA%20WEB/about-hero-leather.webp"
              corner="ATELIER · 02"
            />
          </div>
          <div>
            <div style={{ color: 'var(--gold-300)', marginBottom: 22 }}>
              <Ornament color="var(--gold-300)" />
            </div>
            <div className="eyebrow light" style={{ marginBottom: 22 }}>{t.about.eyebrow}</div>
            <h2 style={{
              fontSize: 'clamp(44px, 5.5vw, 72px)',
              fontStyle: 'italic', fontWeight: 400, lineHeight: 1.05,
              color: 'var(--cream)', whiteSpace: 'pre-line', marginBottom: 36,
            }}>{t.about.title}</h2>
            <p style={{ color: 'rgba(245,237,224,0.82)', fontSize: 20, lineHeight: 1.6, marginBottom: 22 }}>{t.about.p1}</p>
            <p style={{ color: 'rgba(245,237,224,0.82)', fontSize: 20, lineHeight: 1.6, marginBottom: 40 }}>{t.about.p2}</p>
            <div style={{ display: 'flex', alignItems: 'center', gap: 32, flexWrap: 'wrap' }}>
              <button className="btn btn-ghost-light" onClick={() => navigate({ page: 'about' })}>
                {t.about.cta} <span className="arrow" />
              </button>
              <span style={{
                fontFamily: 'var(--font-display)', fontStyle: 'italic',
                fontSize: 24, color: 'var(--gold-300)',
              }}>— {t.about.stat}</span>
            </div>
          </div>
        </div>
      </section>

      {/* WHOLESALE band (big CTA) */}
      <section style={{ background: 'var(--ink)', color: 'var(--cream)', padding: '120px 0', position: 'relative', overflow: 'hidden' }}>
        <img src="products/IMAGENES%20PARA%20WEB/wholesale-bg.webp" alt="" loading="lazy" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center', opacity: 0.12, pointerEvents: 'none' }} />
        <div style={{
          position: 'absolute', inset: 0, opacity: 0.6,
          background: 'linear-gradient(to right, var(--ink) 30%, transparent 70%)',
        }} />
        <div className="container wholesale-grid">
          <div>
            <div className="eyebrow light" style={{ marginBottom: 22 }}>{t.wholesale.eyebrow}</div>
            <h2 style={{
              fontSize: 'clamp(48px, 6vw, 88px)',
              fontStyle: 'italic', fontWeight: 400, lineHeight: 1.02,
              color: 'var(--gold-300)', whiteSpace: 'pre-line', marginBottom: 32,
            }}>{t.wholesale.title}</h2>
            <p style={{ color: 'rgba(245,237,224,0.82)', fontSize: 20, lineHeight: 1.6, marginBottom: 40 }}>{t.wholesale.body}</p>
            <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
              <a href="/portal" className="btn btn-gold">
                {t.wholesale.cta} <span className="arrow" />
              </a>
              <a href="/portal" className="btn btn-ghost-light">
                {t.wholesale.login}
              </a>
            </div>
          </div>
          <ul style={{ listStyle: 'none', padding: 0, margin: 0, borderTop: '1px solid rgba(245,237,224,0.15)' }}>
            {t.wholesale.bullets.map((b, i) => (
              <li key={i} style={{
                padding: '22px 0',
                borderBottom: '1px solid rgba(245,237,224,0.15)',
                display: 'flex', alignItems: 'baseline', gap: 24,
              }}>
                <span style={{
                  fontFamily: 'var(--font-mono)', fontSize: 11,
                  color: 'var(--gold-300)', letterSpacing: '0.22em',
                  minWidth: 38,
                }}>{String(i + 1).padStart(2, '0')}</span>
                <span style={{ fontSize: 20, color: 'var(--cream)', lineHeight: 1.4 }}>{b}</span>
              </li>
            ))}
          </ul>
        </div>
      </section>

      {/* JOURNAL / notes */}
      <section style={{ background: 'var(--parchment)' }}>
        <div className="container">
          <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 48, flexWrap: 'wrap', gap: 20 }}>
            <div>
              <div className="eyebrow" style={{ marginBottom: 16 }}>{t.journal.eyebrow}</div>
              <h2 style={{ fontSize: 'clamp(36px, 4.5vw, 56px)', fontStyle: 'italic', fontWeight: 400 }}>
                {t.journal.title}
              </h2>
            </div>
          </div>
          <div className="journal-grid">
            {t.journal.posts.map((p, i) => {
              const postSlug = p.slug || null;
              // Find the actual blog post to get its hero image
              const blogPost = BLOG_POSTS.find(b => b.slug === postSlug);
              const heroImg = blogPost ? blogPost.hero : WEB_IMAGES[i];
              return (
              <a href="#" key={i} onClick={(e) => { e.preventDefault(); if (postSlug) navigate({ page: 'blog-post', slug: postSlug }); }} style={{ display: 'block' }}>
                <Placeholder
                  label={`${p.tag.toUpperCase()} · ${p.title}`}
                  ratio="5/4"
                  src={heroImg}
                  corner={`N° ${String(i + 1).padStart(2, '0')}`}
                />
                <div style={{ padding: '24px 0' }}>
                  <div className="eyebrow" style={{ marginBottom: 10 }}>{p.tag} · {p.read}</div>
                  <h3 style={{
                    fontFamily: 'var(--font-display)', fontStyle: 'italic',
                    fontSize: 28, fontWeight: 400, lineHeight: 1.15,
                  }}>{p.title}</h3>
                </div>
              </a>
              );
            })}
          </div>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { HomePage });
