// THE EPIZODE — community gallery (UGC). Клиентки загружают свои фото в изделиях.
// Лента, листается стрелками (как «Новинки»), фото открывается на весь экран.
// Модерация: загруженное фото попадает в «на модерации» (localStorage), видно
// только загрузившему. На сайте показываются только одобренные фото (APPROVED).

function EpzCommunity({ T }) {
  const F = EPZ_FONTS;
  useEpzLang();

  // Approved photos shown to everyone (curated by the owner). Owner adds files to
  // assets/community/* and lists them here after moderation.
  // ДЕМО: пока стоят кадры из кампейна/студии — замените на реальные фото клиенток.
  const APPROVED = [
    { src: '/assets/art-003-campaign2.jpg', name: 'Демо', item: 'Платье-рубашка Хацумомо' },
    { src: '/assets/art-003-1.jpg', name: 'Демо', item: 'Платье-рубашка Хацумомо' },
    { src: '/assets/art-003-campaign.jpg', name: 'Демо', item: 'Платье-рубашка Хацумомо' },
    { src: '/assets/art-003-5.jpg', name: 'Демо', item: 'Платье-рубашка Хацумомо' },
    { src: '/assets/art-003-2.jpg', name: 'Демо', item: 'Платье-рубашка Хацумомо' },
    { src: '/assets/art-003-4.jpg', name: 'Демо', item: 'Платье-рубашка Хацумомо' },
  ];

  const [pending, setPending] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('epz-ugc-pending') || '[]'); } catch (e) { return []; }
  });
  const [toast, setToast] = React.useState(false);
  const [err, setErr] = React.useState(false);
  const [lightbox, setLightbox] = React.useState(null);
  const fileRef = React.useRef(null);
  const railRef = React.useRef(null);

  function onPick(e) {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    const isVideo = file.type.startsWith('video');
    if (isVideo) {
      // Reject clips longer than 10s.
      const url = URL.createObjectURL(file);
      const probe = document.createElement('video');
      probe.preload = 'metadata';
      probe.onloadedmetadata = () => {
        URL.revokeObjectURL(url);
        if (probe.duration > 11) {
          setErr(true); setTimeout(() => setErr(false), 4000); e.target.value = '';
          return;
        }
        readAndQueue(file, 'video');
      };
      probe.src = url;
    } else {
      readAndQueue(file, 'image');
    }
    e.target.value = '';
  }
  function readAndQueue(file, kind) {
    const reader = new FileReader();
    reader.onload = () => {
      const next = [...pending, { src: reader.result, kind, at: new Date().toISOString(), status: 'review' }];
      setPending(next);
      try { localStorage.setItem('epz-ugc-pending', JSON.stringify(next)); } catch (err) {}
      setToast(true);
      setTimeout(() => setToast(false), 3500);
    };
    reader.readAsDataURL(file);
  }
  function removePending(idx) {
    const next = pending.filter((_, i) => i !== idx);
    setPending(next);
    try { localStorage.setItem('epz-ugc-pending', JSON.stringify(next)); } catch (err) {}
  }
  const suppressClickRef = React.useRef(false); // kept (unused now)

  // Пришли с главной по «загрузить контент» (?upload=1) — ведём к плитке загрузки и подсвечиваем её
  const uploadIntent = React.useMemo(() => /[?&]upload=1/.test(location.search), []);
  React.useEffect(() => {
    if (!uploadIntent) return;
    const t = setTimeout(() => {
      const cell = document.getElementById('epz-upload-tile');
      if (cell) cell.scrollIntoView({ block: 'center', behavior: 'smooth' });
    }, 400);
    return () => clearTimeout(t);
  }, [uploadIntent]);

  // sticky-бар должен липнуть ПОД шапкой сайта (она тоже sticky)
  const [hdrH, setHdrH] = React.useState(84);
  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);
  }, []);

  // Лента как кампейн/инстаграм: ровная сетка 3 в ряд, все кадры одного размера,
  // вплотную. Демо-кадры повторяются — заменить реальными фото клиенток.
  const FEED = [...APPROVED, ...APPROVED.slice().reverse(), ...APPROVED];
  const galleryItems = [
    ...FEED.map((p) => ({ ...p, ratio: '3 / 4' })),
    { empty: true, ratio: '3 / 4' },
    { invite: true },
  ];

  return (
    <section style={{ borderTop: `1px solid ${T.border}` }}>
      <style>{`
        .ugc-masonry { display: grid; grid-template-columns: repeat(3, 1fr); gap: 0; padding: 0; }
        .ugc-cell { position: relative; overflow: hidden; }
        .ugc-cell img, .ugc-cell .ugc-bg, .ugc-cell video { transition: transform 0.6s ease; }
        .ugc-cell:hover .ugc-bg, .ugc-cell:hover video { transform: scale(1.04); }
        @media (max-width: 1100px) { .ugc-masonry { columns: 3; } }
        @media (max-width: 720px)  { .ugc-masonry { columns: 2; } }
        @media (max-width: 420px)  { .ugc-masonry { columns: 1; } }
        @keyframes epzUploadPulse { 0%, 100% { box-shadow: inset 0 0 0 1px transparent; } 50% { box-shadow: inset 0 0 0 2px var(--epz-acc); } }
      `}</style>

      {/* ── Sticky-бар: метка + кнопка загрузки. Прячется при скролле вниз ── */}
      <div style={{
        position: 'sticky', top: hdrH, zIndex: 40,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16,
        padding: '12px clamp(16px, 3vw, 40px)',
        background: T.bg, borderBottom: `1px solid ${T.border}`,
      }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 9, fontFamily: F.mono, fontSize: 10, letterSpacing: '0.24em', textTransform: 'uppercase', opacity: 0.85 }}>
          <span style={{ width: 7, height: 7, borderRadius: 7, background: T.accent, display: 'inline-block' }} />
          {epzT('THE EPIZODE вживую')}
        </div>
        <button onClick={() => fileRef.current && fileRef.current.click()} style={{
          display: 'inline-flex', alignItems: 'center', gap: 8, whiteSpace: 'nowrap',
          background: T.accent, color: T.accentText, border: 0, cursor: 'pointer', borderRadius: 40,
          padding: '10px 20px', fontFamily: F.mono, fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase'
        }}>＋ {epzT('загрузить контент')}</button>
      </div>
      <style>{`@keyframes epzLiveBlink { 0%, 55%, 100% { opacity: 1; } 65%, 90% { opacity: 0.2; } }`}</style>
      <input ref={fileRef} type="file" accept="image/*,video/*" onChange={onPick} style={{ display: 'none' }} />

      {/* ── Лента — фото вплотную, без воздуха ── */}
      <div className="ugc-masonry">
        {galleryItems.map((p, i) => (
          p.invite ? (
            /* приглашение — занимает две пустые клетки справа от «добавить фото» */
            <div key={i} style={{
              gridColumn: 'span 2', aspectRatio: '3 / 2', borderTop: `1px solid ${T.border}`, borderBottom: `1px solid ${T.border}`,
              display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 16,
              padding: '0 clamp(24px, 6vw, 90px)', textAlign: 'center',
            }}>
              <div style={{ fontFamily: F.display, fontSize: 'clamp(26px, 3.2vw, 42px)', fontStyle: 'italic', lineHeight: 1.15 }}>{epzT('Здесь не хватает вас')}</div>
              <div style={{ fontFamily: F.body, fontSize: 13, lineHeight: 1.65, opacity: 0.55, maxWidth: 400 }}>{epzT('Пришлите свой кадр в THE EPIZODE — после модерации он займёт это место')}</div>
            </div>
          ) : p.empty ? (
            <div key={i} id="epz-upload-tile" className="ugc-cell" onClick={() => fileRef.current && fileRef.current.click()} style={{
              aspectRatio: p.ratio, cursor: 'pointer', border: `1px solid ${T.border}`,
              display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 10,
              background: `repeating-linear-gradient(135deg, ${T.bgAlt} 0 12px, transparent 12px 13px)`,
              ...(uploadIntent ? { '--epz-acc': T.accent, animation: 'epzUploadPulse 1.5s ease-in-out 4' } : {}),
            }}>
              <span style={{ fontFamily: F.display, fontSize: 34, color: T.accentInk, lineHeight: 1 }}>+</span>
              <span style={{ fontFamily: F.mono, fontSize: 9, letterSpacing: '0.18em', textTransform: 'uppercase', opacity: 0.5 }}>{epzT('добавить фото')}</span>
            </div>
          ) : (
            <div key={i} className="ugc-cell" onClick={() => setLightbox(p)} style={{ cursor: 'zoom-in', background: '#241a18' }}>
              {p.kind === 'video' ?
                <video src={p.src} muted loop playsInline autoPlay style={{ display: 'block', width: '100%', aspectRatio: p.ratio, objectFit: 'cover' }} /> :
                <div className="ugc-bg" style={{ width: '100%', aspectRatio: p.ratio, backgroundImage: `url(${p.src})`, backgroundSize: 'cover', backgroundPosition: 'center' }} />
              }
              {p.kind === 'video' && <span style={{ position: 'absolute', top: 12, right: 12, fontFamily: F.mono, fontSize: 8, letterSpacing: '0.14em', textTransform: 'uppercase', color: '#EFE7D6', background: 'rgba(20,17,14,0.5)', padding: '3px 7px' }}>видео</span>}
            </div>
          )
        ))}
      </div>

      {/* Pending (visible only to this uploader, locally) */}
      {pending.length > 0 && (
        <div style={{ padding: '0 32px', marginTop: 40, marginBottom: 40 }}>
          <div style={{ fontFamily: F.mono, fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: T.accentInk, marginBottom: 16, display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ width: 6, height: 6, borderRadius: 6, background: T.accent, display: 'inline-block' }} />
            ваши фото на модерации · видите только вы
          </div>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            {pending.map((p, i) => (
              <div key={i} style={{ position: 'relative', width: 120, aspectRatio: '3/4', border: `1px solid ${T.border}`, overflow: 'hidden' }}>
                {p.kind === 'video' ?
                  <video src={p.src} muted loop playsInline autoPlay style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', filter: 'grayscale(0.3) brightness(0.85)' }} /> :
                  <div style={{ position: 'absolute', inset: 0, backgroundImage: `url(${p.src})`, backgroundSize: 'cover', backgroundPosition: 'center', filter: 'grayscale(0.3) brightness(0.85)' }} />
                }
                <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'flex-end', padding: 8 }}>
                  <span style={{ fontFamily: F.mono, fontSize: 8, letterSpacing: '0.14em', textTransform: 'uppercase', color: '#EFE7D6', background: 'rgba(20,17,14,0.55)', padding: '3px 6px' }}>на модерации{p.kind === 'video' ? ' · видео' : ''}</span>
                </div>
                <button onClick={() => removePending(i)} aria-label="Убрать" style={{ position: 'absolute', top: 6, right: 6, width: 22, height: 22, borderRadius: '50%', border: 0, background: 'rgba(20,17,14,0.6)', color: '#EFE7D6', cursor: 'pointer', fontFamily: F.mono, fontSize: 11 }}>×</button>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 14, fontFamily: F.body, fontSize: 12, lineHeight: 1.55, opacity: 0.55, maxWidth: 520 }}>
            Мы проверим фото и опубликуем его в галерее, если оно подходит. Загрузка приватная — на сайте фото появится только после одобрения.
          </div>
        </div>
      )}

      {/* Lightbox */}
      {lightbox && (
        <div onClick={() => setLightbox(null)} style={{ position: 'fixed', inset: 0, zIndex: 200, background: 'rgba(10,8,7,0.92)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'zoom-out', padding: 24 }}>
          {lightbox.kind === 'video' ?
            <video onClick={(e) => e.stopPropagation()} src={lightbox.src} controls autoPlay loop playsInline style={{ height: '88vh', maxWidth: '92vw', background: '#000' }} /> :
            <div onClick={(e) => e.stopPropagation()} style={{ height: '88vh', aspectRatio: '3/4', maxWidth: '92vw', backgroundColor: '#000', backgroundImage: `url(${lightbox.src})`, backgroundSize: 'contain', backgroundPosition: 'center', backgroundRepeat: 'no-repeat' }} />
          }
          <button onClick={() => setLightbox(null)} aria-label="Закрыть" style={{ position: 'fixed', top: 22, right: 26, background: 'transparent', color: '#EFE7D6', border: 0, cursor: 'pointer', fontFamily: F.mono, fontSize: 22 }}>✕</button>
        </div>
      )}

      {err && (
        <div style={{
          position: 'fixed', bottom: 28, left: '50%', transform: 'translateX(-50%)', zIndex: 200,
          background: '#3a1418', color: '#EFE7D6', padding: '14px 22px',
          fontFamily: F.mono, fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase',
          boxShadow: '0 18px 50px rgba(0,0,0,0.3)'
        }}>
          видео длиннее 10 сек — обрежьте и попробуйте снова
        </div>
      )}

      {toast && (
        <div style={{
          position: 'fixed', bottom: 28, left: '50%', transform: 'translateX(-50%)', zIndex: 200,
          background: T.btnPrimary, color: T.btnPrimaryFg, padding: '14px 22px',
          fontFamily: F.mono, fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase',
          boxShadow: '0 18px 50px rgba(0,0,0,0.3)'
        }}>
          фото отправлено на модерацию ✓
        </div>
      )}
    </section>
  );
}

