"use client";

import { type ReactNode } from "react";
import { GraphQLProvider } from "@/providers/graphql-provider";
import { AuthProvider } from "@/providers/auth-provider";
import { ToastProvider } from "@/providers/toast-provider";
import { AdminShell } from "@/components/admin-shell";
import { MswInitializer } from "@/components/msw-initializer";
import { useState, useEffect } from "react";

/**
 * MF Remote 入口组件
 *
 * 仲裁 ARB-002 §2.2：Shell 动态 import admin/AdminApp 加载管理端
 * - MF 模式：Shell 提供 GraphQLProvider/AuthProvider/AppShell，AdminApp 仅渲染页面
 * - Standalone 模式：AdminApp 自建 providers + AdminShell
 *
 * 暴露：next.config.js exposes: { './AdminApp': './src/app/admin-app.tsx' }
 */
export default function AdminApp({ children }: { children: ReactNode }) {
  const [mswReady, setMswReady] = useState(false);

  // MF 模式下复用 Shell providers（通过 dynamic import）
  // Standalone 模式下自建 providers
  const isStandalone = process.env.NEXT_PUBLIC_MF_ENABLED !== "true";

  useEffect(() => {
    if (!isStandalone) {
      setMswReady(true);
    }
  }, [isStandalone]);

  if (!isStandalone) {
    // MF 模式：Shell 已提供 providers + AppShell
    return <>{children}</>;
  }

  // Standalone 模式：自建 providers
  return (
    <GraphQLProvider>
      <MswInitializer onReady={() => setMswReady(true)} />
      {mswReady && (
        <AuthProvider>
          <ToastProvider>
            <AdminShell>{children}</AdminShell>
          </ToastProvider>
        </AuthProvider>
      )}
    </GraphQLProvider>
  );
}
