// Main page composition: hero, video grids, instructor, schedule, FAQ, footer.

const {
  buildLots, computeLotState, fmtPrice, fmtDateBR, LotProgressBar, CTAProgress
} = window;

// ── Reusable bits ───────────────────────────────────────────────────────────

function AutoVideo({ src, poster, className = '', style, muted = true, loop = true, autoPlay = true, playsInline = true, controls = false, eager = false }) {
  const ref = React.useRef(null);
  const [inView, setInView] = React.useState(eager);

  // Observe viewport intersection — only load/play when near viewport
  React.useEffect(() => {
    if (eager) { setInView(true); return; }
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          setInView(e.isIntersecting);
        });
      },
      { rootMargin: '200px 0px', threshold: 0.01 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, [eager]);

  // Attach src + play only when in view; detach when out of view
  React.useEffect(() => {
    const video = ref.current;
    if (!video || !src) return;
    if (!inView) {
      // Free memory when not visible
      try { video.pause(); } catch(e) {}
      if (video.src) {
        video.removeAttribute('src');
        try { video.load(); } catch(e) {}
      }
      return;
    }
    const tryPlay = () => {
      if (!autoPlay) return;
      const p = video.play();
      if (p && p.catch) p.catch(() => {});
    };
    let cleanup;
    if (src.endsWith('.m3u8') || src.includes('.m3u8?')) {
      if (video.canPlayType('application/vnd.apple.mpegurl')) {
        video.src = src;
        video.addEventListener('loadedmetadata', tryPlay, { once: true });
      } else if (window.Hls && window.Hls.isSupported()) {
        const hls = new window.Hls({ capLevelToPlayerSize: true, autoStartLoad: true });
        hls.loadSource(src);
        hls.attachMedia(video);
        hls.on(window.Hls.Events.MANIFEST_PARSED, tryPlay);
        cleanup = () => hls.destroy();
      }
    } else {
      video.src = src;
      video.addEventListener('loadedmetadata', tryPlay, { once: true });
    }
    const delayed = setTimeout(tryPlay, 300);
    return () => {
      clearTimeout(delayed);
      if (cleanup) cleanup();
    };
  }, [src, autoPlay, inView]);

  return (
    <video
      ref={ref}
      className={className}
      style={style}
      poster={poster}
      muted={muted}
      loop={loop}
      autoPlay={autoPlay}
      playsInline={playsInline}
      controls={controls}
      preload="none"
    />
  );
}

// Stripe placeholder (for when we don't have a video yet)
function VideoPlaceholder({ label, ratio = '16 / 9' }) {
  return (
    <div className="vid-placeholder" style={{ aspectRatio: ratio }}>
      <div className="vid-placeholder-inner">
        <span className="mono">▶ {label}</span>
      </div>
    </div>
  );
}

// Enhanced CTA that can optionally show a CTAProgress underneath it.
function CTAButton({ children, href = '#', kind = 'primary', fullWidth = false, progress = null }) {
  return (
    <div className={`cta-wrap ${fullWidth ? 'cta-wrap-full' : ''}`}>
      <a href={href} className={`cta cta-${kind} ${fullWidth ? 'cta-full' : ''}`}>
        <span className="cta-label">{children}</span>
        <span className="cta-arrow" aria-hidden>
          <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
            <path d="M4 9h10M10 4l5 5-5 5" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </span>
      </a>
      {progress && <CTAProgress {...progress} />}
    </div>
  );
}

function Eyebrow({ index, children }) {
  return (
    <div className="eyebrow mono">
      <span className="eyebrow-idx">[{String(index).padStart(2, '0')}]</span>
      <span className="eyebrow-bar" aria-hidden />
      <span>{children}</span>
    </div>
  );
}

function Tag({ children }) {
  return <span className="tag mono">{children}</span>;
}

// ── Hero ────────────────────────────────────────────────────────────────────

function Hero({ schedule, now, checkoutUrl, config }) {
  const state = computeLotState(schedule, now);
  const active = state.activeIndex >= 0 ? state.lots[state.activeIndex] : state.lots[0];
  const activeUrl = (active && active.url) || checkoutUrl || '#';

  return (
    <section className="hero" data-screen-label="01 Hero">
      {/* Full-bleed background video */}
      <div className="hero-bg">
        <AutoVideo
          src={config.heroVideo}
          className="hero-bg-video"
          eager
        />
        <div className="hero-bg-scrim" />
        <div className="hero-bg-grid" aria-hidden />
      </div>

      <TopBar />

      <div className="hero-content">
        <div className="hero-eyebrow mono" data-reveal data-reveal-kind="fade">
          <span className="dot live" />
          <span>AO VIVO · ONLINE · {config.eventDates}</span>
        </div>

        <h1 className="hero-title" data-reveal data-reveal-kind="rise" style={{'--reveal-delay': '150ms'}}>
          <span className="hero-title-line">Workshop de</span>
          <span className="hero-title-line accent">animações com IA</span>
          <span className="hero-title-line">como profissional.</span>
        </h1>

        <p className="hero-sub" data-reveal data-reveal-kind="up" style={{'--reveal-delay': '450ms'}}>
          2 dias inteiros criando um projeto do zero de um dos tipos de vídeo
          de IA mais valorizados do mercado. Animação a nível profissional.
        </p>

        <div className="hero-cta-lot" data-reveal data-reveal-kind="up" style={{'--reveal-delay': '600ms'}}>
          <div className="hero-ctas">
            <CTAButton href={activeUrl} kind="primary">
              COMPRAR INGRESSO · LOTE {String(active.number).padStart(2, '0')}
            </CTAButton>
          </div>
          <LotProgressBar schedule={schedule} now={now} accent={config.accent} />
        </div>

        <div className="hero-stats mono" data-reveal data-reveal-kind="fade" style={{'--reveal-delay': '800ms'}}>
          <div><span className="big">11.376</span><span className="label">alunos nas edições anteriores</span></div>
          <div className="sep" />
          <div><span className="big">5ª</span><span className="label">edição do IA Maker</span></div>
          <div className="sep" />
          <div><span className="big">2 dias</span><span className="label">mão na massa, projeto do zero</span></div>
        </div>
      </div>
    </section>
  );
}

function TopBar() {
  return (
    <header className="topbar">
      <div className="topbar-logo mono">
        <span className="logo-mark">◎</span>
        <span>IA MAKER <span className="topbar-ed">/ 5ª EDIÇÃO</span></span>
      </div>
      <nav className="topbar-nav mono">
        <a href="#conteudo">conteúdo</a>
        <a href="#cronograma">cronograma</a>
        <a href="#instrutor">instrutor</a>
        <a href="#faq">faq</a>
      </nav>
      <div className="topbar-status mono">
        <span className="dot live" />
        <span>AO VIVO EM BREVE</span>
      </div>
    </header>
  );
}

Object.assign(window, { Hero, TopBar, AutoVideo, VideoPlaceholder, CTAButton, Eyebrow, Tag });
