/* HERO - frame-perfect scroll video using pre-extracted JPG frames.
   Loads frames/ezgif-frame-XXX.jpg, downscales into an offscreen canvas, then
   paints on scroll. No mp4 decode, no browser seeking jitter. */
function Hero() {
  const sectionRef = React.useRef(null);
  const canvasRef = React.useRef(null);
  const framesRef = React.useRef([]);
  const [framesReady, setFramesReady] = React.useState(false);
  const [loadPct, setLoadPct] = React.useState(0);
  const progress = useSectionProgress(sectionRef);
  const isMobile = useIsMobile();
  // Capture isMobile once for loader (don't re-decode if user resizes mid-scroll)
  const isMobileInitial = React.useRef(isMobile);

  // If we're rendered inside the SiteShowcase iframe, skip frame loading entirely.
  const inIframe = typeof window !== 'undefined' && window !== window.top;

  React.useEffect(() => {
    if (inIframe) {
      // Mark frames ready without loading anything so the loader overlay disappears.
      setFramesReady(true);
      return;
    }
    let cancelled = false;
    const TOTAL_AVAILABLE = 301;
    const STEP = isMobileInitial.current ? 6 : 2;
    const MAX_W = isMobileInitial.current ? 600 : 960;
    const folder = isMobileInitial.current ? 'frames_v1_mobile' : 'frames_v1';
    const indices = [];
    for (let i = 1; i <= TOTAL_AVAILABLE; i += STEP) indices.push(i);

    (async () => {
      const frames = new Array(indices.length);
      let loaded = 0;

      const loadOne = (i, idx) => new Promise((resolve) => {
        const img = new Image();
        img.decoding = 'async';
        img.onload = () => {
          const scale = Math.min(1, MAX_W / img.naturalWidth);
          const W = Math.round(img.naturalWidth * scale);
          const H = Math.round(img.naturalHeight * scale);
          const c = document.createElement('canvas');
          c.width = W; c.height = H;
          c.getContext('2d').drawImage(img, 0, 0, W, H);
          frames[idx] = c;
          loaded++;
          if (!cancelled) setLoadPct(loaded / indices.length);
          resolve();
        };
        img.onerror = () => { loaded++; if (!cancelled) setLoadPct(loaded / indices.length); resolve(); };
        img.src = `${folder}/frame_${String(i).padStart(4, '0')}.jpg`;
      });

      const CONCURRENCY = 8;
      let cursor = 0;
      const workers = Array.from({ length: CONCURRENCY }, async () => {
        while (cursor < indices.length && !cancelled) {
          const idx = cursor++;
          await loadOne(indices[idx], idx);
        }
      });
      await Promise.all(workers);

      framesRef.current = frames.filter(Boolean);
      if (!cancelled) setFramesReady(true);
    })();

    return () => { cancelled = true; };
  }, []);

  const progressRef = React.useRef(0);
  React.useEffect(() => { progressRef.current = progress; }, [progress]);

  const smoothedRef = React.useRef(0);

  React.useEffect(() => {
    if (!framesReady) return;
    const cv = canvasRef.current;
    if (!cv) return;
    const ctx = cv.getContext('2d');
    let raf = 0;
    let lastIdx = -1;

    const resize = () => {
      const dpr = Math.min(window.devicePixelRatio || 1, 2);
      cv.width = Math.round(window.innerWidth * dpr);
      cv.height = Math.round(window.innerHeight * dpr);
      cv.style.width = window.innerWidth + 'px';
      cv.style.height = window.innerHeight + 'px';
      lastIdx = -1; // force redraw after resize
    };

    const paint = () => {
      const total = framesRef.current.length;
      if (!total) return;

      // Critically-damped easing toward target progress: smooths wheel/trackpad jitter
      const target = progressRef.current;
      const diff = target - smoothedRef.current;
      // snap on tiny diffs to avoid endless micro-animation
      smoothedRef.current = Math.abs(diff) < 0.0002 ? target : smoothedRef.current + diff * 0.16;
      const p = smoothedRef.current;

      const idx = clamp(Math.round(p * (total - 1)), 0, total - 1);
      if (idx === lastIdx) {
        // still update transform/filter below, but skip redrawing same frame
      } else {
        const cw = cv.width, ch = cv.height;
        const fr = framesRef.current[idx];
        if (!fr) return;
        const fw = fr.width, fh = fr.height;
        const scale = Math.max(cw / fw, ch / fh);
        const dw = fw * scale, dh = fh * scale;
        const dx = (cw - dw) / 2, dy = (ch - dh) / 2;
        // 'copy' fully replaces the destination - no ghosting from prior frames
        ctx.globalCompositeOperation = 'copy';
        ctx.drawImage(fr, dx, dy, dw, dh);
        ctx.globalCompositeOperation = 'source-over';
        lastIdx = idx;
      }

      // Drive canvas transform/filter directly from smoothed p (bypasses React render/CSS transition fight)
      const sc = lerp(1.05, 1.0, clamp(p * 3, 0, 1));
      cv.style.transform = `scale(${sc})`;
      cv.style.filter = `saturate(${lerp(1.05, 1.15, p)}) contrast(1.06)`;
    };

    const tick = () => { paint(); raf = requestAnimationFrame(tick); };
    resize();
    window.addEventListener('resize', resize);
    raf = requestAnimationFrame(tick);
    return () => { cancelAnimationFrame(raf); window.removeEventListener('resize', resize); };
  }, [framesReady]);

  const titleOpacity = clamp(1 - progress * 4.5, 0, 1);
  const titleY = -progress * 180;
  const titleScale = lerp(1, 1.08, clamp(progress * 3, 0, 1));
  const kickerOpacity = clamp(1 - (progress - 0.92) * 12, 0, 1);
  const ctaShow = smoothstep(0.92, 0.99, progress);
  const ctaY = lerp(40, 0, ctaShow);

  const cards = [
    { tag: 'TXT01', t: 'לא צריך לדעת לתכנת.', s: 'אתה מתאר מה אתה רוצה - קלוד בונה את הכל.' },
    { tag: 'TXT02', t: '17 פרקים. 94 שיעורים.', s: 'מהיסודות ועד מערכת מלאה שעולה לאוויר.' },
    { tag: 'TXT03', t: 'לא תיאוריה.', s: 'CRM, סוכן AI, מפעל תוכן, פרסומות - דברים אמיתיים שמכניסים כסף.' },
    { tag: 'TXT04', t: 'גם שיווק, גם בנייה.', s: 'איתור נישה, מחקר מתחרים, פרסומות, השקה - חבילה אחת שלמה.' },
  ];
  const window0 = 0.22, window1 = 0.90;
  const span = window1 - window0;
  const each = span / cards.length;

  return (
    <section ref={sectionRef} style={{position:'relative', height: inIframe ? '120vh' : (isMobile ? '560vh' : '780vh'), background:'#0A0907'}}>
      <div style={{position:'sticky', top:0, height:'100vh', overflow:'hidden'}}>
        <canvas
          ref={canvasRef}
          style={{position:'absolute', inset:0, width:'100%', height:'100%', display:'block', willChange:'transform, filter'}}
        />

        {!framesReady && (
          <div style={{position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center', flexDirection:'column', gap:20, background:'#0A0907', zIndex:20}}>
            <div style={{fontSize:11, letterSpacing:'0.22em', textTransform:'uppercase', color:'#EEB332', fontFamily:'Open Sans, sans-serif', fontWeight:600}}>טוען חוויה</div>
            <div style={{width:240, height:2, background:'rgba(245,242,237,0.08)', borderRadius:500, overflow:'hidden'}}>
              <div style={{height:'100%', width:`${loadPct*100}%`, background:'linear-gradient(90deg, #DD9933, #FFD777)', boxShadow:'0 0 12px #EEB332', transition:'width 120ms linear'}} />
            </div>
            <div style={{fontSize:12, color:'rgba(245,242,237,0.45)', fontFamily:'monospace'}}>{Math.round(loadPct*100)}%</div>
          </div>
        )}

        <div style={{position:'absolute', inset:0, pointerEvents:'none',
          background:`radial-gradient(ellipse at 50% 50%, rgba(238,179,50,${lerp(0.14, 0.05, progress)}) 0%, rgba(0,0,0,0) 60%)`}} />

        <div style={{position:'absolute', inset:0, pointerEvents:'none',
          background:`linear-gradient(180deg, rgba(10,9,7,${lerp(0.12, 0.22, smoothstep(0.30, 0.55, progress))}) 0%, rgba(10,9,7,${lerp(0.22, 0.38, smoothstep(0.30, 0.55, progress))}) 100%)`}} />

        <div style={{position:'absolute', inset:0, pointerEvents:'none',
          background:'radial-gradient(circle at 50% 50%, rgba(0,0,0,0) 60%, rgba(0,0,0,0.35) 100%)'}} />

        <div style={{position:'absolute', top: isMobile ? 84 : 32, left:0, right:0, display:'flex', justifyContent:'center', padding:'0 12px', pointerEvents:'none', opacity: kickerOpacity, transition:'opacity 200ms'}}>
          <div dir="rtl" style={{display:'flex', alignItems:'center', gap: isMobile ? 8 : 12, padding: isMobile ? '5px 12px' : '8px 18px', border:'1px solid rgba(238,179,50,0.45)', borderRadius:500, fontSize: isMobile ? 10 : 12, letterSpacing: isMobile ? '0.10em' : '0.14em', textTransform:'uppercase', color:'#EEB332', background:'rgba(10,9,7,0.4)', backdropFilter:'blur(8px)', WebkitBackdropFilter:'blur(8px)', whiteSpace:'nowrap'}}>
            <span style={{width: isMobile ? 5 : 6, height: isMobile ? 5 : 6, background:'#EEB332', borderRadius:'50%', boxShadow:'0 0 12px #EEB332'}} />
            <span>הקורס המלא בעברית · <bdi>AI</bdi> ו-<bdi>Claude Code</bdi> · <bdi>2026</bdi></span>
          </div>
        </div>

        <div style={{position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center', flexDirection:'column', padding:'0 24px', textAlign:'center',
          transform:`translateY(${titleY}px) scale(${titleScale})`,
          opacity: titleOpacity, transition:'opacity 100ms linear', pointerEvents:'none'}}>
          <h1 style={{fontFamily:'Open Sans, sans-serif', fontWeight:900, fontSize:'clamp(64px, 11vw, 184px)', lineHeight:0.92, letterSpacing:'-0.025em', margin:0, color:'#F5F2ED', textShadow:'0 4px 60px rgba(0,0,0,0.6)'}}>
            <span style={{display:'block'}}>אתה חושב.</span>
            <span style={{display:'block', background:'linear-gradient(180deg, #FFD777 0%, #EEB332 50%, #B27418 100%)', WebkitBackgroundClip:'text', WebkitTextFillColor:'transparent', backgroundClip:'text'}}>
              Claude מבצע.
            </span>
          </h1>
          <p style={{marginTop: isMobile ? 16 : 24, fontSize: isMobile ? 15 : 'clamp(18px, 1.6vw, 24px)', color:'rgba(245,242,237,0.82)', maxWidth:680, fontWeight:300, lineHeight:1.5, padding: isMobile ? '0 8px' : 0}}>
            94 שיעורים בעברית עם <b style={{color:'#EEB332', fontWeight:600}}>Claude Code</b>. מערכות אמיתיות, לקוחות משלמים - בלי לכתוב שורת קוד אחת.
          </p>
        </div>

        {cards.map((c, i) => {
          const start = window0 + i * each;
          const end = start + each;
          const inP = smoothstep(start, start + each * 0.06, progress);
          const outP = 1 - smoothstep(end - each * 0.06, end, progress);
          const visible = Math.min(inP, outP);
          const dy = lerp(14, 0, inP) + lerp(0, -14, 1 - outP);
          const blurAmt = lerp(4, 0, inP) + lerp(0, 4, 1 - outP);

          return (
            <div key={c.tag} style={{
              position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center',
              padding:'0 24px', pointerEvents:'none',
              opacity: visible,
              transform: `translateY(${dy}px)`,
              filter: blurAmt > 0.1 ? `blur(${blurAmt}px)` : 'none',
              transition: 'opacity 180ms linear, transform 180ms linear, filter 180ms linear',
            }}>
              <FloatingCard tag={c.tag} title={c.t} sub={c.s} idx={i} />
            </div>
          );
        })}

        <div style={{position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center', padding:'0 24px',
          transform:`translateY(${ctaY}px)`, opacity: ctaShow, pointerEvents: ctaShow > 0.5 ? 'auto' : 'none'}}>
          <div style={{textAlign:'center'}}>
            <div style={{fontFamily:'Open Sans', fontWeight:800, fontSize: isMobile ? 'clamp(28px, 7vw, 40px)' : 'clamp(40px, 5vw, 72px)', lineHeight:1.1, color:'#F5F2ED', marginBottom: isMobile ? 18 : 24, textShadow:'0 4px 40px rgba(0,0,0,0.6)'}}>
              מוכנים להתחיל לבנות?
            </div>
            <button onClick={() => scrollToSection('pricing')} style={{background:'transparent', color:'#EEB332', border:'2px solid #DD9933', borderRadius:500, padding: isMobile ? '14px 30px' : '18px 48px', fontSize: isMobile ? 15 : 18, fontFamily:'Open Sans, sans-serif', fontWeight:600, cursor:'pointer', boxShadow:'0 0 32px 4px rgba(238,179,50,0.45)'}}>
              הירשם לקורס &larr;
            </button>
          </div>
        </div>

        <div style={{position:'absolute', bottom:36, left:0, right:0, display:'flex', justifyContent:'center', pointerEvents:'none', opacity: clamp(1 - progress * 12, 0, 1)}}>
          <div style={{display:'flex', flexDirection:'column', alignItems:'center', gap:14}}>
            <div style={{fontSize:11, letterSpacing:'0.2em', textTransform:'uppercase', color:'rgba(245,242,237,0.55)'}}>גלול להמשך</div>
            <div style={{width:1, height:48, background:'linear-gradient(180deg, rgba(238,179,50,0.8), rgba(238,179,50,0))'}} />
          </div>
        </div>

        <div style={{position:'absolute', bottom:0, left:0, right:0, height:2, background:'rgba(245,242,237,0.06)'}}>
          <div style={{height:'100%', width:`${progress*100}%`, background:'linear-gradient(90deg, #DD9933, #EEB332, #FFD777)', boxShadow:'0 0 12px #EEB332', transition:'width 80ms linear'}} />
        </div>
      </div>
    </section>
  );
}

function FloatingCard({ tag, title, sub, idx }) {
  const isMobile = useIsMobile();
  const desktopOffsets = [
    {top:'18%', left:'10%', right:'auto', maxW:520, align:'right'},
    {top:'22%', left:'auto', right:'8%', maxW:540, align:'right'},
    {top:'58%', left:'12%', right:'auto', maxW:500, align:'right'},
    {top:'52%', left:'auto', right:'10%', maxW:560, align:'right'},
  ];
  // Mobile: all cards centered horizontally, with slight vertical offset for visual variety
  const mobileOffsets = [
    {top:'34%', left:16, right:16, align:'right'},
    {top:'38%', left:16, right:16, align:'right'},
    {top:'46%', left:16, right:16, align:'right'},
    {top:'42%', left:16, right:16, align:'right'},
  ];
  const offsets = isMobile ? mobileOffsets : desktopOffsets;
  const o = offsets[idx % offsets.length];
  return (
    <div style={{
      position:'absolute', top:o.top, left:o.left, right:o.right,
      maxWidth: isMobile ? 'none' : o.maxW,
      width: isMobile ? 'auto' : 'min(86vw, 560px)',
      background:'rgba(19,17,15,0.55)',
      border:'1px solid rgba(238,179,50,0.30)',
      borderRadius:5,
      padding: isMobile ? '18px 18px' : '28px 32px',
      backdropFilter:'blur(14px) saturate(1.2)',
      WebkitBackdropFilter:'blur(14px) saturate(1.2)',
      boxShadow:'0 30px 60px -20px rgba(0,0,0,0.5), 0 0 40px -12px rgba(238,179,50,0.25)',
      textAlign: o.align,
      direction:'rtl',
    }}>
      <div style={{fontSize: isMobile ? 10 : 11, letterSpacing:'0.22em', color:'#EEB332', fontFamily:'monospace', marginBottom: isMobile ? 8 : 14}}>
        - {tag}
      </div>
      <div style={{fontFamily:'Open Sans', fontWeight:900, fontSize: isMobile ? 'clamp(22px, 6.5vw, 32px)' : 'clamp(28px, 3.4vw, 44px)', lineHeight:1.15, letterSpacing:'-0.02em', color:'#F5F2ED', marginBottom: isMobile ? 6 : 10}}>
        {title}
      </div>
      <div style={{fontSize: isMobile ? 14 : 'clamp(15px, 1.2vw, 18px)', lineHeight:1.5, color:'rgba(245,242,237,0.85)'}}>
        {sub}
      </div>
    </div>
  );
}

window.Hero = Hero;
