/* CourseCinema — full-screen GSAP+Framer scrub landing section (used on course.html + home) */
const CRS_MODULE_ITEMS = [
  { icon: 'circle-dot', label: 'קומבינציה מכנית' },
  { icon: 'cpu', label: 'דיגיטלי וביומטרי' },
  { icon: 'volume-x', label: 'פריצה שקטה בשטח' },
  { icon: 'crosshair', label: 'קידוח מדויק' },
  { icon: 'shield-check', label: 'כספות בתקן' },
  { icon: 'briefcase', label: 'הקמת עסק' },
];
const CRS_OUTCOMES = [
  { icon: 'award', b: 'תעודת הסמכה', d: 'תעודת סיום קורס טכנאי כספות — חתומה ומוכרת בענף.' },
  { icon: 'wrench', b: 'ערכת כלים בסיסית', d: 'יוצאים מהקורס עם הכלים הנדרשים לקריאה הראשונה בשטח.' },
  { icon: 'users', b: 'ליווי אישי אחרי הקורס', d: 'זמינות בוואטסאפ לשאלות מהשטח גם אחרי סיום ההכשרה.' },
  { icon: 'phone-call', b: 'הפניית לקוחות ראשונים', d: 'עומס עבודה שחורג מהיכולת שלי — מועבר לבוגרי הקורס.' },
];
const CRS_FINALE_STATS = [{ to: 10, suffix: '+', label: 'שנות ניסיון' }, { to: 6, suffix: '', label: 'מודולים' }, { to: 100, suffix: '%', label: 'מעשי' }];
const CRS_WA = 'https://wa.me/972543312367?text=%D7%94%D7%99%D7%99%20%D7%A9%D7%9C%D7%95%D7%9D%2C%20%D7%90%D7%A9%D7%9E%D7%97%20%D7%9C%D7%A4%D7%A8%D7%98%D7%99%D7%9D%20%D7%A2%D7%9C%20%D7%94%D7%A7%D7%95%D7%A8%D7%A1';
const CIN = [
  { num: '01', rail: 'ההכשרה', icon: 'graduation-cap', kicker: 'ההכשרה', side: 'r',
    title: 'קורס אחד. מקצוע שלם.', accent: [2, 3],
    desc: 'הכשרה מעשית לפריצת כספות — למנעולנים, לטכנאים ולמי שרוצה להיכנס לנישה המבוקשת והרווחית ביותר בענף. קבוצה קטנה, ליווי אישי של שלום.',
    chips: [{ icon: 'clock-3', label: '10+ שנות ניסיון בשטח' }, { icon: 'users', label: 'קבוצה קטנה בלבד' }, { icon: 'hand', label: 'למידה דרך הידיים' }] },
  { num: '02', rail: 'השיטה', icon: 'layers', kicker: 'שישה מודולים', side: 'l', blur: true,
    title: 'מהחוגה ועד המנעול הביומטרי', accent: [3],
    desc: 'כל שיטות הפתיחה שקיימות בשוק, בלי להרוס ובלי לשבור: מניפולציה של קומבינציה מכנית, מנעולים דיגיטליים, עקיפה שקטה וקידוח מדויק.',
    chips: CRS_MODULE_ITEMS },
  { num: '03', rail: 'התרגול', icon: 'wrench', kicker: 'תרגול מעשי', side: 'r',
    title: 'ידיים על הכספת מהשיעור הראשון', accent: [0],
    desc: 'כל מודול נפתח בהסבר קצר וממשיך ישר לעבודה על כספות אמיתיות. טועים, מתקנים, פותחים — עד שהידיים כבר יודעות לבד.',
    chips: [{ icon: 'crosshair', label: 'תרגול צמוד על כל כספת' }, { icon: 'user-check', label: 'ליווי אישי בכל שלב' }, { icon: 'package', label: 'כלים מקצועיים כלולים' }] },
  { num: '04', rail: 'התוצאה', icon: 'briefcase', kicker: 'מה יוצא איתך', side: 'l',
    title: 'יוצאים מוכנים לקריאה הראשונה', accent: [2, 3],
    desc: 'לא רק ידע — תיק שלם ליציאה לשטח: תעודה חתומה, ערכת כלים, ליווי אחרי הקורס והפניית לקוחות ראשונים.',
    cards: CRS_OUTCOMES },
  { num: '05', rail: 'ההרשמה', icon: 'key-round', kicker: 'ההרשמה פתוחה', side: 'c',
    title: 'הכספת פתוחה. עכשיו תורכם.', accent: [2, 3],
    desc: 'המקומות בכל מחזור מוגבלים, כדי שכל אחד יקבל זמן אמיתי על הכספות. השאירו פרטים למטה — או כתבו לי ישירות בוואטסאפ.',
    finale: true },
];
const CIN_T = [0, .21, .42, .63, .84, 1];
const CIN_V = [.012, .228, .476, .664, .862, .985];

