"use client";

/**
 * Providers — 客户端 Provider 聚合（ai14）
 *
 * 职责：
 * - TanStack Query QueryClientProvider（L2 服务端状态）
 * - GraphQLProvider（urql client 单例，复用 Shell 暴露的 ARB-002 配置）
 * - MSW mock 初始化（仅 dev + NEXT_PUBLIC_API_MOCKING=enabled）
 *
 * 设计依据：02-architecture-design.md §1.1 / §1.2
 */

import { useState, useEffect, type ReactNode } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { GraphQLProvider } from "@/lib/graphql/provider";
import { initMocks } from "@/mocks/browser";

export default function Providers({
  children,
}: {
  children: ReactNode;
}): JSX.Element {
  // QueryClient 单例：useState 保证组件 re-render 时实例稳定
  const [queryClient] = useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            // 学生端数据频变：5min staleTime 平衡性能与新鲜度
            staleTime: 5 * 60 * 1000,
            retry: 1,
            refetchOnWindowFocus: false,
          },
          mutations: {
            retry: 0,
          },
        },
      }),
  );

  // MSW 初始化（仅 dev + mock 启用，且仅在浏览器环境）
  useEffect(() => {
    if (typeof window === "undefined") return;
    if (process.env.NEXT_PUBLIC_API_MOCKING !== "enabled") return;
    void initMocks();
  }, []);

  return (
    <QueryClientProvider client={queryClient}>
      <GraphQLProvider>{children}</GraphQLProvider>
    </QueryClientProvider>
  );
}
