"use client";
/**
 * Auth 屏
 *
 * 
 */
import { useEffect, useSyncExternalStore } from "react";
import { useRouter } from "next/navigation";

import { MobileShell } from "@/app/_components/core";
import { useAuthDispatch, useAuthState } from "@/stores/auth/auth-context";
import { ROUTES } from "@/router/routes";

import { AuthBackground, AuthPanel } from "./components";
import styles from "./components/auth-screen.module.css";
import { Logger } from "@/utils";

const log = new Logger("AppAuthAuthScreen");

export function AuthScreen() {
  const state = useAuthState();
  const authDispatch = useAuthDispatch();
  const router = useRouter();
  const redirectTo = useSyncExternalStore(
    subscribeLocationSnapshot,
    readRedirectFromLocation,
    () => null,
  );
  const safeRedirectTo = getSafeRedirectPath(redirectTo) ?? ROUTES.chat;

  // 邮箱登录成功 → 跳转；User hydrate 由根级 <UserAuthSync /> 监听 loginStatus 变化处理。
  // 用 pendingRedirect flag（不是 useRef transition detection）——
  // re-mount 时 flag 在 auth context 里持久，区分"刚按了"和"re-visit"准确无误。
  useEffect(() => {
    log.debug("[auth-screen] useEffect (loginStatus + pendingRedirect)", {
      pending: state.pendingRedirect,
      loginStatus: state.loginStatus,
      willRedirect:
        state.pendingRedirect && state.loginStatus !== "notLoggedIn",
    });

    if (state.pendingRedirect && state.loginStatus !== "notLoggedIn") {
      log.debug("[auth-screen] useEffect → router.replace [via pendingRedirect flag]", {
        redirectTo: safeRedirectTo,
      });
      authDispatch({ type: "AuthClearPendingRedirect" });
      router.replace(safeRedirectTo);
    }
  }, [
    state.loginStatus,
    state.pendingRedirect,
    authDispatch,
    router,
    safeRedirectTo,
  ]);

  return (
    <MobileShell>
      <div className={styles.wrapper}>
        <AuthBackground />
        <div className={styles.content}>
          <AuthPanel />
        </div>
      </div>
    </MobileShell>
  );
}

function getSafeRedirectPath(redirectTo: string | null | undefined): string | null {
  if (!redirectTo) return null;
  if (!redirectTo.startsWith("/") || redirectTo.startsWith("//")) return null;
  return redirectTo;
}

function readRedirectFromLocation(): string | null {
  if (typeof window === "undefined") return null;
  return new URLSearchParams(window.location.search).get("redirect");
}

function subscribeLocationSnapshot(): () => void {
  return () => {};
}
