import { Navigate, Route, Routes } from 'react-router-dom';
import { usePartnerSession } from './contexts/PartnerSessionContext';
import { isSubAccount } from './lib/partnerAccess';
import TabLayout from './layouts/TabLayout';
import SubAccountLayout from './layouts/SubAccountLayout';
import HomePage from './pages/HomePage';
import StoreListPage from './pages/StoreListPage';
import StoreDetailPage from './pages/StoreDetailPage';
import StoreCreatePage from './pages/StoreCreatePage';
import OrderListPage from './pages/OrderListPage';
import OrderDetailPage from './pages/OrderDetailPage';
import CenterPage from './pages/CenterPage';
import BillsPage from './pages/BillsPage';
import SettlementPage from './pages/SettlementPage';
import ReshipPage from './pages/ReshipPage';
import WeeklyReportPage from './pages/WeeklyReportPage';
import LeaderboardPage from './pages/LeaderboardPage';
import StaffListPage from './pages/StaffListPage';
import StaffCreatePage from './pages/StaffCreatePage';

function PrimaryRoutes() {
  return (
    <Routes>
      <Route element={<TabLayout />}>
        <Route path="/" element={<HomePage />} />
        <Route path="/stores" element={<StoreListPage />} />
        <Route path="/orders" element={<OrderListPage />} />
        <Route path="/center" element={<CenterPage />} />
      </Route>
      <Route path="/stores/new" element={<StoreCreatePage />} />
      <Route path="/center/bills" element={<BillsPage />} />
      <Route path="/center/settlement" element={<SettlementPage />} />
      <Route path="/center/staff" element={<StaffListPage />} />
      <Route path="/center/staff/new" element={<StaffCreatePage />} />
      <Route path="/reshipments" element={<ReshipPage />} />
      <Route path="/reports/weekly" element={<WeeklyReportPage />} />
      <Route path="/leaderboard" element={<LeaderboardPage />} />
      <Route path="/stores/:id" element={<StoreDetailPage />} />
      <Route path="/orders/:id" element={<OrderDetailPage />} />
      <Route path="*" element={<Navigate to="/" replace />} />
    </Routes>
  );
}

function SubAccountRoutes() {
  return (
    <Routes>
      <Route element={<SubAccountLayout />}>
        <Route path="/stores" element={<StoreListPage />} />
        <Route path="/stores/new" element={<StoreCreatePage />} />
        <Route path="/stores/:id" element={<StoreDetailPage />} />
      </Route>
      <Route path="*" element={<Navigate to="/stores/new?step=1" replace />} />
    </Routes>
  );
}

export default function PartnerAppRoutes() {
  const { account, authenticated } = usePartnerSession();

  if (!authenticated) {
    return null;
  }

  if (isSubAccount(account)) {
    return <SubAccountRoutes />;
  }
  return <PrimaryRoutes />;
}
