"use client";

import { SessionProvider } from "next-auth/react";
import { Toaster } from "react-hot-toast";
import GlobalLoginModal from "@/components/auth/GlobalLoginModal";
import { useSyncMe } from "@/hooks/useSyncMe";

/**
 * 登录后把服务端 /api/me 同步到本地 vote store 的隐形组件。
 * 必须放在 SessionProvider 内部才能拿到 useSession。
 */
function SyncMeBridge() {
  useSyncMe();
  return null;
}

/**
 * 客户端全局 Provider 集合
 * - SessionProvider: 让 client 组件能用 useSession()
 * - SyncMeBridge: 登录后用 /api/me 覆盖本地票数态(跨设备同步关键)
 * - Toaster: 全站 toast 容器（紫调样式，自动叠加）
 */
export default function Providers({ children }: { children: React.ReactNode }) {
  return (
    <SessionProvider>
      <SyncMeBridge />
      {children}
      <GlobalLoginModal />
      <Toaster
        position="top-center"
        toastOptions={{
          duration: 2800,
          style: {
            background: "rgba(34, 29, 74, 0.95)",
            backdropFilter: "blur(16px)",
            color: "#fff",
            border: "1px solid rgba(139, 92, 246, 0.4)",
            boxShadow:
              "0 12px 32px rgba(0,0,0,0.5), 0 0 24px rgba(139,92,246,0.25)",
            fontSize: "13px",
            letterSpacing: "0.5px",
            padding: "10px 16px",
            borderRadius: "12px",
          },
          success: {
            iconTheme: {
              primary: "#a78bfa",
              secondary: "#fff",
            },
          },
          error: {
            iconTheme: {
              primary: "#f472b6",
              secondary: "#fff",
            },
          },
        }}
      />
    </SessionProvider>
  );
}
