// Floating portfolio strip — auto-loads whatever sits in assets/portfolio/.
// Drop a .mp4/.webm/.gif into that folder on Hostinger and it shows up here.
// list.php scans the folder (PHP runs on Hostinger). If it can't be reached
// (e.g. a local preview with no PHP) it falls back to the local files below.
const HERO_PORTFOLIO_DIR = 'assets/portfolio/';
const HERO_VIDEO_EXTS = ['mp4', 'webm', 'mov', 'm4v', 'ogv'];
const HERO_FALLBACK = [
  'assets/portfolio/1.mp4', 'assets/portfolio/2.mp4', 'assets/portfolio/3.mp4',
  'assets/portfolio/4.mp4', 'assets/portfolio/5.mp4', 'assets/portfolio/6.mp4',
  'assets/portfolio/7.mp4', 'assets/portfolio/8.mp4', 'assets/portfolio/9.mp4',
];
function heroIsVideo(src) {
  return HERO_VIDEO_EXTS.includes((src.split('.').pop() || '').toLowerCase());
}
// Lightweight poster (first-frame JPEG) for each video so the tile shows
// instantly while the heavy clip streams in behind it.
function heroPosterFor(src) {
  const i = src.lastIndexOf('/');
  const dir = src.slice(0, i + 1);
  const file = src.slice(i + 1).replace(/\.[^.]+$/, '');
  return dir + 'posters/' + file + '.jpg';
}

