// THE EPIZODE — homepage.
// Uses shared layout (header / footer / theme) from layout.jsx.

function EpzHomepage() {
  const F = EPZ_FONTS;
  useEpzLang();
  const items = EPZ_COLLECTION;
  // Порядок мозаики кампейна фиксируется на загрузку страницы (микс — только при обновлении,
  // без дёрганья на ре-рендерах). Платок Тони (004) всегда в малом квадрате.
  const mosaicSlots = React.useMemo(() => {
    const byId = (id) => EPZ_EPISODES.find((e) => e.id === id);
    const others = ['001', '002', '003'].map(byId);
    for (let i = others.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); const t = others[i]; others[i] = others[j]; others[j] = t; }
    return [{ area: 'a', ep: others[0] }, { area: 'b', ep: others[1] }, { area: 'c', ep: others[2] }, { area: 'd', ep: byId('004') }];
  }, []);
  // Бегущая строка-плёнка скрыта (дублировала кампейн). Вернуть → true.
  const SHOW_FILM_ROLL = false;
  const featured = items[2];

  const [theme, setTheme, T] = useEpzTheme();
  const dark = theme === 'dark';
  const cornerCol = T.cornerCrop;
  const [clubOpen, setClubOpen] = React.useState(false);

  // Герой занимает ровно первый экран (шапка sticky и в потоке — вычитаем её высоту),
  // чтобы снизу не выглядывал следующий блок: 100% погружение в первый кадр.
  const [hdrH, setHdrH] = React.useState(63);
  React.useEffect(() => {
    const measure = () => {
      const h = document.querySelector('header');
      if (h) setHdrH(Math.round(h.getBoundingClientRect().height));
    };
    measure();
    window.addEventListener('resize', measure);
    return () => window.removeEventListener('resize', measure);
  }, []);

  // Live scrubber: real seconds ticking 0 → 4:00 (4 episodes ≈ 4 minutes), then loops.
  const SCRUB_TOTAL = 240;
  const [elapsed, setElapsed] = React.useState(0);
  React.useEffect(() => {
    const t = setInterval(() => setElapsed((e) => (e + 1) % (SCRUB_TOTAL + 1)), 1000);
    return () => clearInterval(t);
  }, []);
  const fmtTime = (s) => `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`;
  const scrubPct = elapsed / SCRUB_TOTAL * 100;

  // Catalog carousel — index-based, whole-card aligned, custom smooth easing.
  const railRef = React.useRef(null);
  const showcaseLen = epzHomeShowcase().length;
  const idxRef = React.useRef(showcaseLen); // start of middle copy
  const animRef = React.useRef(false);
  function railCards() {
    return railRef.current ? railRef.current.querySelectorAll('.home-card') : [];
  }
  function animateScroll(el, to, dur) {
    animRef.current = true;
    const start = el.scrollLeft,change = to - start,t0 = performance.now();
    const ease = (p) => p < 0.5 ? 4 * p * p * p : 1 - Math.pow(-2 * p + 2, 3) / 2;
    function step(now) {
      const p = Math.min(1, (now - t0) / dur);
      el.scrollLeft = start + change * ease(p);
      if (p < 1) requestAnimationFrame(step);else animRef.current = false;
    }
    requestAnimationFrame(step);
  }
  function alignTo(i, animate) {
    const el = railRef.current;const cards = railCards();
    if (!el || !cards[i]) return;
    const target = cards[i].offsetLeft - 32; // flush to left padding → whole card
    if (animate) animateScroll(el, target, 780);else
    el.scrollLeft = target;
  }
  function nearestIdx() {
    const el = railRef.current;const cards = railCards();
    if (!el || !cards.length) return idxRef.current;
    let best = 0,bd = Infinity;
    cards.forEach((c, i) => {
      const d = Math.abs(c.offsetLeft - 32 - el.scrollLeft);
      if (d < bd) {bd = d;best = i;}
    });
    return best;
  }
  function scrollRail(dir) {
    const N = showcaseLen;
    let i = nearestIdx() + dir * 2;
    alignTo(i, true);
    idxRef.current = i;
    setTimeout(() => {
      let j = idxRef.current;
      if (j < N) {j += N;alignTo(j, false);idxRef.current = j;} else
      if (j >= 2 * N) {j -= N;alignTo(j, false);idxRef.current = j;}
    }, 820);
  }
  React.useEffect(() => {
    idxRef.current = showcaseLen;
    const t = setTimeout(() => alignTo(showcaseLen, false), 60);
    // бесконечная прокрутка: при ручном скролле незаметно перебрасываем в среднюю копию
    const el = railRef.current;
    const N = showcaseLen;
    const onScroll = () => {
      if (animRef.current || !el) return;
      const cards = railCards();
      if (cards.length < 2 * N) return;
      const setW = cards[N].offsetLeft - cards[0].offsetLeft;
      const base = cards[0].offsetLeft - 32;
      if (el.scrollLeft < base + setW * 0.15) el.scrollLeft += setW;else
      if (el.scrollLeft > base + setW * 1.85) el.scrollLeft -= setW;
    };
    if (el) el.addEventListener('scroll', onScroll, { passive: true });
    return () => {clearTimeout(t);if (el) el.removeEventListener('scroll', onScroll);};
  }, []);

  return (
    <div style={{
      width: '100%',
      background: T.bg,
      color: T.text,
      fontFamily: F.mono,
      fontSize: 13,
      lineHeight: 1.5,
      WebkitFontSmoothing: 'antialiased',
      transition: 'background 0.3s ease, color 0.3s ease'
    }}>
      <style>{`
        @keyframes epzScan {
          0%   { transform: translateY(-100%); }
          100% { transform: translateY(100vh); }
        }
        @keyframes epzFlicker {
          0%,100% { opacity: 0.95; }
          50%     { opacity: 1; }
          51%     { opacity: 0.85; }
        }
        @keyframes epzScrub {
          0%   { left: 8%; }
          100% { left: 92%; }
        }
        @keyframes epzTicker {
          from { transform: translateX(0); }
          to   { transform: translateX(-50%); }
        }
        @keyframes epzKenBurns {
          0%   { transform: scale(1.04); }
          100% { transform: scale(1.28) translateY(3%); }
        }
        @keyframes epzGrain {
          0%,100% { transform: translate(0,0); }
          25% { transform: translate(2%, -2%); }
          50% { transform: translate(-2%, 2%); }
          75% { transform: translate(1%, 1%); }
        }
        .epz-scanline { animation: epzScan 8s linear infinite; }
        .epz-flicker  { animation: epzFlicker 4s infinite; }
        .epz-scrub    { animation: epzScrub 14s ease-in-out infinite alternate; }
        @keyframes epzRecBlink { 0%, 55%, 100% { opacity: 1; } 65%, 90% { opacity: 0.15; } }
        .epz-rec-dot  { animation: epzRecBlink 1.8s ease-in-out infinite; }
        .epz-rail { scrollbar-width: none; -ms-overflow-style: none; }
        .epz-rail::-webkit-scrollbar { display: none; }
        .epz-rail-card { transition: opacity 0.2s; }
        .home-img-wrap { position: relative; overflow: hidden; aspect-ratio: 3/4; }
        .home-img, .home-img-alt { position: absolute; inset: 0; background-size: cover; background-position: center; background-repeat: no-repeat; transition: opacity 0.55s ease, transform 0.7s ease; }
        .home-img-wrap.is-photo { background-color: #FAF6EE; }
        .home-img-contain, .home-img-alt-contain { background-size: contain !important; mix-blend-mode: multiply; inset: 14px !important; }
        .home-img-alt { opacity: 0; }
        .home-card:hover .home-img-alt { opacity: 1; }
        .home-card:hover .home-img { opacity: 0; }
        .home-actions { display: none; }
        .home-sizes { display: none; }
        .home-card:hover .home-meta { display: none; }
        .home-card:hover .home-sizes { display: block; }
        @media (hover: none) { .home-card:hover .home-meta { display: block; } .home-card:hover .home-sizes { display: none; } }
        @media (max-width: 680px) {
          .epz-rail-card { width: 44vw !important; }
          .epz-rail { gap: 10px !important; padding-left: 16px !important; padding-right: 16px !important; }
          .epz-scrub-row { gap: 12px !important; padding: 0 16px !important; }
          .epz-scrub-hide { display: none !important; }
          .epz-hero-corner { font-size: 8px !important; right: 14px !important; }
          .epz-hero-corner-tr { top: 14px !important; }
          .epz-hero-corner-br { bottom: 14px !important; }
        }
        .epz-camp-img { transition: transform 0.7s ease; }
        .epz-camp:hover .epz-camp-img { transform: scale(1.06); }
        .epz-camp-cta { transition: opacity 0.2s ease; }
        .epz-camp:hover .epz-camp-cta { opacity: 1; }
        .epz-mosaic { display: grid; }
        .epz-hero-cta { transition: padding 0.4s cubic-bezier(.7,0,.2,1), letter-spacing 0.4s ease; }
        .epz-hero-cta:hover { padding-left: 52px !important; padding-right: 52px !important; letter-spacing: 0.36em !important; }
        .epz-pill { transition: background 0.25s ease, color 0.25s ease, border-color 0.25s ease, letter-spacing 0.35s ease; }
        a.epz-pill:hover { background: #EFE7D6 !important; color: #14110E !important; border-color: #EFE7D6 !important; letter-spacing: 0.26em !important; }
        a.epz-pill-fill:hover { background: #4E1117 !important; color: #EFE7D6 !important; letter-spacing: 0.26em !important; }
        @media (max-width: 760px) {
          .epz-mosaic { grid-template-columns: 1fr 1fr !important; grid-template-areas: none !important; grid-auto-rows: 46vw; height: auto !important; }
          .epz-mosaic .epz-camp { grid-area: auto !important; }
        }
        .epz-ticker   { animation: epzTicker 45s linear infinite; }
        .epz-ken      { animation: epzKenBurns 12s ease-in-out infinite alternate; }
        .epz-grain    { animation: epzGrain 1.4s steps(6) infinite; }
        .epz-ep-card a, .epz-ep-card { color: inherit; text-decoration: none; }
      `}</style>

      <EpzHeader theme={theme} setTheme={setTheme} T={T} current="archive" />

      {/* ═════════════════════ HERO — видео ~5 сек (положить файл assets/video-hero-1.mp4; пока его нет — показывается постер) ═════════════════════ */}
      <section style={{ position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'relative', height: `calc(100svh - ${hdrH}px)`, minHeight: 560, overflow: 'hidden', background: '#000' }}>
          <video autoPlay muted loop playsInline
            poster="/assets/hero-home.jpg"
            src="/assets/video-hero-1.mp4"
            style={{
              position: 'absolute', inset: 0, width: '100%', height: '100%',
              objectFit: 'cover', objectPosition: 'center 22%',
              filter: dark ?
              'contrast(1.04) brightness(0.9) saturate(0.9)' :
              'contrast(1.02) brightness(1) saturate(0.98)'
            }}></video>
          <div style={{
            position: 'absolute', inset: 0,
            background: dark ?
            'linear-gradient(to top, rgba(20,17,14,0.85) 0%, rgba(20,17,14,0.25) 45%, rgba(20,17,14,0.55) 100%)' :
            'linear-gradient(to top, rgba(246,241,228,0.55) 0%, rgba(0,0,0,0.10) 45%, rgba(0,0,0,0.30) 100%)',
            transition: 'background 0.3s ease'
          }} />

          {/* REC indicator top-left */}
          <div style={{
            position: 'absolute', top: 24, left: 24,
            display: 'flex', gap: 9, alignItems: 'center',
            fontSize: 10, letterSpacing: '0.24em', textTransform: 'uppercase',
            color: T.text, opacity: 0.92
          }}>
            <span className="epz-rec-dot" style={{ width: 9, height: 9, borderRadius: 9, background: T.accent, display: 'inline-block' }} />
            <span>rec</span>
          </div>

          {/* CTA на заглавном кадре — прозрачная кнопка */}
          <div style={{ position: 'absolute', left: 0, right: 0, bottom: 40, display: 'flex', justifyContent: 'center' }}>
            <a href="#pilot" onClick={(e) => { e.preventDefault(); const el = document.getElementById('pilot'); if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.pageYOffset - 10, behavior: 'smooth' }); }} className="epz-hero-cta" style={{
              position: 'relative', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              padding: '16px 30px', color: '#EFE7D6', textDecoration: 'none',
              fontFamily: F.mono, fontSize: 13, letterSpacing: '0.3em', textTransform: 'uppercase',
              textShadow: '0 2px 12px rgba(0,0,0,0.5)',
            }}>
              {[['t', 'l'], ['t', 'r'], ['b', 'l'], ['b', 'r']].map(([v, h], i) => (
                <span key={i} style={{
                  position: 'absolute', width: 16, height: 16,
                  top: v === 't' ? 0 : 'auto', bottom: v === 'b' ? 0 : 'auto',
                  left: h === 'l' ? 0 : 'auto', right: h === 'r' ? 0 : 'auto',
                  borderTop: v === 't' ? '1.5px solid rgba(239,231,214,0.85)' : 'none',
                  borderBottom: v === 'b' ? '1.5px solid rgba(239,231,214,0.85)' : 'none',
                  borderLeft: h === 'l' ? '1.5px solid rgba(239,231,214,0.85)' : 'none',
                  borderRight: h === 'r' ? '1.5px solid rgba(239,231,214,0.85)' : 'none',
                }} />
              ))}
              {epzT('смотреть коллекцию')}
            </a>
          </div>
        </div>

      </section>

      {/* ═════════════════════ Большое горизонтальное фото ═════════════════════ */}
      <section style={{ position: 'relative', height: '78vh', minHeight: 620, overflow: 'hidden', background: '#000' }}>
        <div style={{
          position: 'absolute', inset: 0,
          backgroundImage: 'url(/assets/hero-hatsumomo.jpg)',
          backgroundSize: 'cover', backgroundPosition: 'center 18%',
          filter: dark ? 'contrast(1.04) brightness(0.9) saturate(0.9)' : 'none'
        }}></div>
        <a href="/catalog/" className="epz-pill" style={{
          position: 'absolute', left: 'clamp(24px, 3.5vw, 56px)', bottom: 'clamp(28px, 3.5vw, 56px)',
          display: 'inline-flex', alignItems: 'center', gap: 8,
          border: '1px solid rgba(239,231,214,0.6)', color: '#EFE7D6', textDecoration: 'none',
          borderRadius: 40, padding: '10px 20px', fontFamily: F.mono, fontSize: 10,
          letterSpacing: '0.18em', textTransform: 'uppercase', textShadow: '0 1px 8px rgba(0,0,0,0.4)'
        }}>{epzT('перейти в каталог')} →</a>
      </section>

      {/* ═════════════════════ CAMPAIGN — мозаика (большой + 3) — вместо коллажа ═════════════════════ */}
      <section style={{ padding: 0 }}>
        {(() => {
          const slots = mosaicSlots;
          return (
            <div className="epz-mosaic" style={{ gridTemplateColumns: '1.6fr 1fr 1fr', gridTemplateRows: '1fr 1fr', gridTemplateAreas: '"a b c" "a b d"', gap: 0, height: 'clamp(520px, 56vw, 840px)' }}>
              {slots.map(({ area, ep }) => {
                const arts = epzArticlesOf(ep.id);
                const cImg = ep.image || (arts.find((x) => x.image) || {}).image || null;
                const contain = ep.campaignContain || !ep.image;
                return (
                  <a key={area} href={`/episode-${ep.id}/`} className="epz-camp" style={{ gridArea: area, position: 'relative', overflow: 'hidden', color: '#EFE7D6', textDecoration: 'none', background: contain ? EPZ_COLORS.photoBg : '#000' }}>
                    {cImg ?
                      <div className="epz-camp-img" style={{ position: 'absolute', inset: 0, backgroundImage: `url(${cImg})`, backgroundSize: contain ? 'contain' : 'cover', backgroundPosition: contain ? 'center' : 'center 22%', backgroundRepeat: 'no-repeat', mixBlendMode: contain ? 'multiply' : 'normal', filter: contain ? 'none' : 'contrast(1.04) brightness(0.9)' }} /> :
                      <EpzPlaceholder label={`${epzT('Эпизод')} ${ep.id}`} sub={epzT(ep.title)} ratio="auto" tone="dark" style={{ aspectRatio: 'auto', width: '100%', height: '100%' }} />
                    }
                    <div style={{ position: 'absolute', left: 0, right: 0, bottom: 20, display: 'flex', justifyContent: 'center' }}>
                      <div className="epz-camp-cta" style={{ fontFamily: F.mono, fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: '#EFE7D6', textShadow: '0 2px 10px rgba(0,0,0,0.6)' }}>{epzT('смотреть эпизод')} →</div>
                    </div>
                  </a>
                );
              })}
            </div>
          );
        })()}
      </section>

      {/* ═════════════════════ КОЛЛЕКЦИЯ «ПИЛОТ» — сетка 4 в ряд, без бокового скролла ═════════════════════ */}
      <section id="pilot" style={{ padding: '48px 0 56px' }}>
        <div style={{ padding: '0 32px', marginBottom: 18 }}>
          <h2 style={{
            fontFamily: F.mono, fontSize: 10, letterSpacing: '0.24em',
            textTransform: 'uppercase', opacity: 0.5, fontWeight: 400, margin: 0
          }}>{epzT('Коллекция «Пилот»')}</h2>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 20, padding: '0 32px' }}>
          {(() => {
            // порядок карточек задан вручную: платье Catherine → платье Elvira → комплект Elvira шёлк →
            // платье Hatsumomo → комплект Elvira вискоза → тренч Catherine → платок Tony → комплект Catherine
            const ORDER = ['001-1', '002-1', '002-2:set', '003-1', '002-3:set', '001-2', '004-1', '001-set'];
            const all = epzHomeShowcase();
            return ORDER.map((id) => all.find((a) => a.id === id)).filter(Boolean)
              .map((a) => <HomeProductCard key={a.id} a={a} T={T} grid />);
          })()}
        </div>
        <div style={{ display: 'flex', justifyContent: 'center', marginTop: 34 }}>
          <a href="/catalog/" style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            border: `1px solid ${T.text}`, color: T.text, textDecoration: 'none',
            padding: '13px 30px', fontFamily: F.mono, fontSize: 10,
            letterSpacing: '0.2em', textTransform: 'uppercase'
          }}>{epzT('смотреть полностью')}</a>
        </div>
      </section>

      {/* ═════════════════════ FILM ROLL ═════════════════════ */}
      {/* СКРЫТО по просьбе: бегущая строка из фото дублировала кампейн.
          Сохранено для будущего — поменять SHOW_FILM_ROLL на true, чтобы вернуть. */}
      {SHOW_FILM_ROLL && (
      <section style={{
        background: T.filmStrip, padding: '40px 0', margin: '24px 0 60px', overflow: 'hidden',
        borderTop: `1px solid ${T.border}`,
        borderBottom: `1px solid ${T.border}`
      }}>
        <div style={{
          height: 12,
          backgroundImage: `radial-gradient(circle at 50% 50%, ${T.filmGap} 1.6px, transparent 1.7px)`,
          backgroundSize: '14px 100%', backgroundRepeat: 'repeat-x', backgroundPosition: '0 50%',
          marginBottom: 16
        }} />
        <div className="epz-ticker" style={{ display: 'flex', width: 'max-content' }}>
          {[0, 1].map((dup) =>
          <div key={dup} style={{ display: 'flex', gap: 4, paddingRight: 4 }}>
              {[0, 1, 2, 3, 2, 1, 0, 3].map((idx, i) => {
              const it = items[idx];
              return (
                <div key={i} style={{
                  width: 240, height: 320, position: 'relative',
                  border: '2px solid #000',
                  background: it.image ?
                  `center 25% / cover no-repeat url(${it.image}) ` : '#2a1a18',
                  filter: 'grayscale(0.3) contrast(1.05)'
                }}>
                    {!it.image &&
                  <EpzPlaceholder label={it.title} sub={it.scene} ratio="auto" tone="dark"
                  style={{ aspectRatio: 'auto', width: '100%', height: '100%' }} />
                  }
                    <div style={{
                    position: 'absolute', bottom: 8, left: 10,
                    fontSize: 9, letterSpacing: '0.22em', textTransform: 'uppercase',
                    color: '#EFE7D6', mixBlendMode: 'screen'
                  }}>
                      ep&nbsp;{it.id} · {it.timecode}
                    </div>
                  </div>);

            })}
            </div>
          )}
        </div>
        <div style={{
          height: 12,
          backgroundImage: `radial-gradient(circle at 50% 50%, ${T.filmGap} 1.6px, transparent 1.7px)`,
          backgroundSize: '14px 100%', backgroundRepeat: 'repeat-x', backgroundPosition: '0 50%',
          marginTop: 16
        }} />
      </section>
      )}

      {/* ═════════════════════ LOYALTY teaser ═════════════════════ */}
      {/* лояльность-тизер убран с главной по просьбе */}

      {/* ═════════════════════ COMMUNITY (UGC) ═════════════════════ */}
      <EpzCommunityTeaser T={T} />

      {/* ═════════════════════ MANIFESTO ═════════════════════ */}
      {/* Убран с главной по просьбе. Вёрстка сохранена в founder-quote.jsx (window.EpzFounderQuote) — для будущей страницы. */}

      {/* ═════════════════════ INNER CIRCLE — Telegram (компакт, по центру) ═════════════════════ */}
      <section id="club" className="epz-m1" style={{
        margin: '32px 32px 0', padding: 'clamp(40px, 4.5vw, 60px) clamp(32px, 4vw, 56px)', scrollMarginTop: 80,
        background: T.bgFeatured, border: `1px solid ${T.border}`, textAlign: 'center'
      }}>
        <img src="/assets/founder.jpg" alt={epzT('Ольга Колесник, основательница THE EPIZODE')}
          style={{ width: 76, height: 76, borderRadius: 76, objectFit: 'cover', objectPosition: 'center 20%', display: 'block', margin: '0 auto' }} />
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 9, fontFamily: F.mono, fontSize: 10, letterSpacing: '0.24em', textTransform: 'uppercase', color: T.accentInk, marginTop: 16 }}>
          <span className="epz-rec-dot" style={{ width: 7, height: 7, borderRadius: 7, background: T.accent, display: 'inline-block' }} />
          {epzT('закрытый показ · только для клиентов бренда')}
        </div>
        <p style={{ margin: '12px auto 0', fontFamily: F.body, fontSize: 15, lineHeight: 1.6, letterSpacing: 0, opacity: 0.55, maxWidth: 420 }}>
          {epzT('Telegram-канал основательницы бренда')}
        </p>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 24, marginTop: 22, flexWrap: 'wrap' }}>
          <span style={{ fontFamily: F.display, fontSize: 44, fontWeight: 300, lineHeight: 0.85, color: T.accentInk }}>83<span style={{ fontSize: 20, opacity: 0.4, color: T.text }}> / 300</span></span>
          <div style={{ position: 'relative', width: 180, height: 5, background: T.border, overflow: 'hidden' }}>
            <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: `${(83 / 300) * 100}%`, background: T.accent }} />
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 36px', maxWidth: 620, margin: '26px auto 0', borderTop: `1px solid ${T.border}`, textAlign: 'left' }}>
          {['выбор тканей для коллекций', 'ваш голос за кино', 'эскизы до релиза', 'ранний предзаказ', 'доступ к покупке образцов', '−10% на первый заказ'].map((perk, i) => (
            <div key={perk} style={{ display: 'flex', alignItems: 'baseline', gap: 12, padding: '9px 0', borderBottom: `1px solid ${T.border}` }}>
              <span style={{ fontFamily: F.mono, fontSize: 9, letterSpacing: '0.1em', color: T.accentInk, minWidth: 16 }}>{String(i + 1).padStart(2, '0')}</span>
              <span style={{ fontFamily: F.mono, fontSize: 9.5, letterSpacing: '0.13em', textTransform: 'uppercase', opacity: 0.78 }}>{epzT(perk)}</span>
            </div>
          ))}
        </div>
        <button onClick={() => setClubOpen(true)} style={{
          marginTop: 28, display: 'inline-flex', alignItems: 'center', gap: 12,
          background: T.btnPrimary, color: T.btnPrimaryFg, border: 0, cursor: 'pointer',
          padding: '15px 26px', fontFamily: F.mono, fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase'
        }}>{epzT('запросить приглашение →')}
        </button>
      </section>

      <EpzFooter T={T} />
      <EpzClubModal open={clubOpen} onClose={() => setClubOpen(false)} T={T} />
    </div>);

}

