import type { Metadata, Viewport } from "next";
import localFont from 'next/font/local';
import { NextIntlClientProvider } from 'next-intl';
import { getMessages } from 'next-intl/server';
import { notFound } from 'next/navigation';
import { locales, type Locale } from '@/i18n/config';
import { Toaster } from 'sonner';
import { ChunkErrorHandler } from '@/components/providers/ChunkErrorHandler';
import "../globals.css";

// 🔧 Pretendard Variable 폰트 - FOUT 완전 방지
const pretendard = localFont({
  src: '../../../public/font/PretendardVariable.woff2',
  variable: '--font-pretendard',
  display: 'swap',
  preload: true,
  weight: '100 900', // Variable 폰트 weight 범위
});

// 🏷️ 환경별 접두사
const getEnvPrefix = () => {
  const env = process.env.NEXT_PUBLIC_APP_ENV;
  if (env === 'local') return '[L]';
  if (env === 'development') return '[D]';
  return '';
};

const APP_NAME = 'SAM';
const APP_TITLE = `${getEnvPrefix()}${APP_NAME} - 내 손안의 대시보드`;

export const metadata: Metadata = {
  title: {
    default: APP_TITLE,
    template: `%s | ${getEnvPrefix()}${APP_NAME} Smart Automation Management`
  },
  description: "내 손안의 대시보드 SAM - 중소기업을 위한 스마트 경영 시스템",
  robots: {
    index: false,
    follow: false,
    nocache: true,
    googleBot: {
      index: false,
      follow: false,
      'max-video-preview': -1,
      'max-image-preview': 'none',
      'max-snippet': -1,
    },
  },
  verification: {
    // Add site verification if needed
    // google: 'your-verification-code',
  },
  openGraph: {
    type: 'website',
    locale: 'ko_KR',
    siteName: APP_NAME,
    title: APP_TITLE,
    description: '내 손안의 대시보드 SAM - 중소기업을 위한 스마트 경영 시스템',
  },
  // Prevent caching of sensitive pages
  other: {
    'cache-control': 'no-cache, no-store, must-revalidate',
  },
};

// 📱 Viewport 설정 - iOS safe-area 지원 + 확대 가능
export const viewport: Viewport = {
  width: 'device-width',
  initialScale: 1,
  minimumScale: 1,        // 최소 100%
  maximumScale: 5,        // 최대 500%까지 확대 가능
  userScalable: true,     // 손가락 확대 허용
  viewportFit: 'cover',   // 아이폰 노치/다이나믹 아일랜드/하단 홈바 영역 커버
};

export function generateStaticParams() {
  return locales.map((locale) => ({ locale }));
}

export default async function RootLayout({
  children,
  params,
}: Readonly<{
  children: React.ReactNode;
  params: Promise<{ locale: string }>;
}>) {
  const { locale } = await params;

  // Ensure the incoming locale is valid
  if (!locales.includes(locale as Locale)) {
    notFound();
  }

  // Providing all messages to the client
  const messages = await getMessages();

  return (
    <html lang={locale} className={pretendard.variable} suppressHydrationWarning>
      <body className={`${pretendard.className} antialiased`} suppressHydrationWarning>
        <NextIntlClientProvider messages={messages}>
          <ChunkErrorHandler />
          {children}
          <Toaster richColors position="top-right" />
        </NextIntlClientProvider>
      </body>
    </html>
  );
}