function CinTitle({ c, W }) {
  const words = c.title.split(' ');
  return (
    <h3 className="cin-title">
      {words.map((w, i) => <React.Fragment key={i}><W className={'w' + (c.accent.includes(i) ? ' accent' : '')} variants={CIN_VARS.word}>{w}</W>{i < words.length - 1 ? ' ' : ''}</React.Fragment>)}
    </h3>
  );
}

const CIN_VARS = {
  wrap: { hidden: {}, show: { transition: { staggerChildren: .06, delayChildren: .04 } }, exit: { transition: { staggerChildren: .022, staggerDirection: -1 } } },
  up: { hidden: { opacity: 0, y: 46, rotateX: -35, filter: 'blur(10px)' }, show: { opacity: 1, y: 0, rotateX: 0, filter: 'blur(0px)', transition: { type: 'spring', stiffness: 190, damping: 24 } }, exit: { opacity: 0, y: -30, filter: 'blur(8px)', transition: { duration: .28, ease: 'easeIn' } } },
  word: { hidden: { opacity: 0, y: '0.9em', rotateX: -70 }, show: { opacity: 1, y: 0, rotateX: 0, transition: { type: 'spring', stiffness: 240, damping: 26 } }, exit: { opacity: 0, y: '-0.5em', transition: { duration: .22 } } },
  chip: { hidden: { opacity: 0, y: 26, scale: .85, rotateZ: -2 }, show: { opacity: 1, y: 0, scale: 1, rotateZ: 0, transition: { type: 'spring', stiffness: 260, damping: 22 } }, exit: { opacity: 0, scale: .9, transition: { duration: .2 } } },
  ghost: { hidden: { opacity: 0 }, show: { opacity: 1, transition: { duration: .9 } }, exit: { opacity: 0, transition: { duration: .25 } } },
};

function CinCopy({ idx, FM, enrollHref }) {
  const c = CIN[idx];
  const { Button } = window.DS;
  const statRefs = React.useRef([]);
  const T = React.useMemo(() => {
    if (FM) return { div: FM.motion.div, p: FM.motion.p, span: FM.motion.span };
    const plain = (tag) => ({ children, className, style }) => React.createElement(tag, { className, style }, children);
    return { div: plain('div'), p: plain('p'), span: plain('span') };
  }, [FM]);
  React.useEffect(() => {
    if (!c.finale) return;
    const t = setTimeout(() => {
      CRS_FINALE_STATS.forEach((s, i) => {
        const el = statRefs.current[i];
        if (!el) return;
        if (window.gsap) { const o = { v: 0 }; gsap.to(o, { v: s.to, duration: 1.4, ease: 'power2.out', onUpdate: () => { el.textContent = Math.round(o.v); } }); }
        else el.textContent = s.to;
      });
    }, 450);
    return () => clearTimeout(t);
  }, [c]);
  return (
    <div className={'cin-copy side-' + c.side + (c.blur ? ' has-blur' : '')}>
      <T.div className="cin-inner" variants={CIN_VARS.wrap} initial="hidden" animate="show" exit="exit">
        <T.span key="g" className="cin-ghost" variants={CIN_VARS.ghost} aria-hidden="true">{c.num}</T.span>
        <T.p key="k" className="cin-kicker" variants={CIN_VARS.up}><span key="i" className="cin-kicker-ic"><window.LIcon name={c.icon} size={14} /></span>{c.kicker}</T.p>
        <CinTitle key="t" c={c} W={T.span} />
        <T.p key="d" className="cin-desc" variants={CIN_VARS.up}>{c.desc}</T.p>
        {c.chips && <div key="ch" className="cin-chips">{c.chips.map((m, i) => <T.span className="cin-chip" key={i} variants={CIN_VARS.chip}><window.LIcon key="ic" name={m.icon} size={14} />{m.label}</T.span>)}</div>}
        {c.cards && <div key="ca" className="cin-cards">{c.cards.map((o) => <T.div className="cin-card" key={o.b} variants={CIN_VARS.chip}><span key="a" className="cin-card-ic"><window.LIcon name={o.icon} size={15} /></span><span key="b"><b>{o.b}</b><small>{o.d}</small></span></T.div>)}</div>}
        {c.finale && (
          <React.Fragment key="f">
            <T.div className="cin-stats" variants={CIN_VARS.up}>
              {CRS_FINALE_STATS.map((s, i) => <span className="cin-stat" key={i}><b><span ref={(el) => (statRefs.current[i] = el)}>0</span>{s.suffix}</b><small>{s.label}</small></span>)}
            </T.div>
            <T.div className="cin-ctas" variants={CIN_VARS.up}>
              <Button key="b1" variant="gold" size="lg" href={enrollHref}>שריינו לי מקום</Button>
              <Button key="b2" variant="whatsapp" size="lg" href={CRS_WA} target="_blank" icon={<img src="https://cdn.simpleicons.org/whatsapp/white" alt="" width="18" height="18" />}>דברו איתי בוואטסאפ</Button>
            </T.div>
          </React.Fragment>
        )}
      </T.div>
    </div>
  );
}