// ─── Club invite modal — клиенты бренда → закрытый телеграм ───────────────────
function EpzClubModal({ open, onClose, T }) {
  const F = EPZ_FONTS;
  const [sent, setSent] = React.useState(false);
  const [form, setForm] = React.useState({ name: '', contact: '', order: '', about: '' });

  React.useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => { document.body.style.overflow = ''; window.removeEventListener('keydown', onKey); };
  }, [open]);

  function submit(e) {
    e.preventDefault();
    // Persist request locally so the founder can review (демо — без бэкенда).
    try {
      const list = JSON.parse(localStorage.getItem('epz-club-requests') || '[]');
      list.push({ ...form, at: new Date().toISOString() });
      localStorage.setItem('epz-club-requests', JSON.stringify(list));
    } catch (err) {}
    setSent(true);
  }

  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));
  const field = {
    width: '100%', background: 'transparent', color: T.text, outline: 'none',
    border: `1px solid ${T.border}`, padding: '14px 16px', marginBottom: '-1px',
    fontFamily: F.mono, fontSize: 14,
  };

  return (
    <>
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, zIndex: 110, background: 'rgba(0,0,0,0.6)',
        opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none', transition: 'opacity 0.3s ease',
      }} />
      <div role="dialog" aria-modal="true" style={{
        position: 'fixed', zIndex: 111, top: '50%', left: '50%',
        width: 'min(560px, 92vw)', maxHeight: '88vh', overflowY: 'auto',
        transform: open ? 'translate(-50%, -50%)' : 'translate(-50%, -46%)',
        opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none',
        transition: 'opacity 0.3s ease, transform 0.3s ease',
        background: T.bg, color: T.text, border: `1px solid ${T.border}`,
        boxShadow: '0 30px 90px rgba(0,0,0,0.5)', padding: 'clamp(28px, 4vw, 44px)',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 22 }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontFamily: F.mono, fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase', color: T.accentInk }}>
            <span style={{ width: 6, height: 6, borderRadius: 6, background: T.accent, display: 'inline-block' }} />
            за кулисами · по приглашению
          </div>
          <button onClick={onClose} aria-label="Закрыть" style={{ background: 'transparent', color: 'inherit', border: 0, cursor: 'pointer', fontFamily: F.mono, fontSize: 16, lineHeight: 1 }}>✕</button>
        </div>

        {sent ? (
          <div style={{ padding: '20px 0 8px' }}>
            <h3 style={{ fontFamily: F.display, fontSize: 'clamp(34px, 5vw, 52px)', fontWeight: 300, fontStyle: 'italic', lineHeight: 1.05, margin: 0 }}>
              Заявка принята.
            </h3>
            <p style={{ marginTop: 18, fontFamily: F.body, fontSize: 15, lineHeight: 1.6, opacity: 0.82 }}>
              Мы проверим вашу историю заказов и пришлём персональную ссылку-приглашение в течение пары дней. Если что-то понадобится уточнить — напишем на указанный контакт.
            </p>
            <button onClick={onClose} style={{
              marginTop: 28, background: T.btnPrimary, color: T.btnPrimaryFg, border: 0, cursor: 'pointer',
              padding: '16px 26px', fontFamily: F.mono, fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase',
            }}>хорошо →</button>
          </div>
        ) : (
          <>
            <h3 style={{ fontFamily: F.display, fontSize: 'clamp(30px, 4vw, 44px)', fontWeight: 300, fontStyle: 'italic', lineHeight: 1.08, margin: 0 }}>
              Запросить приглашение
            </h3>
            <p style={{ marginTop: 14, fontFamily: F.body, fontSize: 14, lineHeight: 1.6, opacity: 0.78 }}>
              Канал — закрытый, только для тех, кто уже покупал THE EPIZODE. Оставьте контакты и номер заказа: мы сверим и пришлём личную ссылку.
            </p>
            <form onSubmit={submit} style={{ marginTop: 24 }}>
              <input required placeholder="имя" value={form.name} onChange={set('name')} style={field} />
              <input required placeholder="telegram (@ник) или email" value={form.contact} onChange={set('contact')} style={field} />
              <input placeholder="номер заказа (EPZ-000000)" value={form.order} onChange={set('order')} style={field} />
              <textarea placeholder="что носите из THE EPIZODE? (необязательно)" value={form.about} onChange={set('about')} rows={3} style={{ ...field, resize: 'vertical', fontFamily: F.body }} />
              <button type="submit" style={{
                marginTop: 22, width: '100%', background: T.btnPrimary, color: T.btnPrimaryFg, border: 0, cursor: 'pointer',
                padding: '18px 24px', fontFamily: F.mono, fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase',
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              }}>
                <span>отправить заявку</span><span>→</span>
              </button>
              <div style={{ marginTop: 14, fontFamily: F.body, fontSize: 12, lineHeight: 1.5, opacity: 0.5 }}>
                Нажимая «отправить», вы соглашаетесь, что мы свяжемся с вами по указанному контакту.
              </div>
            </form>
          </>
        )}
      </div>
    </>
  );
}

