// ============= VIDEO WALKTHROUGH — mock product screencast =============

// chapter timing + which product screen plays (durations in seconds)
const VIDEO_CHAPTERS = [
  { dur: 15, ico: <IconGrid />,   origin: "50% 26%", screen: () => <DashboardMock /> },
  { dur: 19, ico: <IconYT />,     origin: "50% 40%", screen: () => <ScreenLeads /> },
  { dur: 15, ico: <IconShield />, origin: "50% 44%", screen: () => <ScreenVerify /> },
  { dur: 15, ico: <IconChart />,  origin: "50% 40%", screen: () => <ScreenAnalytics /> },
  { dur: 20, ico: <IconInbox />,  origin: "50% 52%", screen: () => <ScreenInbox /> },
];
const VIDEO_TOTAL = VIDEO_CHAPTERS.reduce((a, c) => a + c.dur, 0);
const VIDEO_STARTS = (() => { let a = 0; return VIDEO_CHAPTERS.map((c) => { const s = a; a += c.dur; return s; }); })();

function vwFmt(s) {
  s = Math.max(0, Math.floor(s));
  const m = Math.floor(s / 60), sec = s % 60;
  return `${m}:${String(sec).padStart(2, "0")}`;
}

const IconVolOn = () => <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 5 6 9H2v6h4l5 4V5z" /><path d="M15.5 8.5a5 5 0 0 1 0 7M19 5a9 9 0 0 1 0 14" /></svg>;
const IconVolOff = () => <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 5 6 9H2v6h4l5 4V5z" /><path d="m23 9-6 6M17 9l6 6" /></svg>;
const IconExpand = () => <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M8 3H5a2 2 0 0 0-2 2v3M21 8V5a2 2 0 0 0-2-2h-3M16 21h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3" /></svg>;

