/* 逐梦航空 VI · 网页浏览版 — 右侧连续顺滑滚动 */
const { useState, useEffect, useRef, useCallback } = React;

const SLIDES = window.SLIDES || [];
const DESIGN_W = 1920;
const DESIGN_H = 1080;

/* 注入一段 section HTML（静态内容） */
function Stage({ html }) {
  const ref = useRef(null);
  useEffect(() => {
    if (ref.current) ref.current.innerHTML = html;
  }, [html]);
  return <div className="stage" ref={ref} />;
}

function App() {
  const [cur, setCur] = useState(0);
  const [dims, setDims] = useState({ w: DESIGN_W, h: DESIGN_H, scale: 1 });
  const railRef = useRef(null);
  const mainRef = useRef(null);
  const itemsRef = useRef([]);

  /* 计算每页缩放：适配主区域宽度，且每页约 90% 视口高 */
  const fit = useCallback(() => {
    const main = mainRef.current;
    if (!main) return;
    const availW = main.clientWidth - 96;     // 左右留白
    const availH = main.clientHeight * 0.9;    // 每页约九成视口高
    const scale = Math.min(availW / DESIGN_W, availH / DESIGN_H);
    setDims({ w: DESIGN_W * scale, h: DESIGN_H * scale, scale });
  }, []);

  useEffect(() => {
    fit();
    window.addEventListener('resize', fit);
    return () => window.removeEventListener('resize', fit);
  }, [fit]);

  /* 滚动时：找出最接近视口中心的页 → 高亮 */
  const onScroll = useCallback(() => {
    const main = mainRef.current;
    if (!main) return;
    const mid = main.scrollTop + main.clientHeight / 2;
    let best = 0, bestD = Infinity;
    itemsRef.current.forEach((el, i) => {
      if (!el) return;
      const c = el.offsetTop + el.offsetHeight / 2;
      const d = Math.abs(c - mid);
      if (d < bestD) { bestD = d; best = i; }
    });
    setCur(best);
  }, []);

  /* 点击缩略图 → 平滑滚动到该页 */
  const jump = useCallback((i) => {
    const el = itemsRef.current[i];
    const main = mainRef.current;
    if (el && main) {
      main.scrollTo({ top: el.offsetTop - 48, behavior: 'smooth' });
    }
  }, []);

  /* 键盘上下 → 跳到相邻页 */
  useEffect(() => {
    const onKey = (e) => {
      if (['ArrowDown', 'ArrowRight', 'PageDown'].includes(e.key)) {
        e.preventDefault(); jump(Math.min(SLIDES.length - 1, cur + 1));
      } else if (['ArrowUp', 'ArrowLeft', 'PageUp'].includes(e.key)) {
        e.preventDefault(); jump(Math.max(0, cur - 1));
      } else if (e.key === 'Home') { jump(0); }
      else if (e.key === 'End') { jump(SLIDES.length - 1); }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [cur, jump]);

  /* 当前缩略图滚动到可视区域 */
  useEffect(() => {
    const rail = railRef.current;
    if (!rail) return;
    const row = rail.querySelector(`[data-i="${cur}"]`);
    if (row) {
      const rt = row.offsetTop, rh = row.offsetHeight;
      const st = rail.scrollTop, sh = rail.clientHeight;
      if (rt < st + 12) rail.scrollTo({ top: rt - 12, behavior: 'smooth' });
      else if (rt + rh > st + sh - 12) rail.scrollTo({ top: rt + rh - sh + 12, behavior: 'smooth' });
    }
  }, [cur]);

  return (
    <div className="app">
      <div className="rail" ref={railRef}>
        {SLIDES.map((s, i) => (
          <div
            key={i}
            data-i={i}
            className={'thumb-row' + (i === cur ? ' active' : '')}
            onClick={() => jump(i)}
          >
            <div className="thumb-num">{i + 1}</div>
            <div className="thumb">
              <Stage html={s.html} />
            </div>
          </div>
        ))}
      </div>

      <div className="main" ref={mainRef} onScroll={onScroll}>
        <div className="scroll-pad" />
        {SLIDES.map((s, i) => (
          <div
            key={i}
            className="slide-item"
            ref={(el) => (itemsRef.current[i] = el)}
            style={{ width: dims.w + 'px', height: dims.h + 'px' }}
          >
            <div
              className="stage-scaled"
              style={{ transform: `scale(${dims.scale})` }}
            >
              <Stage html={s.html} />
            </div>
          </div>
        ))}
        <div className="scroll-pad" />
        <div className="pageno">{String(cur + 1).padStart(2, '0')} / {String(SLIDES.length).padStart(2, '0')}</div>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
