import { createHashRouter, createBrowserRouter } from 'react-router-dom';

import config from '@/config';

import routerConfig from './routes';
import { getTitleByPath } from './titles';

const router =
    config.app.routerMode === 'hash'
        ? createHashRouter(routerConfig)
        : createBrowserRouter(routerConfig);

const setPageTitle = (pathname: string) => {
    const routeTitle = getTitleByPath(pathname);
    if (routeTitle) {
        document.title = `${config.app.title} - ${routeTitle}`;
    } else {
        document.title = config.app.title;
    }
};

const getInitialPathname = () => {
    if (config.app.routerMode === 'hash') {
        const hash = window.location.hash.replace(/^#/, ''); // 去掉 '#'
        const [path] = hash.split('?'); // 提取路径和查询部分
        return path;
    } else {
        return window.location.pathname; // 获取 history 模式的路径和查询
    }
};

// 设置初始标题
const initialPathname = getInitialPathname();

setPageTitle(initialPathname);

router.subscribe((state) => {
    console.log(' router.subscribe ~ state:', state);
    setPageTitle(state.location.pathname);
});

export { routerConfig };
export default router;