// ─── Homepage teaser: full-bleed gallery + две прозрачные кнопки (без текста/баллов) ──
function EpzCommunityTeaser({ T }) {
  const F = EPZ_FONTS;
  useEpzLang();
  const IMG = ['/assets/art-003-campaign2.jpg', '/assets/art-003-campaign.jpg'];
  return (
    <section className="epz-live" style={{ position: 'relative', display: 'grid', gridTemplateColumns: '1.6fr 2fr', minHeight: 'clamp(480px, 52vw, 760px)', padding: '0 12px', background: T.bg }}>
      <style>{`
        @keyframes epzLiveBlink { 0%, 55%, 100% { opacity: 1; } 65%, 90% { opacity: 0.15; } }
        .epz-pill { transition: background 0.25s ease, color 0.25s ease, border-color 0.25s ease; }
        a.epz-pill:hover { background: #EFE7D6 !important; color: #14110E !important; border-color: #EFE7D6 !important; }
        a.epz-pill-fill:hover { background: #4E1117 !important; color: #EFE7D6 !important; }
        @media (max-width: 760px) {
          .epz-live { grid-template-columns: 1fr !important; }
          .epz-live > div:last-of-type { display: none !important; }
        }
      `}</style>
      {IMG.map((s, i) => (
        <div key={i} style={{ background: `#241a18 url(${s}) center 16% / cover no-repeat` }} />
      ))}
      {/* затемнение сверху и снизу для читаемости */}
      <div style={{ position: 'absolute', top: 0, bottom: 0, left: 12, right: 12, background: 'linear-gradient(to top, rgba(10,8,6,0.5) 0%, rgba(10,8,6,0) 32%, rgba(10,8,6,0) 72%, rgba(10,8,6,0.35) 100%)', pointerEvents: 'none' }} />
      {/* метка — как REC на главном герое */}
      <div style={{ position: 'absolute', left: 24, top: 24, color: '#EFE7D6' }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 9, fontFamily: F.mono, fontSize: 9, letterSpacing: '0.24em', textTransform: 'uppercase', opacity: 0.92 }}>
          <span style={{ width: 7, height: 7, borderRadius: 7, background: '#B3242F', display: 'inline-block', flexShrink: 0 }} />
          <span>THE EPIZODE: {epzT('реальные фотографии клиентов')}</span>
        </div>
      </div>
      {/* пояснение + кнопки — слева внизу */}
      <div style={{ position: 'absolute', left: 'clamp(24px, 3.5vw, 56px)', bottom: 'clamp(28px, 3.5vw, 56px)', maxWidth: 300 }}>
        <div style={{ color: '#EFE7D6', fontFamily: F.body, fontSize: 12.5, lineHeight: 1.6, opacity: 0.92, marginBottom: 16, textShadow: '0 1px 18px rgba(10,8,6,0.5)' }}>
          {epzT('Поделитесь своим образом, после модерации он появится здесь')}
        </div>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'nowrap' }}>
          <a href="/live/?upload=1" className="epz-pill epz-pill-fill" style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap', background: '#6E1A21', color: '#EFE7D6', textDecoration: 'none', borderRadius: 40, padding: '10px 20px', fontFamily: F.mono, fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase' }}>{epzT('загрузить контент')}</a>
          <a href="/live/" className="epz-pill" style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap', border: '1px solid rgba(239,231,214,0.6)', color: '#EFE7D6', textDecoration: 'none', borderRadius: 40, padding: '10px 18px', fontFamily: F.mono, fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase' }}>{epzT('смотреть') + ' →'}</a>
        </div>
      </div>
    </section>
  );
}

// ─── Dedicated page: лента реальных фото клиенток + загрузка ───────────────────
function EpzLivePage() {
  const F = EPZ_FONTS;
  useEpzLang();
  const [theme, setTheme, T] = useEpzTheme();
  return (
    <div style={{ width: '100%', background: T.bg, color: T.text, fontFamily: F.body, fontSize: 14, lineHeight: 1.5, WebkitFontSmoothing: 'antialiased', transition: 'background 0.3s ease, color 0.3s ease' }}>
      <EpzHeader theme={theme} setTheme={setTheme} T={T} current="live" />
      <EpzCrumbs T={T} items={[{ label: 'главная', href: '/' }, { label: 'the epizode вживую' }]} />
      <EpzCommunity T={T} />
      <EpzFooter T={T} />
    </div>
  );
}

window.EpzCommunity = EpzCommunity;
window.EpzCommunityTeaser = EpzCommunityTeaser;
window.EpzLivePage = EpzLivePage;
