import { App as AntdApp, ConfigProvider, theme } from 'antd';
import enUS from 'antd/locale/en_US';
import faIR from 'antd/locale/fa_IR';
import zhCN from 'antd/locale/zh_CN';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import { I18nextProvider, useTranslation } from 'react-i18next';
import { Links, Meta, Outlet, Scripts, ScrollRestoration } from 'react-router';

import { DialogContainer } from '@/components/Dialog/DialogContainer';
import i18n from '@/i18n/frameworkI18n';
import { AntdAppInstanceCapture } from '@/utils/antdAppInstance';
import models from '@/utils/model/autoImportModels';

import './styles/antd.scss';
import './styles/global.scss';
import './styles/tailwind.css';

// 配置 dayjs（模块级，浏览器与 SSG 端均安全）
dayjs.extend(utc);

const antdLocaleMap = {
    'en-US': enUS,
    'fa-IR': faIR,
    'zh-CN': zhCN,
};

/**
 * HTML 外壳。framework 模式由 root 的 Layout 渲染整个文档结构（取代原 index.html）。
 * <Meta/> <Links/> 注入路由声明的 head 内容与样式/资源；<Scripts/> 注入客户端入口脚本；
 * <ScrollRestoration/> 处理导航时的滚动位置。
 */
export function Layout({ children }: { children: React.ReactNode }) {
    return (
        <html lang="en">
            <head>
                <meta charSet="UTF-8" />
                <link rel="icon" type="image/svg+xml" href="/favicon.ico" />
                <meta name="viewport" content="width=device-width, initial-scale=1.0" />
                <meta
                    name="description"
                    content="FlashLink VPN — lightning-fast, free-to-use VPN with high-speed low-latency connection and best-in-class privacy protection."
                />
                <title>FlashLink VPN</title>
                <Meta />
                <Links />
            </head>
            <body>
                {children}
                <ScrollRestoration />
                <Scripts />
            </body>
        </html>
    );
}

/**
 * 应用 Provider 层（原 App.tsx 中 RouterProvider 之上的部分整体迁入）。
 * models 通过自研 import.meta.glob 自动导入后逐层包裹，其内部状态依赖的 storage 已在底层做 SSR 守卫。
 */
const ModelProviders = ({ children }: { children: React.ReactNode }) =>
    models.reduce((acc, model) => <model.Provider>{acc}</model.Provider>, children);

function Providers({ children }: { children: React.ReactNode }) {
    const { i18n: i18nInstance } = useTranslation();
    const locale =
        antdLocaleMap[i18nInstance.language as keyof typeof antdLocaleMap] ||
        antdLocaleMap['en-US'];

    return (
        <ConfigProvider locale={locale} theme={{ algorithm: theme.darkAlgorithm }}>
            <AntdApp className="h-full">
                <AntdAppInstanceCapture />
                <ModelProviders>
                    {children}
                    <DialogContainer />
                </ModelProviders>
            </AntdApp>
        </ConfigProvider>
    );
}

export default function Root() {
    return (
        <I18nextProvider i18n={i18n}>
            <Providers>
                <Outlet />
            </Providers>
        </I18nextProvider>
    );
}
