import { Routes, Route, Navigate } from 'react-router-dom';
import LoginPage from '@/pages/LoginPage';
import MainLayout from '@/layouts/MainLayout';
import Dashboard from '@/pages/Dashboard';

// ── P5: 연말명세서 / 분개장 ──────────────────────────
import AgentAnnualIncomeList   from '@/pages/income/AgentAnnualIncomeList';
import AccountingJournalList   from '@/pages/accounting/AccountingJournalList';

// ── P5-W2: 원천세 / 부가세 신고 ──────────────────────
import WithholdingTaxReportList from '@/pages/tax/WithholdingTaxReportList';
import VatReportList            from '@/pages/tax/VatReportList';

// ── P5-W3: 결산 / 연말명세서 / 이상치 / 예측 ──────────
import AccountingCloseList   from '@/pages/accounting/AccountingCloseList';
import YearEndStatementList  from '@/pages/income/YearEndStatementList';
import RetentionAnomalyList  from '@/pages/kpi/RetentionAnomalyList';
import ForecastKpiList       from '@/pages/kpi/ForecastKpiList';

// ── P4: 수수료 종류 ──────────────────────────────────
import CommissionMaster        from '@/pages/commission/CommissionMaster';
import CollectionCommission    from '@/pages/commission/CollectionCommission';
import RenewalCommission       from '@/pages/commission/RenewalCommission';
import ReinstatementCommission from '@/pages/commission/ReinstatementCommission';
import PersistencyBonus        from '@/pages/commission/PersistencyBonus';
import OverrideLedger          from '@/pages/commission/OverrideLedger';

// ── P4: 설계사 라이프사이클 ───────────────────────────
import AgentContracts  from '@/pages/agent/AgentContracts';
import AgentLicenses   from '@/pages/agent/AgentLicenses';
import AgentTrainings  from '@/pages/agent/AgentTrainings';

// ── P4: 계약 운영 ────────────────────────────────────
import ContractEndorsements from '@/pages/contracts/ContractEndorsements';
import Complaints           from '@/pages/contracts/Complaints';

// ── P4: 시스템 ──────────────────────────────────────
import Approvals from '@/pages/system/Approvals';
import Notices   from '@/pages/system/Notices';

// ── P4: 출금 ────────────────────────────────────────
import WithdrawRequest from '@/pages/payments/WithdrawRequest';

import OrgTree from '@/pages/org/OrgTree';
import AgentList from '@/pages/org/AgentList';
import AgentDetail from '@/pages/org/AgentDetail';
import AgentForm from '@/pages/org/AgentForm';

import CompanyList from '@/pages/product/CompanyList';
import ProductList from '@/pages/product/ProductList';
import ContractList from '@/pages/product/ContractList';

import CommissionRateList    from '@/pages/rule/CommissionRateList';
import PayoutRuleList        from '@/pages/rule/PayoutRuleList';
import OverrideRuleList      from '@/pages/rule/OverrideRuleList';
import ChargebackRuleList    from '@/pages/rule/ChargebackRuleList';
import ExceptionCodeList     from '@/pages/rule/ExceptionCodeList';
import RegulatoryLimitList   from '@/pages/rule/RegulatoryLimitList';
import InstallmentRatioList  from '@/pages/rule/InstallmentRatioList';
import ChargebackGradeList   from '@/pages/rule/ChargebackGradeList';

import ReceiveData from '@/pages/receive/ReceiveData';
import ReceiveMapping from '@/pages/receive/ReceiveMapping';

import RecruitLedger from '@/pages/ledger/RecruitLedger';
import MaintainLedger from '@/pages/ledger/MaintainLedger';
import ExceptionLedger from '@/pages/ledger/ExceptionLedger';

import SettleList          from '@/pages/settle/SettleList';
import BatchRun            from '@/pages/settle/BatchRun';
import PaymentList         from '@/pages/settle/PaymentList';
import DeductionList       from '@/pages/settle/DeductionList';
import PeriodClose         from '@/pages/settle/PeriodClose';
import SettleCorrection    from '@/pages/settle/SettleCorrection';
import TaxInvoiceList      from '@/pages/settle/TaxInvoiceList';
import CommissionDispute   from '@/pages/settle/CommissionDispute';
import IncentiveProgram    from '@/pages/settle/IncentiveProgram';

import PerformanceReport from '@/pages/report/PerformanceReport';
import OrgReport from '@/pages/report/OrgReport';
import ChargebackRiskReport from '@/pages/report/ChargebackRiskReport';

import KpiMonthlySummary from '@/pages/kpi/KpiMonthlySummary';
import KpiOrgSummary from '@/pages/kpi/KpiOrgSummary';
import KpiRetention from '@/pages/kpi/KpiRetention';
import KpiCumulative from '@/pages/kpi/KpiCumulative';

import UserList from '@/pages/system/UserList';
import RoleList from '@/pages/system/RoleList';
import MenuManage from '@/pages/system/MenuManage';
import CodeList from '@/pages/system/CodeList';
import SystemConfig from '@/pages/system/SystemConfig';
import SystemLog from '@/pages/system/SystemLog';
import UploadTemplateManager from '@/pages/system/UploadTemplateManager';
import DataDomainList from '@/pages/system/DataDomainList';
import DataDictionary from '@/pages/system/DataDictionary';
import ExternalCallLogList from '@/pages/system/ExternalCallLogList';

function RequireAuth({ children }: { children: React.ReactNode }) {
  const token = localStorage.getItem('accessToken');
  return token ? <>{children}</> : <Navigate to="/login" replace />;
}

