// Training Follow-Up — App entry

const App = () => {
  const [route, setRoute] = React.useState("login");
  const routeRef = React.useRef("login");
  React.useEffect(() => { routeRef.current = route; }, [route]);

  const [userInfo, setUserInfo]   = React.useState({ role:null, isAdmin:false, canEdit:false, canDelete:false, isHrOrAdmin:false });
  const [dataState, setDataState] = React.useState("loading");
  const [dataError, setDataError] = React.useState(null);
  const [dataVersion, setDataVersion] = React.useState(0);
  const [authError, setAuthError] = React.useState(null);
  const [mustSetPassword, setMustSetPassword] = React.useState(false);

  // Eval modals
  const [showCreate, setShowCreate]       = React.useState(false);
  const [fillEval, setFillEval]           = React.useState(null); // { id, type }

  const reloadData = React.useCallback(async () => {
    try {
      const [, me] = await Promise.all([
        window.TRN_API.loadAll(),
        window.TRN_API.me().catch(() => null),
      ]);
      setUserInfo({
        id: me?.id, email: me?.email, name: me?.name || me?.email,
        role: me?.role || "user",
        isAdmin: !!me?.isAdmin,
        isHrOrAdmin: !!me?.isHrOrAdmin,
        canEdit: !!me?.canEdit,
        canDelete: !!me?.canDelete,
      });
      setDataVersion(v => v + 1);
      setDataState("ready");
    } catch(e) { setDataError(e.message || String(e)); setDataState("error"); }
  }, []);

  React.useEffect(() => {
    const hash = new URLSearchParams(window.location.hash.replace("#",""));
    const urlType = hash.get("type");
    const hashError = hash.get("error");
    if (hashError) {
      const desc = hash.get("error_description") || hashError;
      setAuthError(hash.get("error_code")==="otp_expired" ? "ลิงก์หมดอายุ กรุณาขอใหม่" : desc.replace(/\+/g," "));
      history.replaceState(null,"",window.location.pathname);
    }

    let sub;
    window.TRN_AUTH.onAuthStateChange(async (event, session) => {
      if (session) {
        if ((event==="SIGNED_IN"||event==="INITIAL_SESSION") && routeRef.current==="login") {
          const t = new URLSearchParams(window.location.hash.replace("#","")).get("type");
          if (event==="PASSWORD_RECOVERY"||t==="invite"||t==="recovery"||urlType==="invite") {
            setMustSetPassword(true); history.replaceState(null,"",window.location.pathname);
          }
          setRoute("dashboard"); reloadData();
        }
      } else if (event==="SIGNED_OUT") { setRoute("login"); setDataState("ready"); }
    }).then(({ data }) => { sub = data.subscription; });

    window.TRN_AUTH.getSession().then(session => {
      if (session) { setRoute("dashboard"); reloadData(); }
      else setDataState("ready");
    });
    return () => sub?.unsubscribe();
  }, []);

  const handleLogout = async () => { await window.TRN_AUTH.signOut(); setRoute("login"); };
  const handleDataChange = React.useCallback(() => reloadData(), [reloadData]);
  const openNewEval = () => setShowCreate(true);

  return (
    <ToastProvider>
      <div style={{ minHeight:"100vh" }}>
        {dataState === "loading" && <LoadingSplash />}
        {dataState === "error"   && <ErrorSplash message={dataError} onRetry={reloadData} />}

        {dataState === "ready" && route === "login" && (
          <LoginScreen initialError={authError} onErrorClear={() => setAuthError(null)} />
        )}
        {dataState === "ready" && route === "dashboard" && (
          <DashboardScreen key={dataVersion} user={userInfo}
            onNewEval={openNewEval}
            onViewAll={() => setRoute("evals")}
            onLogout={handleLogout} />
        )}
        {dataState === "ready" && route === "evals" && (
          <EvalListScreen key={dataVersion} user={userInfo}
            onBack={() => setRoute("dashboard")}
            onNewEval={openNewEval}
            onDataChange={handleDataChange} />
        )}

        {mustSetPassword && <SetPasswordModal onDone={() => setMustSetPassword(false)} />}

        <CreateEvalModal open={showCreate && !!userInfo.canEdit}
          onClose={() => setShowCreate(false)}
          onDataChange={handleDataChange} />

        {fillEval && (
          <FillEvalModal open={true} evalId={fillEval.id} type={fillEval.type}
            onClose={() => setFillEval(null)}
            onDataChange={handleDataChange} />
        )}
      </div>
    </ToastProvider>
  );
};

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