"use client";
/**
 * 认证全屏页面
 *
 * 实现方式与 SplashScreen 同款（MobileShell 顶层 + 内部 .wrapper + 背景组件）：
 *   - <MobileShell> 作为 top-level（500px 移动端宽度由 MobileShell 自身约束）
 *   - <AuthBackground> 提供全屏 bg image
 *   - .content 内部承载 AuthPanel（z-index: 2，垂直居中）
 *   - 已登录用户：自动跳 /chat
 *   - 登录成功：通知 ChatBloc + UserBloc
 */
import { useEffect, useRef } from "react";
import { useRouter } from "next/navigation";

import { useAuthState } from "@/stores/auth/auth-context";
import { useChatDispatch } from "@/stores/chat/chat-context";
import { useUserDispatch } from "@/stores/user/user-context";
import { ROUTES } from "@/router/routes";
import { MobileShell } from "@/app/_components/core/mobile-shell";
import { AuthPanel } from "@/app/auth/components/auth-panel";
import { AuthBackground } from "@/app/auth/components/auth-background";

import styles from "./auth-screen.module.css";

export function AuthScreen() {
  // ===== 鉴权路由跳转已由 src/router/proxy.ts 集中处理 =====
  // 本组件只负责：
  //   1. 渲染登录面板
  //   2. 登录成功后初始化 chat/user store + navigate 到 /chat（业务层动作）

  const router = useRouter();
  const state = useAuthState();
  const chatDispatch = useChatDispatch();
  const userDispatch = useUserDispatch();
  const wasSuccess = useRef(false);

  // 邮箱登录成功 → 通知 Chat + User + 跳转
  useEffect(() => {
    if (state.isSuccess && !wasSuccess.current) {
      wasSuccess.current = true;
      chatDispatch({ type: "ChatAuthStatusChanged" });
      userDispatch({ type: "UserInit" });
      router.replace(ROUTES.chat);
    }
  }, [state.isSuccess, chatDispatch, userDispatch, router]);

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