function Hero() {
  const avatars = [
    { src: 'assets/avatars/avatar-4.png' },
    { src: 'assets/avatars/avatar-2.png' },
    { src: 'assets/avatars/avatar-5.png' },
    { src: 'assets/avatars/avatar-1.png' },
    { src: 'assets/avatars/avatar-3.png' },
  ];

  const [portfolio, setPortfolio] = React.useState(HERO_FALLBACK);
  const marqueeRef = React.useRef(null);
  React.useEffect(() => {
    let cancelled = false;
    fetch(HERO_PORTFOLIO_DIR + 'list.php', { cache: 'no-cache' })
      .then((r) => (r.ok ? r.json() : Promise.reject()))
      .then((files) => {
        if (!cancelled && Array.isArray(files) && files.length) {
          setPortfolio(files.map((f) => HERO_PORTFOLIO_DIR + f));
        }
      })
      .catch(() => {});
    return () => { cancelled = true; };
  }, []);

  // Playback management. Two jobs:
  //  1. Only play tiles actually on-screen; pause the rest — so the browser
  //     isn't decoding all 18 looped videos at once (the cause of stutter).
  //  2. Self-heal: heavy clips sometimes fail to re-fire `loop` after a decode
  //     stall and freeze on the last frame. An `ended` handler force-replays
  //     them, so nothing stops after a single pass.
  React.useEffect(() => {
    const root = marqueeRef.current;
    if (!root) return;
    const vids = [...root.querySelectorAll('video')];

    // Safety net: if a clip ends without looping, restart it.
    const onEnded = (e) => {
      const v = e.currentTarget;
      try { v.currentTime = 0; } catch (_) {}
      v.play().catch(() => {});
    };
    vids.forEach((v) => v.addEventListener('ended', onEnded));

    const check = () => {
      const vw = window.innerWidth;
      const vh = window.innerHeight;
      vids.forEach((v) => {
        const r = v.getBoundingClientRect();
        // generous margins so tiles don't thrash play/pause at the edges
        const visible = r.right > -160 && r.left < vw + 160 && r.bottom > -80 && r.top < vh + 80;
        if (visible) {
          // lazy-load: only fetch the heavy clip once the tile nears the screen
          if (!v.src && v.dataset.src) v.src = v.dataset.src;
          if (v.paused) v.play().catch(() => {});
        } else if (!v.paused) {
          v.pause();
        }
      });
    };
    check();
    const id = setInterval(check, 400);
    return () => {
      clearInterval(id);
      vids.forEach((v) => v.removeEventListener('ended', onEnded));
    };
  }, [portfolio]);

  return (
    <section className="hero-sec" style={{
      position: 'relative',
      minHeight: '100vh',
      paddingTop: 110,
      paddingBottom: 0,
      overflow: 'hidden',
      isolation: 'isolate',
      display: 'flex',
      flexDirection: 'column',
    }}>
      {/* Horizon glow band — peak sits right at the marquee's top edge so it fades smoothly behind it */}
      <div aria-hidden className="hero-glow" style={{
        position: 'absolute', left: '50%', bottom: 300,
        transform: 'translateX(-50%)',
        width: '140%', height: 520,
        background: 'radial-gradient(ellipse 55% 100% at 50% 100%, rgba(225,238,255,0.7) 0%, rgba(110,167,255,0.45) 20%, rgba(74,142,255,0.2) 42%, transparent 68%)',
        filter: 'blur(40px)',
        zIndex: 0,
        pointerEvents: 'none',
      }} />

      <div className="container" style={{ position: 'relative', zIndex: 2, textAlign: 'center' }}>
        <div className="hero-proof hero-anim hero-anim-1" style={{
          display: 'inline-flex', alignItems: 'center', gap: 14,
          padding: '8px 18px 8px 8px',
          borderRadius: 999,
          background: 'rgba(255,255,255,0.03)',
          border: '1px solid rgba(255,255,255,0.08)',
          marginBottom: 28,
        }}>
          <div style={{ display: 'flex' }}>
            {avatars.map((a, i) => (
              <img key={i} src={a.src} alt="" style={{
                width: 26, height: 26, borderRadius: '50%',
                border: '1.5px solid #0a0e18',
                marginLeft: i === 0 ? 0 : -8,
                objectFit: 'cover',
                background: '#0a0e18',
                zIndex: 5 - i, position: 'relative',
              }} />
            ))}
          </div>
          <div style={{ textAlign: 'left' }}>
            <div style={{ fontSize: 12, color: 'var(--ink)', letterSpacing: '-0.005em' }}>Loved by 100+ clients worldwide</div>
            <div style={{ fontSize: 11, color: 'var(--ink-muted)' }}>Our clients speak for us</div>
          </div>
        </div>

        {/* Figma-style selection frame around the title + subtitle, with floating callout pills */}
        <div className="hero-frame" style={{
          position: 'relative',
          width: '100%',
          maxWidth: 1140,
          margin: '0 auto 36px',
          padding: '56px 64px 60px',
        }}>
          {/* Dashed bounding frame */}
          <div aria-hidden style={{
            position: 'absolute', inset: 0,
            border: '1px dashed rgba(255,255,255,0.14)',
            pointerEvents: 'none',
          }} />
          {/* Corner accent squares */}
          {[
            { top: -4, left: -4 },
            { top: -4, right: -4 },
            { bottom: -4, left: -4 },
            { bottom: -4, right: -4 },
          ].map((pos, i) => (
            <div key={i} aria-hidden style={{
              position: 'absolute', ...pos,
              width: 8, height: 8,
              background: 'var(--accent)',
              borderRadius: 1.5,
              boxShadow: '0 0 12px rgba(74,142,255,0.6)',
            }} />
          ))}

          {/* Floating callout pills — hidden below 1100px viewport to prevent edge clipping */}
          {/* Top-right: white "End-to-end" — hangs outside the right edge */}
          <div aria-hidden className="hero-pill hero-pill-1" style={{
            position: 'absolute',
            top: 36, right: -68,
            transform: 'rotate(5deg)',
            '--pill-tf-to': 'rotate(5deg)',
            '--pill-tf-from': 'rotate(5deg) translateY(-6px) scale(0.92)',
            padding: '7px 16px',
            background: '#ffffff',
            color: '#0a0e18',
            borderRadius: 999,
            fontSize: 13,
            fontWeight: 500,
            letterSpacing: '-0.005em',
            boxShadow: '0 10px 30px rgba(0,0,0,0.35), 0 0 0 1px rgba(255,255,255,0.06)',
            whiteSpace: 'nowrap',
            zIndex: 3,
          }}>
            End-to-end
            <span style={{
              position: 'absolute', left: -6, top: '50%',
              transform: 'translateY(-50%)',
              width: 0, height: 0,
              borderTop: '6px solid transparent',
              borderBottom: '6px solid transparent',
              borderRight: '7px solid #ffffff',
            }} />
          </div>

          {/* Mid-left: accent "Founder-led" — hangs outside the left edge */}
          <div aria-hidden className="hero-pill hero-pill-2" style={{
            position: 'absolute',
            top: '62%', left: -72,
            transform: 'translateY(-50%) rotate(-6deg)',
            '--pill-tf-to': 'translateY(-50%) rotate(-6deg)',
            '--pill-tf-from': 'translateY(-50%) rotate(-6deg) scale(0.92)',
            padding: '7px 16px',
            background: 'var(--accent)',
            color: '#fff',
            borderRadius: 999,
            fontSize: 13,
            fontWeight: 500,
            letterSpacing: '-0.005em',
            boxShadow: '0 10px 30px rgba(74,142,255,0.35), inset 0 1px 0 rgba(255,255,255,0.2)',
            whiteSpace: 'nowrap',
            zIndex: 3,
          }}>
            Founder-led
            <span style={{
              position: 'absolute', right: -6, top: '50%',
              transform: 'translateY(-50%)',
              width: 0, height: 0,
              borderTop: '6px solid transparent',
              borderBottom: '6px solid transparent',
              borderLeft: '7px solid var(--accent)',
            }} />
          </div>

          {/* Bottom-center: pale "Authority" — straddles the bottom frame edge */}
          <div aria-hidden className="hero-pill hero-pill-3" style={{
            position: 'absolute',
            bottom: -16, left: '50%',
            transform: 'translateX(-50%) rotate(-3deg)',
            '--pill-tf-to': 'translateX(-50%) rotate(-3deg)',
            '--pill-tf-from': 'translateX(-50%) rotate(-3deg) translateY(6px) scale(0.92)',
            padding: '7px 16px',
            background: '#cfe0ff',
            color: '#0a1530',
            borderRadius: 999,
            fontSize: 13,
            fontWeight: 500,
            letterSpacing: '-0.005em',
            boxShadow: '0 10px 30px rgba(207,224,255,0.25)',
            whiteSpace: 'nowrap',
            zIndex: 3,
          }}>
            Authority
            <span style={{
              position: 'absolute', left: '50%', top: -6,
              transform: 'translateX(-50%)',
              width: 0, height: 0,
              borderLeft: '6px solid transparent',
              borderRight: '6px solid transparent',
              borderBottom: '7px solid #cfe0ff',
            }} />
          </div>

          <h1 className="hero-anim hero-anim-2" style={{
            fontFamily: "'Geist', sans-serif",
            fontWeight: 500,
            fontSize: 'clamp(34px, 5.4vw, 76px)',
            letterSpacing: '-0.04em',
            lineHeight: 1.08,
            margin: 0,
            textAlign: 'center',
            position: 'relative',
            background: 'linear-gradient(180deg, #ffffff 0%, #ffffff 55%, #d8e3f5 100%)',
            WebkitBackgroundClip: 'text',
            WebkitTextFillColor: 'transparent',
            backgroundClip: 'text',
          }}>
            <span className="hero-line" style={{ display: 'block', whiteSpace: 'nowrap' }}>
              Generate 30 Days of Content
            </span>
            <span className="hero-line" style={{ display: 'block', whiteSpace: 'nowrap' }}>
              In just 2 hours
            </span>
          </h1>

          <p className="hero-anim hero-anim-3" style={{
            fontSize: 16,
            color: 'var(--ink-dim)',
            maxWidth: 680,
            margin: '22px auto 0',
            lineHeight: 1.55,
            textWrap: 'balance',
            position: 'relative',
            zIndex: 2,
          }}>
            One 2-hour shoot becomes 30 days of content that builds your authority<br className="hero-sub-br" />
            and attracts qualified leads — so you stay focused on closing.
          </p>
        </div>

        <a href="#book-a-call" className="btn btn-primary hero-anim hero-anim-4" style={{ marginTop: 4 }}>
          Book A Call <IconArrow size={12} />
        </a>
      </div>

      {/* Floating portfolio marquee — sits inside the hero, just below the CTA */}
      <div className="hero-anim hero-anim-5" style={{
        position: 'relative',
        marginTop: 44,
        zIndex: 2,
        overflow: 'hidden',
      }}>
        <div aria-hidden style={{
          position: 'absolute', top: 0, bottom: 0, left: 0, width: 180,
          background: 'linear-gradient(90deg, var(--bg) 0%, transparent 100%)',
          zIndex: 3, pointerEvents: 'none',
        }} />
        <div aria-hidden style={{
          position: 'absolute', top: 0, bottom: 0, right: 0, width: 180,
          background: 'linear-gradient(270deg, var(--bg) 0%, transparent 100%)',
          zIndex: 3, pointerEvents: 'none',
        }} />
        <div ref={marqueeRef} className="marquee" style={{ gap: 12, animationDuration: '60s' }}>
          {[...portfolio, ...portfolio].map((src, i) => (
            <div key={i} style={{
              flex: '0 0 auto',
              width: 168,
              aspectRatio: '9/16',
              borderRadius: 14,
              overflow: 'hidden',
              border: '1px solid var(--line)',
              background: '#0a0e18',
              boxShadow: '0 14px 40px rgba(0,0,0,0.5)',
            }}>
              {heroIsVideo(src) ? (
                <video data-src={src} poster={heroPosterFor(src)} muted loop playsInline preload="none"
                  style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
              ) : (
                <img src={src} loading="lazy" alt=""
                  style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
              )}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Hero });
