"use client";

/**
 * Auth → User 同步器
 *
 * AuthStatusChecker 只负责恢复 loginStatus；用户资料由 user machine
 * 管理。这里持续监听登录态变化：
 *   - notLoggedIn → 清空本地 user context
 *   - guest / email / OAuth → 重新 hydrate user store
 */
import { useEffect, useRef } from "react";

import type { LoginStatus } from "@/data/dto/auth";
import { useAuthState } from "@/stores/auth/auth-context";

import { useUserDispatch } from "./user-context";

export function UserAuthSync() {
  const { hasInitialized, isLoading, loginStatus } = useAuthState();
  const userDispatch = useUserDispatch();
  const prevLoginStatusRef = useRef<LoginStatus | null>(null);

  useEffect(() => {
    if (!hasInitialized || isLoading) return;

    const prev = prevLoginStatusRef.current;
    if (prev === loginStatus) return;
    prevLoginStatusRef.current = loginStatus;

    if (loginStatus === "notLoggedIn") {
      userDispatch({ type: "UserClearLocal" });
      return;
    }

    userDispatch({ type: "UserInit" });
  }, [hasInitialized, isLoading, loginStatus, userDispatch]);

  return null;
}