// ─── Newsletter block — RU, −10% first order, consent ────────────────────────
function EpzNewsletter({ T }) {
  const F = EPZ_FONTS;
  useEpzLang();
  const [email, setEmail] = React.useState('');
  const [agree, setAgree] = React.useState(false);
  const [sent, setSent] = React.useState(false);
  function submit(e) {
    e.preventDefault();
    if (!email || !agree) return;
    setSent(true);
    epzToast(epzT('Промокод на −10% отправлен на почту'));
  }
  return (
    <div style={{ padding: '60px 32px', borderRight: `1px solid ${T.border}` }}>
      <div style={{ fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase', opacity: 0.55, marginBottom: 16 }}>
        {epzT('THE NEXT EPIZODE')}
      </div>
      {sent ?
      <div>
          <div style={{ fontFamily: F.display, fontSize: 36, fontStyle: 'italic', lineHeight: 1.1 }}>
            {epzT('Спасибо! Промокод на −10% уже летит на вашу почту.')}
          </div>
          <div style={{ marginTop: 16, fontFamily: F.body, fontSize: 14, letterSpacing: 0, textTransform: 'none', opacity: 0.7, maxWidth: 420, lineHeight: 1.6 }}>
            {epzT('Применится к первому заказу. И вы первой узнаете об открытии эпизода 002.')}
          </div>
        </div> :

      <form onSubmit={submit}>
          <div style={{ display: 'flex', gap: 22, alignItems: 'flex-start' }}>
            <div className="serif" style={{ fontFamily: F.display, color: T.accentInk, fontSize: 70, lineHeight: 0.8, flexShrink: 0 }}>
              −10<span style={{ fontSize: 32 }}>%</span>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: F.display, fontSize: 28, fontWeight: 500, lineHeight: 1.12 }}>
                {epzT('скидка на первый заказ')}
              </div>
              <div style={{ marginTop: 10, fontFamily: F.body, fontSize: 13, letterSpacing: 0, textTransform: 'none', opacity: 0.66, maxWidth: 440, lineHeight: 1.55 }}>
                {epzT('Оставьте e-mail, и мы первыми сообщим о новых поступлениях')}
              </div>
            </div>
          </div>
          <div style={{ marginTop: 24, display: 'flex', gap: 0 }}>
            <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="вашa@почта.ru" required style={{
            flex: 1, border: `1px solid ${T.text}`, borderRight: 0, background: 'transparent', padding: '15px 14px',
            fontFamily: F.mono, fontSize: 14, color: T.text, outline: 'none'
          }} />
            <button type="submit" style={{
            border: 0, background: T.btnPrimary, padding: '0 24px',
            fontFamily: F.mono, fontSize: 11, letterSpacing: '0.2em',
            textTransform: 'uppercase', cursor: 'pointer', color: T.btnPrimaryFg, whiteSpace: 'nowrap'
          }}>
              {epzT('получить −10%')}
            </button>
          </div>
          {/* preferences removed per request */}
          <label style={{ marginTop: 20, display: 'flex', alignItems: 'flex-start', gap: 10, cursor: 'pointer' }}>
            <input type="checkbox" checked={agree} onChange={(e) => setAgree(e.target.checked)} required
          style={{ position: 'absolute', opacity: 0, width: 15, height: 15 }} />
            <span aria-hidden="true" style={{ width: 15, height: 15, marginTop: 2, flexShrink: 0, borderRadius: 3, border: `1.5px solid ${agree ? T.accent : T.border}`, background: agree ? T.accent : 'transparent', color: T.accentText, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, lineHeight: 1, transition: 'background 0.15s, border-color 0.15s' }}>{agree ? '✓' : ''}</span>
            <span style={{ fontFamily: F.body, fontSize: 12, letterSpacing: 0, textTransform: 'none', opacity: 0.75, lineHeight: 1.5 }}>
              {epzT('Я согласна получать письма от THE EPIZODE и принимаю')}{' '}
              <a href="/delivery/" style={{ color: 'inherit', textDecorationStyle: 'dotted' }}>{epzT('политику конфиденциальности')}</a>.
            </span>
          </label>
        </form>
      }
    </div>);

}