export default function App() {
  return (
    <Routes>
      <Route path="/login" element={<LoginPage />} />
      <Route path="/" element={<RequireAuth><MainLayout /></RequireAuth>}>
        <Route index element={<Dashboard />} />

        {/* 조직 / 인사 */}
        <Route path="org/tree"              element={<OrgTree />} />
        <Route path="org/agents"            element={<AgentList />} />
        <Route path="org/agents/new"        element={<AgentForm />} />
        <Route path="org/agents/:id"        element={<AgentDetail />} />
        <Route path="org/agents/:id/edit"   element={<AgentForm />} />

        {/* 상품 / 계약 */}
        <Route path="companies"             element={<CompanyList />} />
        <Route path="products"              element={<ProductList />} />
        <Route path="contracts"             element={<ContractList />} />

        {/* 수수료 규정 */}
        <Route path="rules/commission"          element={<CommissionRateList />} />
        <Route path="rules/payout"              element={<PayoutRuleList />} />
        <Route path="rules/override"            element={<OverrideRuleList />} />
        <Route path="rules/chargeback"          element={<ChargebackRuleList />} />
        <Route path="rules/exceptions"          element={<ExceptionCodeList />} />
        <Route path="rules/regulatory"          element={<RegulatoryLimitList />} />
        <Route path="rules/installment-ratios"  element={<InstallmentRatioList />} />
        <Route path="rules/chargeback-grades"   element={<ChargebackGradeList />} />

        {/* 데이터 수신 */}
        <Route path="receive/data"          element={<ReceiveData />} />
        <Route path="receive/mapping"       element={<ReceiveMapping />} />

        {/* 원장 */}
        <Route path="ledger/recruit"        element={<RecruitLedger />} />
        <Route path="ledger/maintain"       element={<MaintainLedger />} />
        <Route path="ledger/exception"      element={<ExceptionLedger />} />

        {/* 정산 / 지급 */}
        <Route path="settle"                    element={<SettleList />} />
        <Route path="settle/batch"              element={<BatchRun />} />
        <Route path="settle/deductions"         element={<DeductionList />} />
        <Route path="settle/period-close"       element={<PeriodClose />} />
        <Route path="settle/corrections"        element={<SettleCorrection />} />
        <Route path="settle/tax-invoices"       element={<TaxInvoiceList />} />
        <Route path="settle/disputes"           element={<CommissionDispute />} />
        <Route path="settle/incentives"         element={<IncentiveProgram />} />
        <Route path="payments"                  element={<PaymentList />} />

        {/* 리포트 */}
        <Route path="report/performance"    element={<PerformanceReport />} />
        <Route path="report/org"            element={<OrgReport />} />
        <Route path="report/chargeback-risk" element={<ChargebackRiskReport />} />

        {/* KPI 대시보드 */}
        <Route path="kpi/monthly"           element={<KpiMonthlySummary />} />
        <Route path="kpi/org"               element={<KpiOrgSummary />} />
        <Route path="kpi/retention"         element={<KpiRetention />} />
        <Route path="kpi/cumulative"        element={<KpiCumulative />} />
        <Route path="kpi/retention-anomaly" element={<RetentionAnomalyList />} />
        <Route path="kpi/forecast"          element={<ForecastKpiList />} />

        {/* P5: 연말명세서 / 분개장 */}
        <Route path="commission/annual-income"      element={<AgentAnnualIncomeList />} />
        <Route path="commission/accounting-journal" element={<AccountingJournalList />} />

        {/* P5-W2: 원천세 / 부가세 신고 */}
        <Route path="commission/withholding-tax" element={<WithholdingTaxReportList />} />
        <Route path="commission/vat-report"      element={<VatReportList />} />

        {/* P5-W3: 회계 결산 / 연말 지급명세서 */}
        <Route path="commission/accounting-close"    element={<AccountingCloseList />} />
        <Route path="commission/year-end-statement"  element={<YearEndStatementList />} />

        {/* P4: 수수료 종류 */}
        <Route path="commission/type"         element={<CommissionMaster />} />
        <Route path="commission/master"       element={<CommissionMaster />} />
        <Route path="commission/collection"   element={<CollectionCommission />} />
        <Route path="commission/renewal"      element={<RenewalCommission />} />
        <Route path="commission/reinstatement" element={<ReinstatementCommission />} />
        <Route path="commission/persistency"  element={<PersistencyBonus />} />
        <Route path="commission/override-ledger" element={<OverrideLedger />} />

        {/* P4: 설계사 라이프사이클 */}
        <Route path="agent/contracts"  element={<AgentContracts />} />
        <Route path="agent/licenses"   element={<AgentLicenses />} />
        <Route path="agent/trainings"  element={<AgentTrainings />} />

        {/* P4: 계약 운영 */}
        <Route path="contracts/endorsements" element={<ContractEndorsements />} />
        <Route path="contracts/complaints"   element={<Complaints />} />

        {/* P4: 시스템 */}
        <Route path="system/approvals" element={<Approvals />} />
        <Route path="system/notices"   element={<Notices />} />

        {/* P4: 출금 */}
        <Route path="payments/withdraw" element={<WithdrawRequest />} />

        {/* 시스템관리 */}
        <Route path="system/users"          element={<UserList />} />
        <Route path="system/roles"          element={<RoleList />} />
        <Route path="system/menus"          element={<MenuManage />} />
        <Route path="system/codes"          element={<CodeList />} />
        <Route path="system/config"         element={<SystemConfig />} />
        <Route path="system/logs"           element={<SystemLog />} />
        <Route path="system/upload-templates" element={<UploadTemplateManager />} />
        <Route path="system/data-domains"     element={<DataDomainList />} />
        <Route path="system/data-dictionary"  element={<DataDictionary />} />
        <Route path="system/external-call-log" element={<ExternalCallLogList />} />
      </Route>
    </Routes>
  );
}
