/// <reference types="vite/client" />

import React, { Suspense, lazy } from 'react';
import { Routes, Route } from 'react-router-dom';
import Header from '@/components/Header';
import Layout from '@/components/Layout';
import menuItems from '@/data/menuItems';

// 모든 페이지를 glob으로 가져오기
const pages = import.meta.glob('@/pages/**/*.tsx');

// lazy import 유틸
const lazyImport = (path: string) => {
  const importer = pages[`/src/pages/${path}.tsx`];
  return importer
    ? lazy(importer as () => Promise<{ default: React.ComponentType }>)
    : lazy(() => Promise.resolve({ default: () => <div>페이지를 찾을 수 없습니다.</div> }));
};

// Suspense 래핑
const withSuspense = (Component: React.LazyExoticComponent<React.ComponentType>) => (
  <Suspense fallback={<div>로딩 중...</div>}>
    <Component />
  </Suspense>
);

// 메뉴 기반 라우팅
const renderRoutesFromMenu = () => {
  return menuItems.map((parent) => {
    const parentPath = parent.href.replace(/^\//, '');

    return (
      <Route key={parent.href} path={parentPath} element={<Layout />}>
        {parent.children.map((child) => {
          const childPath = child.href.replace(/^\//, '');
          const fullPath = `${parentPath}/${childPath}`;
          const Component = lazyImport(fullPath);

          return (
            <Route
              key={child.href}
              path={childPath}
              element={withSuspense(Component)}
            />
          );
        })}
      </Route>
    );
  });
};

// 메인 및 404 페이지도 lazy import로 처리
const Main = lazyImport('main/index');
const NotFound = lazyImport('NotFound');

const App = () => {
  return (
    <>
      <Header />
      <Routes>
        <Route path="/" element={withSuspense(Main)} />
        {renderRoutesFromMenu()}
        <Route path="*" element={withSuspense(NotFound)} />
      </Routes>
    </>
  );
};

export default App;
