// ============================================================
// VIDEO LESSONS. Longer-form trading tutorials, shown as a
// featured 16:9 player below The Playbook on the homepage.
//
// FIXED list. To add a lesson, add an entry here (id + titleKey)
// and a matching title string in i18n.jsx for each language.
// The first entry is rendered as the featured video.
// ============================================================

const VIDEO_LESSONS = [
  { id: 'df_n58z792M', titleKey: 'lessons.v1.title' },
  { id: 'FfSCmJfY6wo', titleKey: 'lessons.v2.title' },
  { id: 'wQW9BpU8r-I', titleKey: 'lessons.v3.title' },
  { id: 'w30UGwRiofI', titleKey: 'lessons.v4.title' },
];

const VideoLesson = ({ id, title }) => {
  const [playing, setPlaying] = React.useState(false);
  return (
    <figure style={{ margin: 0, flex: 1, minWidth: 0 }}>
      <div style={{
        position: 'relative', width: '100%', aspectRatio: '16 / 9',
        borderRadius: 12, overflow: 'hidden',
        border: '1px solid var(--border)', background: 'var(--ink-2)',
      }}>
        {playing ? (
          <iframe
            src={'https://www.youtube-nocookie.com/embed/' + id + '?autoplay=1&playsinline=1&rel=0'}
            title={title}
            allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
            allowFullScreen
            style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', border: 0 }}
          />
        ) : (
          <button
            type="button"
            onClick={() => setPlaying(true)}
            aria-label={'Play video: ' + title}
            style={{
              position: 'absolute', inset: 0, width: '100%', height: '100%',
              padding: 0, border: 0, cursor: 'pointer', background: 'transparent',
            }}
          >
            <img
              src={'https://i.ytimg.com/vi/' + id + '/maxresdefault.jpg'}
              alt=""
              loading="lazy"
              style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
            />
            <span style={{
              position: 'absolute', inset: 0, display: 'flex',
              alignItems: 'center', justifyContent: 'center',
            }}>
              <span style={{
                width: 72, height: 72, borderRadius: 999, background: 'rgba(0,0,0,.55)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                backdropFilter: 'blur(2px)',
              }}>
                <svg width="30" height="30" viewBox="0 0 24 24" fill="#fff" aria-hidden="true">
                  <path d="M8 5v14l11-7z" />
                </svg>
              </span>
            </span>
          </button>
        )}
      </div>
      <figcaption style={{
        marginTop: 16, fontFamily: 'RH Phonic', fontWeight: 700,
        fontSize: 18, lineHeight: 1.3, color: 'var(--fg)',
      }}>{title}</figcaption>
    </figure>
  );
};

const VideoLessons = () => {
  const { t } = useI18n();
  const scrollerRef = React.useRef(null);
  const [arrows, setArrows] = React.useState({ left: false, right: false });

  // Track scroll position to enable/disable the carousel arrows. The
  // carousel is manual; arrows only appear when the videos overflow the
  // available width (i.e. they can't all sit side by side).
  React.useEffect(() => {
    const el = scrollerRef.current;
    if (!el) return;
    const update = () => {
      const overflow = el.scrollWidth > el.clientWidth + 1;
      setArrows({
        left: overflow && el.scrollLeft > 4,
        right: overflow && el.scrollLeft + el.clientWidth < el.scrollWidth - 4,
      });
    };
    update();
    el.addEventListener('scroll', update, { passive: true });
    window.addEventListener('resize', update);
    return () => {
      el.removeEventListener('scroll', update);
      window.removeEventListener('resize', update);
    };
  }, []);

  const scrollByOne = (dir) => {
    const el = scrollerRef.current;
    if (!el) return;
    const item = el.querySelector('.blog-item');
    const step = item ? item.getBoundingClientRect().width + 32 : el.clientWidth * 0.4;
    el.scrollBy({ left: dir * step, behavior: 'smooth' });
  };

  if (VIDEO_LESSONS.length === 0) return null;

  return (
    <section style={{ padding: '32px 48px 64px', background: 'transparent', position: 'relative' }}>
      <SectionHeader
        eye={t('lessons.eyebrow')}
        title={t('lessons.title')}
        sub={t('lessons.sub')}
        titleSize="clamp(28px,3.2vw,44px)"
      />
      <div style={{ maxWidth: 1200, margin: '0 auto', position: 'relative' }}>
        <div
          ref={scrollerRef}
          className="blog-scroller"
          style={{
            display: 'flex', gap: 32,
            overflowX: 'auto',
            scrollSnapType: 'x proximity',
            scrollBehavior: 'smooth',
            paddingTop: 8, marginTop: -8, paddingBottom: 8,
          }}
        >
          {VIDEO_LESSONS.map((v) => (
            <div key={v.id} className="blog-item">
              <VideoLesson id={v.id} title={t(v.titleKey)} />
            </div>
          ))}
        </div>
        <CarouselArrow dir="left"  show={arrows.left}  onClick={() => scrollByOne(-1)} />
        <CarouselArrow dir="right" show={arrows.right} onClick={() => scrollByOne(1)} />
      </div>
      <div style={{ maxWidth: 1200, margin: '40px auto 0', textAlign: 'left' }}>
        <a
          href="https://www.youtube.com/@BeymannCapital?sub_confirmation=1"
          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('lessons.subscribe')}
          <span aria-hidden="true">→</span>
        </a>
      </div>
    </section>
  );
};

Object.assign(window, { VideoLessons, VideoLesson });