function arrowBtn(T) {
  return {
    width: 40, height: 40, borderRadius: 40,
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    background: 'transparent', color: T.text, border: `1px solid ${T.border}`,
    fontFamily: EPZ_FONTS.mono, fontSize: 15, cursor: 'pointer'
  };
}

// ─── Home carousel product card — nude-project style ─────────────────────────
function HomeProductCard({ a, T, grid }) {
  const F = EPZ_FONTS;
  useEpzLang();
  const ep = epzEpisode(a.episode);
  const img = epzArticleImage(a);
  const store = useEpzStore();
  const wished = store.wish.includes(a.wishId || a.id);
  const [added, setAdded] = React.useState(null);
  const [infoOpen, setInfoOpen] = React.useState(false);
  const href = a.href || `/product/?id=${a.id}`;
  const sizes = a.sizes || ['XS', 'S', 'M', 'L'];
  const priceLabel = a.priceLabel || epzArticlePriceLabel(a);

  function addSize(e, s) {
    e.preventDefault();e.stopPropagation();
    if (a.bundleParts) {
      a.bundleParts.forEach((p) => store.addToCart(p.id, { variant: p.variant || null, size: p.size || s, qty: 1 }));
    } else {
      const cartId = a.cartId || a.id;
      const variant = a.cartVariant !== undefined ? a.cartVariant : a.variants ? 'set' : null;
      store.addToCart(cartId, { variant, size: s, qty: 1 });
    }
    setAdded(s);
    setTimeout(() => setAdded(null), 1400);
  }
  // Комплекты с двумя размерными частями (пижамы): размер топа и брюк выбирается отдельно
  const setParts = React.useMemo(() => {
    if (!a.bundleParts) return null;
    const parts = a.bundleParts.map((p) => {
      const pa = (typeof EPZ_ARTICLES !== 'undefined' && EPZ_ARTICLES.find((x) => x.id === p.id)) || {};
      const label = p.variant === 'top' ? 'топ' : p.variant === 'bottom' ? 'брюки' : (pa.type || 'вещь').toLowerCase();
      const psizes = p.size ? [p.size] : pa.sizes || ['ONE SIZE'];
      return { ...p, label, psizes, fixed: psizes.length === 1 };
    });
    return parts.filter((p) => !p.fixed).length > 1 ? parts : null;
  }, [a]);
  const [selParts, setSelParts] = React.useState({});
  function addPartSize(e, i, s) {
    e.preventDefault(); e.stopPropagation();
    const next = { ...selParts, [i]: s };
    setSelParts(next);
    if (setParts.every((p, k) => p.fixed || next[k])) {
      setParts.forEach((p, k) => store.addToCart(p.id, { variant: p.variant || null, size: p.fixed ? p.psizes[0] : next[k], qty: 1 }));
      setAdded(setParts.map((p, k) => p.fixed ? null : `${epzT(p.label)} ${next[k]}`).filter(Boolean).join(' · '));
      setTimeout(() => { setAdded(null); setSelParts({}); }, 1600);
    }
  }
  function wishClick(e) {
    e.preventDefault(); e.stopPropagation();
    epzWishAdd(a);
  }

  return (
    <div className="home-card epz-rail-card" style={grid ? { width: '100%' } : {
      flex: '0 0 auto', width: 'clamp(260px, 28vw, 340px)', scrollSnapAlign: 'start'
    }}>
      <a href={href} style={{ display: 'block', color: 'inherit', textDecoration: 'none' }}>
        <div className="home-img-wrap is-photo">
          {img ?
          <>
              <div className="home-img home-img-contain" style={{ backgroundImage: `url(${img})`, backgroundPosition: 'center' }} />
              <div className={`home-img-alt${a.hoverCover ? '' : ' home-img-alt-contain'}`} style={{ backgroundImage: `url(${a.hoverImage || img})`, backgroundSize: a.hoverCover ? 'cover' : 'contain', backgroundPosition: a.hoverCover ? 'center 18%' : 'center' }} />
            </> :

          <EpzPlaceholder label={a.title} sub={ep.scene} ratio="auto" tone={T.placeholderTone}
          style={{ aspectRatio: 'auto', width: '100%', height: '100%' }} />
          }

          {/* предзаказ и ткань теперь в подписи под фото (вариант 04) */}

          {/* heart */}
          <button onClick={wishClick} aria-label={wished ? epzT('Убрать из избранного') : epzT('В избранное')} style={{
            position: 'absolute', top: 12, right: 12, zIndex: 3,
            border: 0, cursor: 'pointer', padding: 0,
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            background: 'transparent', color: EPZ_COLORS.burgundy, filter: 'drop-shadow(0 1px 2px rgba(255,255,255,0.5))'
          }}>
            <EpzIcon name={wished ? 'heart-filled' : 'heart'} size={19} />
          </button>

          {/* hover actions: sizes + cart */}
          {!a.isBundle &&
          <div className="home-actions" style={{
            position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 3,
            background: 'linear-gradient(to top, rgba(20,17,14,0.92), rgba(20,17,14,0))',
            padding: '28px 12px 12px', color: '#EFE7D6'
          }}>
            <div style={{ fontSize: 9, letterSpacing: '0.2em', textTransform: 'uppercase', opacity: 0.7, marginBottom: 8, textAlign: 'center' }}>
              {added ? `${epzT('добавлено')} · ${added}` : epzT('быстрый размер')}
            </div>
            <div style={{ display: 'flex', gap: 6, justifyContent: 'center', flexWrap: 'wrap' }}>
              {sizes.map((s) =>
              <button key={s} onClick={(e) => addSize(e, s)} style={{
                minWidth: 38, padding: '8px 6px', cursor: 'pointer',
                background: added === s ? '#EFE7D6' : 'transparent',
                color: added === s ? '#14110E' : '#EFE7D6',
                border: '1px solid rgba(239,231,214,0.55)',
                fontFamily: F.mono, fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase'
              }}>{s}</button>
              )}
            </div>
          </div>
          }
        </div>
      </a>

      {/* caption — swaps to sizes on hover */}
      <div style={{ position: 'relative', padding: '9px 16px 0' }}>
        {/* swap area: title/price ↔ sizes on hover */}
        <div style={{ position: 'relative', minHeight: 84 }}>
          <div className="home-meta">
            <a href={href} style={{ display: 'block', color: 'inherit', textDecoration: 'none' }}>
              {/* название — mono капсом */}
              <div style={{ fontFamily: F.mono, fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', lineHeight: 1.6, opacity: 0.85, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
                {epzT(a.homeTitle || a.short || a.title)}
              </div>
              {/* цена — сразу под названием */}
              <div className="home-price" style={{ marginTop: 3, fontFamily: F.mono, fontSize: 11, fontWeight: 400, letterSpacing: '0.08em', lineHeight: 1.3 }}>{priceLabel}</div>
              {/* предзаказ — под ценой, мелким бордовым */}
              {a.preorder &&
              <div style={{ marginTop: 7, fontFamily: F.mono, fontSize: 7.5, letterSpacing: '0.18em', textTransform: 'uppercase', color: T.accentInk }}>
                {epzT('предзаказ')}
              </div>
              }
            </a>
          </div>
          <div className="home-sizes">
            <div style={{ fontFamily: F.mono, fontSize: 9, letterSpacing: '0.2em', textTransform: 'uppercase', opacity: 0.6, marginBottom: 10, textAlign: 'center' }}>
              {added ? `${epzT('добавлено')} · ${added}` : epzT('выберите размер')}
            </div>
            {setParts && !added ? (
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
              {setParts.filter((p) => !p.fixed).map((p) => {
                const i = setParts.indexOf(p);
                return (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
                  <span style={{ fontFamily: F.mono, fontSize: 7.5, letterSpacing: '0.14em', textTransform: 'uppercase', opacity: 0.55, minWidth: 40, textAlign: 'right' }}>{epzT(p.label)}</span>
                  {p.psizes.map((s) => (
                    <button key={s} onClick={(e) => addPartSize(e, i, s)} style={{
                      padding: '6px 8px', cursor: 'pointer', lineHeight: 1,
                      background: selParts[i] === s ? T.accent : 'transparent',
                      color: selParts[i] === s ? T.accentText : T.text,
                      border: `1px solid ${selParts[i] === s ? T.accent : T.border}`,
                      fontFamily: F.mono, fontSize: 8.5, letterSpacing: '0.08em', textTransform: 'uppercase'
                    }}>{s}</button>
                  ))}
                </div>
                );
              })}
            </div>
            ) : !added ? (
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', justifyContent: 'center' }}>
              {sizes.map((s) =>
            <button key={s} onClick={(e) => addSize(e, s)} style={{
                minWidth: 42, padding: '12px 6px', cursor: 'pointer',
                background: added === s ? T.accent : 'transparent',
                color: added === s ? T.accentText : T.text,
                border: `1px solid ${added === s ? T.accent : T.border}`,
                fontFamily: F.mono, fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase'
              }}>{s}</button>
            )}
            </div>
            ) : null}
          </div>
        </div>

        {/* цитата убрана (вариант 04 — минимум шума) */}
      </div>
    </div>);

}

window.EpzHomepage = EpzHomepage;