// Pet MBTI — app router. Handles the SPA routes plus deep-linking: a shared
// result URL (/t/CODE.html?s=…) boots straight to the right type with the right
// trait bars, and navigating pushes matching history entries so links are
// shareable, bookmarkable, and the back button works.
const AC = window.PM_C;
const { NavBar, Footer, Landing, TestPage, Reveal, ResultPage, TypesGallery, TypeDetail } = window;
const PM_TYPES = window.PM_TYPES;

// Fixed theme for the production site (the design-time tweaks panel is dropped).
const ACCENT = '#F58A50';
const HERO_MOOD = 'playful';
window.PM_C.pawDeep = ACCENT;

const N = window.PM_QUESTIONS.length;

function currentView() {
  return new URLSearchParams(window.location.search || '').get('view');
}

function App() {
  // Parse the entry URL exactly once to pick the initial screen.
  const boot = React.useRef(window.pmBoot()).current;
  const [route, setRoute] = React.useState(() => {
    if (boot) return boot.pct ? 'result' : 'detail';
    if (currentView() === 'types') return 'types';
    return 'home';
  });
  const [answers, setAnswers] = React.useState(Array(N).fill(null));
  const [qIndex, setQIndex] = React.useState(0);
  const [result, setResult] = React.useState(() =>
    boot && boot.pct ? { code: boot.code, type: PM_TYPES[boot.code], pct: boot.pct } : null);
  const [detail, setDetail] = React.useState(() => (boot && !boot.pct ? boot.code : null));
  const [shareTarget, setShareTarget] = React.useState(null); // { type, pct }
  const scRef = React.useRef(null);

  const scrollTop = () => { if (scRef.current) scRef.current.scrollTo(0, 0); window.scrollTo(0, 0); };
  const pushUrl = (url) => { try { window.history.pushState({}, '', url); } catch (e) { /* noop */ } };

  // Keep the browser Back/Forward buttons in sync with the SPA.
  React.useEffect(() => {
    const onPop = () => {
      const b = window.pmBoot();
      if (b && b.pct) { setResult({ code: b.code, type: PM_TYPES[b.code], pct: b.pct }); setRoute('result'); }
      else if (b) { setDetail(b.code); setRoute('detail'); }
      else if (currentView() === 'types') { setRoute('types'); }
      else { setRoute('home'); }
      scrollTop();
    };
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  const PFX = window.PM_PREFIX || '';   // '' (English root) or '/zh'
  const goHome = () => { setRoute('home'); scrollTop(); pushUrl(PFX + '/'); };
  const goTypes = () => { setRoute('types'); scrollTop(); pushUrl(PFX + '/?view=types'); };
  const startTest = () => { setAnswers(Array(N).fill(null)); setQIndex(0); setRoute('test'); scrollTop(); pushUrl(PFX + '/'); };

  const answer = (i, v) => {
    setAnswers((prev) => { const nx = [...prev]; nx[i] = v; return nx; });
  };

  const finish = () => {
    const res = window.pmScore(answers.map((a) => (a == null ? 0 : a)));
    setResult(res);
    setRoute('reveal'); scrollTop();
    setTimeout(() => {
      setRoute('result'); scrollTop();
      pushUrl(window.pmShareUrl(res.code, res.pct));
    }, 1800);
  };

  const openType = (code) => { setDetail(code); setRoute('detail'); scrollTop(); pushUrl(window.pmTypeUrl(code)); };
  const openShare = (type, pct) => setShareTarget({ type, pct: pct || null });

  let screen, navActive = route;
  if (route === 'test') {
    screen = <TestPage answers={answers} onAnswer={answer} onFinish={finish}
      onHome={goHome} index={qIndex} setIndex={setQIndex} />;
  } else if (route === 'reveal') {
    screen = <Reveal />;
  } else if (route === 'result' && result) {
    screen = <ResultPage type={result.type} pct={result.pct} mood={HERO_MOOD} onShare={openShare}
      onRetake={startTest} onAllTypes={goTypes} onOpenType={openType} />;
  } else if (route === 'types') {
    screen = <TypesGallery onOpenType={openType} onStart={startTest} />; navActive = 'types';
  } else if (route === 'detail' && detail) {
    screen = <TypeDetail type={PM_TYPES[detail]} mood={HERO_MOOD} onShare={openShare}
      onRetake={startTest} onAllTypes={goTypes} onOpenType={openType} />;
  } else {
    screen = <Landing onStart={startTest} onTypes={goTypes} onOpenType={openType} />;
  }

  const showChrome = route !== 'reveal';

  return (
    <div ref={scRef} style={{ minHeight: '100vh', background: AC.bg, display: 'flex', flexDirection: 'column' }}>
      {showChrome && <NavBar onHome={goHome} onTypes={goTypes} onStart={startTest} active={navActive} />}
      <div key={route + (route === 'detail' ? detail : '')} style={{ flex: 1, animation: 'pm-fade .3s ease' }}>
        {screen}
      </div>
      {showChrome && route !== 'test' && <Footer />}

      {shareTarget && <window.ShareModal type={shareTarget.type} pct={shareTarget.pct} onClose={() => setShareTarget(null)} />}
    </div>
  );
}

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