// App.jsx — flow controller + app shell
const VALID_SCREENS = ['login', 'select', 'random', 'hint'];

function readSession() {
  try { return JSON.parse(sessionStorage.getItem('buddy_state') || '{}'); } catch { return {}; }
}

function App() {
  // sessionStorage survives refresh within the same tab, but is empty in a new tab —
  // so the user logs in fresh per tab while keeping their session alive across reloads.
  const [state, setState] = React.useState(readSession);

  // Derive initial screen from URL hash, guarded by session state
  const [screen, setScreen] = React.useState(() => {
    const h = window.location.hash.slice(1);
    if (VALID_SCREENS.includes(h) && (h === 'login' || readSession().me)) return h;
    return 'login';
  });

  const [anim, setAnim] = React.useState("in");
  const [data, setData] = React.useState(null);
  const [loadErr, setLoadErr] = React.useState("");

  // Ref so the popstate handler always sees the latest state without re-binding
  const stateRef = React.useRef(state);
  React.useEffect(() => {
    stateRef.current = state;
    try { sessionStorage.setItem('buddy_state', JSON.stringify(state)); } catch {}
  }, [state]);

  React.useEffect(() => {
    loadAppData().then(setData).catch((e) => setLoadErr(e.message || "โหลดข้อมูลไม่สำเร็จ"));
  }, []);

  // Hash routing: keep URL hash in sync and handle browser back/forward
  React.useEffect(() => {
    history.replaceState({}, '', '#' + screen);

    const onPopState = () => {
      const h = window.location.hash.slice(1);
      const target = VALID_SCREENS.includes(h) ? h : 'login';
      if (target !== 'login' && !stateRef.current.me) {
        history.replaceState({}, '', '#login');
        setScreen('login');
        return;
      }
      setAnim("out");
      setTimeout(() => { setScreen(target); setAnim("in"); window.scrollTo(0, 0); }, 180);
    };

    window.addEventListener('popstate', onPopState);
    return () => window.removeEventListener('popstate', onPopState);
  }, []);

  const set = (patch) => setState((s) => ({ ...s, ...patch }));
  const go = (next) => {
    setAnim("out");
    setTimeout(() => {
      history.pushState({}, '', '#' + next);
      setScreen(next);
      setAnim("in");
      window.scrollTo(0, 0);
    }, 180);
  };
  // logout / switch user — wipe session state and return to login
  const reset = () => { setState({}); go("login"); };

  const ScreenComp = { login: Login, select: BuddySelect, random: RandomGroup, hint: BuddyHint }[screen];

  const bg = {
    login:  "bg-[radial-gradient(circle_at_50%_0%,#fff_0%,#FAF5EC_45%,#efe4cf_100%)]",
    select: "bg-[radial-gradient(circle_at_50%_0%,#fff_0%,#FAF5EC_45%,#efe4cf_100%)]",
    random: "bg-safari-mahogany",
    hint:   "bg-safari-grass",
  }[screen];

  const Shell = ({ children, bgClass }) => (
    <div className={`min-h-[100dvh] w-full flex justify-center transition-colors duration-300 ${bgClass}`}>
      <div className="relative w-full max-w-md min-h-[100dvh] flex flex-col">{children}</div>
    </div>
  );

  if (loadErr) {
    return (
      <Shell bgClass={bg}>
        <div className="flex-1 flex flex-col items-center justify-center text-center px-8 font-serif text-safari-mahogany">
          <div className="w-16 h-16 rounded-full bg-safari-red/10 text-safari-red flex items-center justify-center mb-4">
            <Icon name="lock" className="w-8 h-8" />
          </div>
          <p className="font-semibold text-[17px]">โหลดข้อมูลไม่สำเร็จ</p>
          <p className="text-[13.5px] text-safari-brown mt-1.5 leading-snug">{loadErr}</p>
        </div>
      </Shell>
    );
  }

  if (!data) {
    return (
      <Shell bgClass={bg}>
        <div className="flex-1 flex flex-col items-center justify-center gap-4 font-serif">
          <div className="w-12 h-12 rounded-full border-[3px] border-safari-gold/25 border-t-safari-red animate-spin" />
          <p className="text-[13.5px] text-safari-brown">กำลังเตรียมซาฟารี…</p>
        </div>
      </Shell>
    );
  }

  return (
    <Shell bgClass={bg}>
      <div className={`flex-1 flex flex-col transition-all duration-200
                       ${anim === "in" ? "opacity-100 translate-y-0" : "opacity-0 translate-y-1"}`}>
        <ScreenComp go={go} state={state} set={set} data={data} reset={reset} />
      </div>
    </Shell>
  );
}

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