"use client";

import { useAuthGuard } from '@/hooks/useAuthGuard';
import AuthenticatedLayout from '@/layouts/AuthenticatedLayout';
import { RootProvider } from '@/contexts/RootProvider';
import { ApiErrorProvider } from '@/contexts/ApiErrorContext';
import { FCMProvider } from '@/contexts/FCMProvider';
import { DevFillProvider, DevToolbar } from '@/components/dev';
import { PermissionGate } from '@/contexts/PermissionContext';
import { ModuleGuard } from '@/components/auth/ModuleGuard';

/**
 * Protected Layout
 *
 * Purpose:
 * - Apply authentication guard to all protected pages
 * - Apply common layout (sidebar, header) to all protected pages
 * - Provide global context (RootProvider)
 * - Provide API error handling context (ApiErrorProvider)
 * - Initialize FCM push notifications (Capacitor native apps)
 * - Prevent browser back button cache issues
 * - Centralized protection for all routes under (protected)
 *
 * Protected Routes:
 * - /dashboard
 * - /items/* (품목관리)
 * - /master-data/* (기준정보관리)
 * - /production/* (생산관리)
 * - All other authenticated pages
 */
export default function ProtectedLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  // 🔒 모든 하위 페이지에 인증 보호 적용
  useAuthGuard();

  // 🎨 모든 하위 페이지에 공통 레이아웃 및 Context 적용
  // 🚨 ApiErrorProvider: Server Action 401 에러 시 자동 로그인 리다이렉트
  // 📱 FCMProvider: Capacitor 네이티브 앱에서 FCM 푸시 알림 초기화
  return (
    <RootProvider>
      <ApiErrorProvider>
        <FCMProvider>
          <DevFillProvider>
            <AuthenticatedLayout>
              <PermissionGate>
                <ModuleGuard>{children}</ModuleGuard>
              </PermissionGate>
            </AuthenticatedLayout>
            <DevToolbar />
          </DevFillProvider>
        </FCMProvider>
      </ApiErrorProvider>
    </RootProvider>
  );
}