// ============================================================
// YOUTUBE SHORTS — a row of 9:16 Shorts from the channel.
// Click-to-play "facade": we show the vertical thumbnail and only
// load the YouTube iframe when the viewer clicks (lighter than many
// live players, and lets the cards match the site).
//
// Like the X feed, this is all-or-nothing: the section renders only
// if ALL the listed videos verify as available (via YouTube's
// CORS-open oEmbed endpoint), and scrolls as a carousel when they
// don't all fit in a row.
//
// FIXED list — to change it, edit SHORT_URLS (paste each Short's URL).
// ============================================================

const SHORT_URLS = [
  'https://youtube.com/shorts/9wGzeEw5Sls',
  'https://youtube.com/shorts/AK2B9l4CLxk',
  'https://youtube.com/shorts/E6vJIc7GIUI',
  'https://www.youtube.com/shorts/mR0444bMsSE',
  'https://www.youtube.com/shorts/wsmfAPpDapc',
  'https://youtube.com/shorts/oMW81gFbA5k',
  'https://youtube.com/shorts/uuQjro8N_U8',
  'https://youtube.com/shorts/-7xz-XLXcWk',
  'https://www.youtube.com/shorts/5H8OxtxW29E',
  'https://www.youtube.com/shorts/kj-53_Q71-g',
  
];

const YT_CHANNEL_URL = 'https://www.youtube.com/@BeymannCapital';

const ytIdFromUrl = (url) => {
  const m = String(url).match(/(?:shorts\/|watch\?v=|youtu\.be\/|embed\/)([\w-]{11})/);
  return m ? m[1] : null;
};

const YTShorts = () => {
  const { t } = useI18n();
  const sectionRef = React.useRef(null);
  // 'loading' | 'ok' (all available) | 'empty' (one+ missing).
  const [status, setStatus] = React.useState('loading');

  React.useEffect(() => {
    let cancelled = false;
    const ids = SHORT_URLS.map(ytIdFromUrl);
    if (ids.length === 0 || ids.some((id) => !id)) { setStatus('empty'); return; }
    Promise.all(ids.map((id) =>
      fetch('https://www.youtube.com/oembed?format=json&url=' +
        encodeURIComponent('https://www.youtube.com/watch?v=' + id))
        .then((r) => r.ok)
        .catch(() => false)
    )).then((results) => {
      if (!cancelled) setStatus(results.every(Boolean) ? 'ok' : 'empty');
    });
    return () => { cancelled = true; };
  }, []);

  // The shared SectionHeader tags its title + quote with [data-reveal], which
  // start at opacity:0 until the page's reveal observer adds .is-revealed. That
  // observer runs once at page load, but this section mounts LATER (after the
  // async availability check), so its header would be missed and stay invisible.
  // Reveal this section's elements ourselves once it's in the DOM.
  React.useEffect(() => {
    if (status !== 'ok' || !sectionRef.current) return;
    const els = sectionRef.current.querySelectorAll('[data-reveal]');
    if (!('IntersectionObserver' in window)) {
      els.forEach((el) => el.classList.add('is-revealed'));
      return;
    }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) { e.target.classList.add('is-revealed'); io.unobserve(e.target); }
      });
    }, { rootMargin: '0px 0px -10% 0px', threshold: 0.12 });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, [status]);

  // All-or-nothing: don't render the section unless every video is available.
  if (status !== 'ok') return null;

  return (
    <section ref={sectionRef} className="yt-section" style={{ background: 'transparent', position: 'relative' }}>
      <SectionHeader eye={t('yt.eyebrow')} title={t('yt.title')} sub={t('yt.sub')} titleSize="clamp(28px,3.2vw,44px)" />
      <div>
        <Carousel itemWidth={240} gap={24} maxWidth={1200}>
          {SHORT_URLS.map((url, i) => <YTShort key={i} id={ytIdFromUrl(url)} />)}
        </Carousel>
      </div>
      <div style={{ maxWidth: 1200, margin: '48px auto 0', textAlign: 'left' }}>
        <a
          href={YT_CHANNEL_URL}
          target="_blank"
          rel="noopener noreferrer"
          style={{
            display: 'inline-flex', alignItems: 'center', gap: 10,
            color: 'var(--gold-400)', textDecoration: 'none',
            fontFamily: 'RH Phonic', fontSize: 13, fontWeight: 500,
            letterSpacing: '.16em', textTransform: 'uppercase',
            transition: 'gap 200ms var(--ease-out)',
          }}
          onMouseEnter={(e) => { e.currentTarget.style.gap = '14px'; }}
          onMouseLeave={(e) => { e.currentTarget.style.gap = '10px'; }}
        >
          {t('yt.cta')}
          <span aria-hidden="true">→</span>
        </a>
      </div>
    </section>
  );
};

const YTShort = ({ id }) => {
  const [playing, setPlaying] = React.useState(false);
  return (
    <div className="yt-short">
      {playing ? (
        <iframe
          src={'https://www.youtube-nocookie.com/embed/' + id + '?autoplay=1&playsinline=1&rel=0'}
          title="YouTube Shorts player"
          allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
          allowFullScreen
        />
      ) : (
        <button type="button" onClick={() => setPlaying(true)} aria-label="Play Short">
          <img src={'https://i.ytimg.com/vi/' + id + '/oardefault.jpg'} alt="" loading="lazy" />
          <span style={{
            position: 'absolute', inset: 0, display: 'flex',
            alignItems: 'center', justifyContent: 'center',
          }}>
            <span style={{
              width: 46, height: 46, borderRadius: 999, background: 'rgba(0,0,0,.55)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              backdropFilter: 'blur(2px)',
            }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="#fff" aria-hidden="true">
                <path d="M8 5v14l11-7z" />
              </svg>
            </span>
          </span>
        </button>
      )}
    </div>
  );
};

Object.assign(window, { YTShorts, YTShort });
