"use client";

import { useCallback } from "react";
import { useRouter } from "next/navigation";
import { useLoginModalStore } from "@/lib/login-modal-store";
import LoginModal from "./LoginModal";

/**
 * 全局登录弹窗 · 挂在 Providers 树最上层。
 * 调用 `useLoginModalStore.show(redirectTo?)` 即可唤起。
 * 登录成功后：有 redirectTo 则 push 过去；无则当前页刷新。
 */
export default function GlobalLoginModal() {
  const router = useRouter();
  const open = useLoginModalStore((s) => s.open);
  const redirectTo = useLoginModalStore((s) => s.redirectTo);
  const setOpen = useLoginModalStore((s) => s.setOpen);

  const handleSuccess = useCallback(() => {
    if (redirectTo) {
      router.push(redirectTo);
      router.refresh();
    } else if (typeof window !== "undefined") {
      window.location.reload();
    }
  }, [redirectTo, router]);

  return (
    <LoginModal
      open={open}
      onClose={() => setOpen(false)}
      onSuccess={handleSuccess}
    />
  );
}
