// App.js
import { BrowserRouter as Router, useRoutes } from 'react-router-dom';
import "./App.css"
import routes from "@/Routes";
import { useCallback, useEffect, useState } from "react";
import appApi from "@/api/app";
import { useStore } from "@/store";
import { parsePageConfig } from "@/utils/parsePageConfig";
import type { I18nData, SupportLocale } from "@/type";

function AppRoutes() {
    return useRoutes(routes);
}

function App() {
    const [init, setInit] = useState(false);
    const locale = useStore((s) => s.locale);
    const appConfig = useStore((s) => s.appConfig);

    const initState = useCallback((data: any) => {
        const company = data?.__global__.company;
        const { favicon, shortName } = company || {};
        if (favicon) {
            const favor: any = document.querySelector("link[rel*='icon']") || document.createElement('link');
            favor.type = 'image/x-icon';
            favor.rel = 'shortcut icon';
            favor.href = favicon;
        }
        if (shortName) {
            document.title = shortName
        }
    }, [])

    const getAppConfig = useCallback(async () => {
        try {
            const res = await appApi.getAppConfig();
            const data = parsePageConfig(res.data.items) as I18nData;
            useStore.getState().setAppConfig(data);
            const currentLocale = useStore.getState().locale;
            const config = data[currentLocale] ?? data["zh-CN"];
            const supportLocales: SupportLocale[] = [
                { key: "zh-CN", label: "中文" },
                { key: "en-US", label: "English" },
            ];
            useStore.getState().setSupportLocales(supportLocales);
            initState(config);
        } catch (error) {
            console.log(error);
        }
        setInit(true);
    }, [])

    useEffect(() => {
        if (init) return;
        getAppConfig();
    }, []);

    useEffect(() => {
        const shortName = (appConfig as { company?: { config?: { shortName?: string } } })?.company?.config?.shortName;
        if (shortName) document.title = shortName;
    }, [locale, appConfig]);

    return (
        <>
            <div>
                <Router>
                    <AppRoutes />
                </Router>
            </div>
        </>
    );
}

export default App;