function VideoWalkthrough() {
  const { t } = useApp();
  const V = t("video");
  const chapters = V.chapters || [];
  const poster = V.poster || {};

  const wrapRef = useRef(null);
  const { seen } = useInView(wrapRef, { threshold: 0.35 });

  const [time, setTime] = useState(() => {
    const v = parseFloat(localStorage.getItem("of_video_time") || "0");
    return isFinite(v) && v > 0 && v < VIDEO_TOTAL ? v : 0;
  });
  const [playing, setPlaying] = useState(false);
  const [started, setStarted] = useState(false);
  const [muted, setMuted] = useState(true);
  const [capsOn, setCapsOn] = useState(true);
  const [capShown, setCapShown] = useState(true);

  const rafRef = useRef(0);
  const lastRef = useRef(0);
  const timeRef = useRef(time);
  timeRef.current = time;

  const ended = time >= VIDEO_TOTAL - 0.02;

  // playback loop
  useEffect(() => {
    if (!playing) return;
    lastRef.current = performance.now();
    const tick = (now) => {
      const dt = (now - lastRef.current) / 1000;
      lastRef.current = now;
      let nt = timeRef.current + dt;
      if (nt >= VIDEO_TOTAL) { nt = VIDEO_TOTAL; setTime(nt); setPlaying(false); return; }
      setTime(nt);
      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
  }, [playing]);

  // persist position (throttled to whole frames is fine; write on change)
  useEffect(() => {
    const id = setTimeout(() => localStorage.setItem("of_video_time", String(time)), 120);
    return () => clearTimeout(id);
  }, [time]);

  // autoplay once when scrolled into view
  const autoRef = useRef(false);
  useEffect(() => {
    if (seen && !autoRef.current && !ended) {
      autoRef.current = true;
      setStarted(true);
      setPlaying(true);
    }
  }, [seen, ended]);

  const toggle = useCallback(() => {
    if (ended) { setTime(0); setStarted(true); setPlaying(true); return; }
    setStarted(true);
    setPlaying((p) => !p);
  }, [ended]);

  // current chapter + local progress
  let ci = 0;
  for (let i = 0; i < VIDEO_CHAPTERS.length; i++) { if (time >= VIDEO_STARTS[i]) ci = i; }
  const chStart = VIDEO_STARTS[ci];
  const chDur = VIDEO_CHAPTERS[ci].dur;
  const local = Math.min(1, Math.max(0, (time - chStart) / chDur));
  const chap = chapters[ci] || { t: "", lines: [""] };

  // caption: swap line at the halfway point of the chapter
  const lineIdx = local < 0.5 ? 0 : 1;
  const capText = (chap.lines || [])[lineIdx] || (chap.lines || [])[0] || "";

  // re-fade the caption whenever the visible line changes
  const capKeyRef = useRef("");
  const capKey = ci + "-" + lineIdx;
  useEffect(() => {
    if (capKeyRef.current !== capKey) { capKeyRef.current = capKey; setCapShown(false); const id = requestAnimationFrame(() => setCapShown(true)); return () => cancelAnimationFrame(id); }
  }, [capKey]);

  // Ken-Burns transform driven by chapter progress (stays in sync when scrubbing)
  const kbScale = 1.035 + local * 0.06;
  const kbY = -local * 2.4;
  const kbStyle = { transform: `scale(${kbScale.toFixed(4)}) translateY(${kbY.toFixed(2)}%)`, transformOrigin: VIDEO_CHAPTERS[ci].origin };

  const overall = time / VIDEO_TOTAL;

  const seek = useCallback((e) => {
    const el = e.currentTarget;
    const r = el.getBoundingClientRect();
    const ratio = Math.min(1, Math.max(0, (e.clientX - r.left) / r.width));
    setTime(ratio * VIDEO_TOTAL);
    setStarted(true);
  }, []);

  const jump = useCallback((i) => { setTime(VIDEO_STARTS[i] + 0.001); setStarted(true); setPlaying(true); }, []);

  const ScreenC = VIDEO_CHAPTERS[ci].screen;

  return (
    <section className="section" id="video">
      <div className="wrap">
        <SecHead eyebrow={V.eyebrow} t1={V.title1} t2={V.title2} sub={V.sub} center />

        <Reveal className="vw">
          <div className="vw__player">
            <div className="vw__glow" aria-hidden="true"></div>
            <div className="vw__frame" onClick={toggle}>
              <div className="vw__stage">
                {/* recorded app window */}
                <div className="vw__rec">
                  <div className="vw__kb" style={kbStyle}>
                    <div className="vw__win">
                      <div className="vw__winbar">
                        <div className="vw__dots"><i></i><i></i><i></i></div>
                        <span className="vw__url"><IconLock />{V.url}/{["dashboard","leads","verify","analytics","inbox"][ci]}</span>
                        <span className="vw__rec-rec"><i></i>{V.live}</span>
                      </div>
                      <div className="vw__screen" key={ci}><ScreenC /></div>
                    </div>
                  </div>
                </div>

                {/* chapter chip */}
                <div className="vw__chip">
                  <span className="vw__chip-ico">{VIDEO_CHAPTERS[ci].ico}</span>
                  <span>
                    <span className="vw__chip-k" style={{ display: "block" }}>{V.chapLabel} {String(ci + 1).padStart(2, "0")} / {String(chapters.length).padStart(2, "0")}</span>
                    <span className="vw__chip-t" style={{ display: "block" }}>{chap.t}</span>
                  </span>
                </div>

                {/* caption / subtitle */}
                {capsOn && capText ? (
                  <div className="vw__cap-wrap">
                    <div className="vw__cap vw__cap-key no-tr" style={{ opacity: capShown ? 1 : 0, transform: capShown ? "none" : "translateY(8px)" }}>{capText}</div>
                  </div>
                ) : null}

                {/* poster / big play overlay */}
                <div className={`vw__poster ${started && playing ? "hidden" : ""}`}>
                  <button className="vw__bigplay" onClick={(e) => { e.stopPropagation(); toggle(); }} aria-label="Play">
                    <IconPlay />
                  </button>
                  <div className="vw__poster-meta">
                    <div className="vw__poster-kick">{poster.kick}</div>
                    <div className="vw__poster-play">{ended ? poster.replay : poster.play} · {vwFmt(VIDEO_TOTAL)}</div>
                    <div className="vw__poster-badge"><i></i>{poster.badge}</div>
                  </div>
                </div>

                {/* control bar */}
                <div className="vw__ctrl" onClick={(e) => e.stopPropagation()}>
                  <button className="vw__play" onClick={toggle} aria-label={playing ? "Pause" : "Play"}>
                    {playing ? <IconPause /> : <IconPlay className="is-play" />}
                  </button>
                  <div className="vw__time">{vwFmt(time)}<span className="sep">/</span>{vwFmt(VIDEO_TOTAL)}</div>
                  <div className="vw__scrub" onClick={seek}>
                    <div className="vw__track">
                      <div className="vw__buffer"></div>
                      <div className="vw__fill no-tr" style={{ width: `${overall * 100}%` }}></div>
                      {VIDEO_STARTS.slice(1).map((s, i) => (
                        <span key={i} className="vw__tick" style={{ left: `${(s / VIDEO_TOTAL) * 100}%` }}></span>
                      ))}
                      <div className="vw__thumb no-tr" style={{ left: `${overall * 100}%` }}></div>
                    </div>
                  </div>
                  <div className="vw__right">
                    <button className="vw__ibtn" onClick={() => setCapsOn((v) => !v)} title={V.capLabel} aria-label="Captions" style={{ position: "relative" }}>
                      <span style={{ fontFamily: "var(--mono)", fontSize: 10, fontWeight: 700, letterSpacing: ".04em", border: "1px solid currentColor", borderRadius: 4, padding: "2px 4px", opacity: capsOn ? 1 : .5 }}>CC</span>
                    </button>
                    <button className="vw__ibtn" onClick={() => setMuted((v) => !v)} title="Sound" aria-label="Sound">
                      {muted ? <IconVolOff /> : <IconVolOn />}
                    </button>
                    <span className="vw__hd">HD</span>
                    <button className="vw__ibtn" title="Fullscreen" aria-label="Fullscreen"><IconExpand /></button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* chapter rail */}
          <div className="vw__chaps">
            {chapters.map((c, i) => {
              const on = i === ci;
              const prog = on ? local : (time > VIDEO_STARTS[i] ? 1 : 0);
              return (
                <button key={i} className={`vw__chapbtn ${on ? "on" : ""}`} onClick={() => jump(i)}>
                  <div className="vw__chapbtn__n">
                    <span className="vw__chapbtn__ico">{VIDEO_CHAPTERS[i].ico}</span>
                    <span className="vw__chapbtn__time">{vwFmt(VIDEO_STARTS[i])}</span>
                  </div>
                  <div className="vw__chapbtn__t">{c.t}</div>
                  <div className="vw__chapbtn__bar no-tr" style={{ width: `${prog * 100}%` }}></div>
                </button>
              );
            })}
          </div>

          <div className="vw__foot"><IconPlay />{V.foot}</div>
        </Reveal>
      </div>
    </section>
  );
}

Object.assign(window, { VideoWalkthrough });