function CourseCinema({ enrollHref = '#crs-enroll' }) {
  const FM = (window.Motion && window.Motion.motion && window.Motion.AnimatePresence) ? window.Motion : null;
  const isStatic = React.useMemo(() => window.matchMedia('(prefers-reduced-motion: reduce)').matches, []);
  const stageRef = React.useRef(null), shiftRef = React.useRef(null), tiltRef = React.useRef(null), videoRef = React.useRef(null);
  const railRefs = React.useRef([]), tcRef = React.useRef(null), hintRef = React.useRef(null), idxRef = React.useRef(null), stRef = React.useRef(null);
  const chRef = React.useRef(0);
  const [chapter, setChapter] = React.useState(0);

  React.useEffect(() => {
    const video = videoRef.current;
    if (!video) return;
    let url = null, cancelled = false, tickFn = null;
    /* iOS root fix: direct Range-streamable URL instead of a blob — WebKit video seeking is unreliable
       on blob: URLs, and the file is now faststart (moov first) so a frame paints without a full 13MB
       download. ?v=2 busts the year-long immutable asset cache so devices fetch the fixed file. */
    video.src = '/assets/video/course-safe.mp4?v=2';
    const onMeta = () => {
      if (isStatic || !window.gsap || !window.ScrollTrigger) { video.muted = true; video.loop = true; video.playsInline = true; video.play().catch(() => {}); return; }
      ScrollTrigger.config({ ignoreMobileResize: true });
      /* iOS root fix: WebKit won't paint frames for a never-played paused video, so scrubbing
         currentTime shows nothing. A muted+playsInline play() is allowed without a gesture —
         prime the decode pipeline once, pause, and rewind; scrubbed seeks render from then on. */
      const prime = video.play();
      if (prime && prime.then) prime.then(() => { video.pause(); try { video.currentTime = 0; } catch (e) {} }).catch(() => {});
      const dur = video.duration || 5;
      const V = CIN_V.map((f) => f * dur);
      let seeking = false, want = V[0];
      const applySeek = () => {
        if (seeking || !video.isConnected) return;
        if (Math.abs(video.currentTime - want) < .02) return;
        seeking = true;
        try { video.currentTime = want; } catch (e) { seeking = false; }
      };
      video.addEventListener('seeked', () => { seeking = false; applySeek(); });
      const HOLD = .4;
      stRef.current = ScrollTrigger.create({
        trigger: stageRef.current, start: 'top top', end: '+=520%', pin: true, scrub: .6, anticipatePin: 1,
        onUpdate: (self) => {
          const p = self.progress;
          let idx = 0;
          for (let i = 0; i < CIN.length; i++) if (p >= CIN_T[i]) idx = i;
          const s0 = CIN_T[idx], s1 = CIN_T[idx + 1];
          const local = s1 > s0 ? (p - s0) / (s1 - s0) : 0;
          const play = local < HOLD ? 0 : (local - HOLD) / (1 - HOLD);
          want = V[idx] + play * (V[idx + 1] - V[idx]);
          applySeek();
          if (idx !== chRef.current) { chRef.current = idx; setChapter(idx); }
          railRefs.current.forEach((el, i) => {
            if (!el) return;
            const bar = el.querySelector('.cin-rail-bar i');
            const l = Math.max(0, Math.min(1, (p - CIN_T[i]) / (CIN_T[i + 1] - CIN_T[i])));
            if (bar) bar.style.width = (l * 100) + '%';
            el.classList.toggle('is-on', i === idx);
          });
          if (hintRef.current) hintRef.current.style.opacity = p > .04 ? '0' : '1';
          if (idxRef.current) idxRef.current.firstChild.textContent = 'פרק 0' + (idx + 1);
        },
      });
      tickFn = () => {
        if (!tcRef.current) return;
        const t = video.currentTime || 0;
        tcRef.current.textContent = 'TC 00:0' + Math.floor(t) + '.' + ('0' + Math.floor((t % 1) * 100)).slice(-2);
      };
      gsap.ticker.add(tickFn);
    };
    video.addEventListener('loadedmetadata', onMeta, { once: true });
    return () => {
      cancelled = true;
      if (url) URL.revokeObjectURL(url);
      if (stRef.current) { stRef.current.kill(); stRef.current = null; }
      if (tickFn && window.gsap) gsap.ticker.remove(tickFn);
    };
  }, [isStatic]);

  React.useEffect(() => {
    if (isStatic || !window.gsap || !shiftRef.current) return;
    const mob = window.matchMedia('(max-width: 760px)').matches;
    const MOVES = mob ? [
      { x: 0, rotationY: 0, scale: 1, y: '0vh' },
      { x: 0, rotationY: 0, scale: 1.14, y: '1vh' },
      { x: 0, rotationY: 0, scale: 1.06, y: '0vh' },
      { x: 0, rotationY: 0, scale: 1.18, y: '2vh' },
      { x: 0, rotationY: 0, scale: 1, y: '3vh' },
    ] : [
      { x: '-9vw', rotationY: 7, scale: 1.03, y: '0vh' },
      { x: '9vw', rotationY: -7, scale: 1.07, y: '0vh' },
      { x: '-8vw', rotationY: 6, scale: 1.05, y: '0vh' },
      { x: '9vw', rotationY: -6, scale: 1.1, y: '0vh' },
      { x: '0vw', rotationY: 0, scale: 1, y: '7vh' },
    ];
    gsap.to(shiftRef.current, { ...MOVES[chapter], duration: 1.5, ease: 'expo.out', overwrite: 'auto' });
  }, [chapter, isStatic]);

  React.useEffect(() => {
    if (isStatic || !window.gsap || !tiltRef.current || !stageRef.current || window.matchMedia('(max-width: 760px)').matches) return;
    const el = stageRef.current;
    const qx = gsap.quickTo(tiltRef.current, 'rotationY', { duration: .9, ease: 'power3.out' });
    const qy = gsap.quickTo(tiltRef.current, 'rotationX', { duration: .9, ease: 'power3.out' });
    const move = (e) => {
      const r = el.getBoundingClientRect();
      qx(((e.clientX - r.left) / r.width - .5) * 4);
      qy(-((e.clientY - r.top) / r.height - .5) * 2.6);
    };
    el.addEventListener('pointermove', move);
    return () => el.removeEventListener('pointermove', move);
  }, [isStatic]);

  const jump = (i) => {
    const st = stRef.current;
    if (!st) return;
    window.scrollTo({ top: st.start + (CIN_T[i] + .002) * (st.end - st.start), behavior: 'smooth' });
  };

  if (isStatic) {
    const { Button } = window.DS;
    return (
      <section className="cin is-static" data-screen-label="Course / Cinema">
        <div className="cin-static-head"><span>המסלול המלא · חמישה פרקים</span></div>
        <video className="cin-static-video" ref={videoRef} muted playsInline loop preload="auto" poster="/assets/video/course-safe-poster.jpg" aria-label="פתיחת כספת שלב אחר שלב"></video>
        {CIN.map((c, i) => (
          <div className="cin-static-ch" key={i}>
            <span className="cin-num">CH.{c.num} — 05</span>
            <p className="cin-kicker"><span className="cin-kicker-ic"><window.LIcon name={c.icon} size={14} /></span>{c.kicker}</p>
            <h3 className="cin-title">{c.title.split(' ').map((w, j) => <React.Fragment key={j}><span className={c.accent.includes(j) ? 'accent' : ''}>{w}</span>{' '}</React.Fragment>)}</h3>
            <p className="cin-desc">{c.desc}</p>
            {c.chips && <div className="cin-chips">{c.chips.map((m, j) => <span className="cin-chip" key={j}><window.LIcon name={m.icon} size={14} />{m.label}</span>)}</div>}
            {c.cards && <div className="cin-cards">{c.cards.map((o) => <div className="cin-card" key={o.b}><span className="cin-card-ic"><window.LIcon name={o.icon} size={15} /></span><span><b>{o.b}</b><small>{o.d}</small></span></div>)}</div>}
            {c.finale && (
              <React.Fragment>
                <div className="cin-stats">{CRS_FINALE_STATS.map((s, j) => <span className="cin-stat" key={j}><b>{s.to}{s.suffix}</b><small>{s.label}</small></span>)}</div>
                <div className="cin-ctas">
                  <Button variant="gold" size="lg" href={enrollHref}>שריינו לי מקום</Button>
                  <Button variant="whatsapp" size="lg" href={CRS_WA} target="_blank" icon={<img src="https://cdn.simpleicons.org/whatsapp/white" alt="" width="18" height="18" />}>דברו איתי בוואטסאפ</Button>
                </div>
              </React.Fragment>
            )}
          </div>
        ))}
      </section>
    );
  }

  return (
    <section className={'cin' + (FM ? '' : ' cin-noFM')} ref={stageRef} data-screen-label="Course / Cinema">
      <div className="cin-persp"><div className="cin-shift" ref={shiftRef}><div className="cin-tilt" ref={tiltRef}><video ref={videoRef} muted playsInline preload="auto" poster="/assets/video/course-safe-poster.jpg" aria-label="פתיחת כספת שלב אחר שלב"></video></div></div></div>
      <div className="cin-grid"></div>
      <div className="cin-noise"></div>
      <div className="cin-vig"></div>
      <i className="cin-corner cin-corner-tl"></i><i className="cin-corner cin-corner-tr"></i><i className="cin-corner cin-corner-bl"></i><i className="cin-corner cin-corner-br"></i>
      <div className="cin-hud">
        <span className="cin-hud-tc"><i></i><span ref={tcRef}>TC 00:00.00</span></span>
        <span className="cin-hud-label">קורס פורצי כספות — המסלול המלא</span>
        <span className="cin-hud-idx" ref={idxRef}><span>פרק 01</span> <small>/ 05</small></span>
      </div>
      {FM ? <FM.AnimatePresence mode="wait"><CinCopy key={chapter} idx={chapter} FM={FM} enrollHref={enrollHref} /></FM.AnimatePresence> : <CinCopy key={chapter} idx={chapter} FM={null} enrollHref={enrollHref} />}
      {chapter === 4 && <img className="cin-cert" src="assets/certs/cert-level-a-he.png" alt="תעודת הסמכה — קורס טכנאי כספות" />}
      <div className="cin-hint" ref={hintRef}><window.LIcon name="chevron-down" size={14} />גללו להמשך</div>
      <div className="cin-rail">
        {CIN.map((c, i) => (
          <button key={i} type="button" ref={(el) => (railRefs.current[i] = el)} className={i === 0 ? 'is-on' : ''} onClick={() => jump(i)} aria-label={'פרק ' + c.num + ' — ' + c.rail}>
            <span className="cin-rail-top"><i>{c.num}</i><span>{c.rail}</span></span>
            <span className="cin-rail-bar"><i></i></span>
          </button>
        ))}
      </div>
    </section>
  );
}


Object.assign(window, { CourseCinema, CRS_WA });
