/* global React, ReactDOM, Scene01, Scene02, Scene03, Scene04, Scene05, Scene06, Scene07 */

// Fixed CH font: Xiaolai — no more user-switchable font.
// Google Fonts already includes Noto Sans KR / JP via the styles import.

const LANGS = /*EDITMODE-BEGIN*/{
  "lang": "zh"
}/*EDITMODE-END*/;

const LANG_OPTIONS = [
  { id: 'zh', label: '中文',   stack: "'XiaolaiSC', 'Noto Serif SC', serif" },
  { id: 'en', label: 'English', stack: "'Cormorant Garamond', 'XiaolaiSC', serif" },
  { id: 'ko', label: '한국어', stack: "'Noto Serif KR', 'XiaolaiSC', serif" },
  { id: 'ja', label: '日本語', stack: "'Noto Serif JP', 'XiaolaiSC', serif" },
];

const LangSwitcher = ({ active, onChange }) => (
  <div className="fontsw" role="group" aria-label="Language">
    <span className="fontsw__label">LANG</span>
    {LANG_OPTIONS.map(f => (
      <button
        key={f.id}
        onClick={() => onChange(f.id)}
        className={`fontsw__btn ${active === f.id ? 'fontsw__btn--active' : ''}`}
        style={{ fontFamily: f.stack }}
      >{f.label}</button>
    ))}
  </div>
);

const Nav = ({ scrolled, current, lang }) => {
  const labels = window.COPY[lang].sceneLabels;
  return (
    <nav className={`nav ${scrolled ? 'nav--scrolled' : ''}`}>
      <a href="#s01" className="nav__brand">
        <img src="assets/monogram-brown.png" alt="K" className="nav__brand-mark" />
        <span className="nav__brand-ch">{window.COPY[lang].navBrand}</span>
      </a>
      <div className="nav__spacer" />
      <div className="nav__meta">
        {String(current + 1).padStart(2, '0')}
        <span style={{ opacity: 0.4, margin: '0 8px' }}>—</span>
        {labels[current]}
      </div>
    </nav>
  );
};

const Rail = ({ current, onJump, total }) => (
  <div className="rail" aria-hidden>
    {Array.from({ length: total }).map((_, i) => (
      <button
        key={i}
        className={`rail__dot ${i === current ? 'rail__dot--active' : ''}`}
        onClick={() => onJump(i)}
        aria-label={`Go to screen ${i + 1}`}
      />
    ))}
  </div>
);

const TOTAL = 7;

const App = () => {
  const [scrolled, setScrolled] = React.useState(false);
  const [current, setCurrent] = React.useState(0);
  const [lang, setLang] = React.useState(() => {
    return localStorage.getItem('kd_lang') || LANGS.lang;
  });

  React.useEffect(() => {
    const opt = LANG_OPTIONS.find(f => f.id === lang) || LANG_OPTIONS[0];
    document.documentElement.style.setProperty('--font-ch', opt.stack);
    document.documentElement.lang = lang;
    localStorage.setItem('kd_lang', lang);
  }, [lang]);

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  React.useEffect(() => {
    const saved = sessionStorage.getItem('kd_scroll');
    if (saved) {
      requestAnimationFrame(() => { window.scrollTo(0, parseFloat(saved)); });
    }
    const onScroll = () => sessionStorage.setItem('kd_scroll', String(window.scrollY));
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const handleEnter = React.useCallback((idx) => setCurrent(idx), []);
  const jumpTo = (i) => {
    const el = document.getElementById(`s0${i + 1}`);
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  const sceneProps = { total: TOTAL, onEnter: handleEnter, lang };

  return (
    <>
      <Nav scrolled={scrolled} current={current} lang={lang} />
      <Rail current={current} onJump={jumpTo} total={TOTAL} />
      <LangSwitcher active={lang} onChange={setLang} />
      <main>
        <Scene01 index={0} {...sceneProps} />
        <Scene02 index={1} {...sceneProps} />
        <Scene03 index={2} {...sceneProps} />
        <Scene04 index={3} {...sceneProps} />
        <Scene05 index={4} {...sceneProps} />
        <Scene06 index={5} {...sceneProps} />
        <Scene07 index={6} {...sceneProps} />
      </main>
    </>
  );
};

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