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

// ── 페이지 레이지 로딩 ──────────────────────────────────
const Dashboard = React.lazy(() => import('@/pages/Dashboard'));

// P5: 연말명세서 / 분개장
const AgentAnnualIncomeList   = React.lazy(() => import('@/pages/income/AgentAnnualIncomeList'));
const AccountingJournalList   = React.lazy(() => import('@/pages/accounting/AccountingJournalList'));

// P5-W2: 원천세 / 부가세 신고
const WithholdingTaxReportList = React.lazy(() => import('@/pages/tax/WithholdingTaxReportList'));
const VatReportList            = React.lazy(() => import('@/pages/tax/VatReportList'));

// P5-W3: 결산 / 연말명세서 / 이상치 / 예측
const AccountingCloseList   = React.lazy(() => import('@/pages/accounting/AccountingCloseList'));
const YearEndStatementList  = React.lazy(() => import('@/pages/income/YearEndStatementList'));
const RetentionAnomalyList  = React.lazy(() => import('@/pages/kpi/RetentionAnomalyList'));
const ForecastKpiList       = React.lazy(() => import('@/pages/kpi/ForecastKpiList'));

// P8: 운영 7도메인
const StepClose            = React.lazy(() => import('@/pages/settle/StepClose'));
const HqSettle             = React.lazy(() => import('@/pages/settle/HqSettle'));
const GradeEvaluation      = React.lazy(() => import('@/pages/org/GradeEvaluation'));
const JointContract        = React.lazy(() => import('@/pages/contracts/JointContract'));
const GuaranteeInsurance   = React.lazy(() => import('@/pages/org/GuaranteeInsurance'));
const ReserveFund          = React.lazy(() => import('@/pages/commission/ReserveFund'));
const CommissionSimulator  = React.lazy(() => import('@/pages/commission/CommissionSimulator'));

// P9: 환수채권
const ClawbackReceivable      = React.lazy(() => import('@/pages/commission/ClawbackReceivable'));

// P7: 수수료 계산 7도메인
const IncomeCommission        = React.lazy(() => import('@/pages/commission/IncomeCommission'));
const ReferralCommission      = React.lazy(() => import('@/pages/commission/ReferralCommission'));
const SettlingSupport         = React.lazy(() => import('@/pages/commission/SettlingSupport'));
const RecognizedPerformance   = React.lazy(() => import('@/pages/commission/RecognizedPerformance'));
const Award                   = React.lazy(() => import('@/pages/commission/Award'));
const LifeSupport             = React.lazy(() => import('@/pages/commission/LifeSupport'));
const BranchAllowance         = React.lazy(() => import('@/pages/commission/BranchAllowance'));

// P4: 수수료 종류
const CommissionMaster        = React.lazy(() => import('@/pages/commission/CommissionMaster'));
const CollectionCommission    = React.lazy(() => import('@/pages/commission/CollectionCommission'));
const RenewalCommission       = React.lazy(() => import('@/pages/commission/RenewalCommission'));
const ReinstatementCommission = React.lazy(() => import('@/pages/commission/ReinstatementCommission'));
const PersistencyBonus        = React.lazy(() => import('@/pages/commission/PersistencyBonus'));
const OverrideLedger          = React.lazy(() => import('@/pages/commission/OverrideLedger'));

// P4: 설계사 라이프사이클
const AgentContracts  = React.lazy(() => import('@/pages/agent/AgentContracts'));
const AgentLicenses   = React.lazy(() => import('@/pages/agent/AgentLicenses'));
const AgentTrainings  = React.lazy(() => import('@/pages/agent/AgentTrainings'));

// P4: 계약 운영
const ContractEndorsements = React.lazy(() => import('@/pages/contracts/ContractEndorsements'));
const ContractSuccessions  = React.lazy(() => import('@/pages/contracts/ContractSuccessions'));
const Complaints           = React.lazy(() => import('@/pages/contracts/Complaints'));

// P4: 시스템
const Approvals = React.lazy(() => import('@/pages/system/Approvals'));
const Notices   = React.lazy(() => import('@/pages/system/Notices'));

// P4: 출금
const WithdrawRequest = React.lazy(() => import('@/pages/payments/WithdrawRequest'));

// 조직 / 인사
const OrgTree    = React.lazy(() => import('@/pages/org/OrgTree'));
const AgentList  = React.lazy(() => import('@/pages/org/AgentList'));
const AgentDetail = React.lazy(() => import('@/pages/org/AgentDetail'));
const AgentForm  = React.lazy(() => import('@/pages/org/AgentForm'));

// 상품 / 계약
const CompanyList  = React.lazy(() => import('@/pages/product/CompanyList'));
const ProductList  = React.lazy(() => import('@/pages/product/ProductList'));
const ContractList = React.lazy(() => import('@/pages/product/ContractList'));

// 수수료 규정
const CommissionRateList    = React.lazy(() => import('@/pages/rule/CommissionRateList'));
const PayoutRuleList        = React.lazy(() => import('@/pages/rule/PayoutRuleList'));
const OverrideRuleList      = React.lazy(() => import('@/pages/rule/OverrideRuleList'));
const ChargebackRuleList    = React.lazy(() => import('@/pages/rule/ChargebackRuleList'));
const ExceptionCodeList     = React.lazy(() => import('@/pages/rule/ExceptionCodeList'));
const RegulatoryLimitList   = React.lazy(() => import('@/pages/rule/RegulatoryLimitList'));
const InstallmentRatioList  = React.lazy(() => import('@/pages/rule/InstallmentRatioList'));
const ChargebackGradeList   = React.lazy(() => import('@/pages/rule/ChargebackGradeList'));

// 데이터 수신
const ReceiveData    = React.lazy(() => import('@/pages/receive/ReceiveData'));
const ReceiveMapping = React.lazy(() => import('@/pages/receive/ReceiveMapping'));

// 원장
const RecruitLedger   = React.lazy(() => import('@/pages/ledger/RecruitLedger'));
const MaintainLedger  = React.lazy(() => import('@/pages/ledger/MaintainLedger'));
const ExceptionLedger = React.lazy(() => import('@/pages/ledger/ExceptionLedger'));

// 정산 / 지급
const SettleList          = React.lazy(() => import('@/pages/settle/SettleList'));
const BatchRun            = React.lazy(() => import('@/pages/settle/BatchRun'));
const PaymentList         = React.lazy(() => import('@/pages/settle/PaymentList'));
const DeductionList       = React.lazy(() => import('@/pages/settle/DeductionList'));
const PeriodClose         = React.lazy(() => import('@/pages/settle/PeriodClose'));
const SettleCorrection    = React.lazy(() => import('@/pages/settle/SettleCorrection'));
const TaxInvoiceList      = React.lazy(() => import('@/pages/settle/TaxInvoiceList'));
const CommissionDispute   = React.lazy(() => import('@/pages/settle/CommissionDispute'));
const IncentiveProgram    = React.lazy(() => import('@/pages/settle/IncentiveProgram'));

// 리포트
const PerformanceReport    = React.lazy(() => import('@/pages/report/PerformanceReport'));
const OrgReport            = React.lazy(() => import('@/pages/report/OrgReport'));
const ChargebackRiskReport = React.lazy(() => import('@/pages/report/ChargebackRiskReport'));

// KPI 대시보드
const KpiMonthlySummary = React.lazy(() => import('@/pages/kpi/KpiMonthlySummary'));
const KpiOrgSummary     = React.lazy(() => import('@/pages/kpi/KpiOrgSummary'));
const KpiRetention      = React.lazy(() => import('@/pages/kpi/KpiRetention'));
const KpiCumulative     = React.lazy(() => import('@/pages/kpi/KpiCumulative'));

// 시스템관리
const UserList              = React.lazy(() => import('@/pages/system/UserList'));
const RoleList              = React.lazy(() => import('@/pages/system/RoleList'));
const MenuManage            = React.lazy(() => import('@/pages/system/MenuManage'));
const CodeList              = React.lazy(() => import('@/pages/system/CodeList'));
const SystemConfig          = React.lazy(() => import('@/pages/system/SystemConfig'));
const SystemLog             = React.lazy(() => import('@/pages/system/SystemLog'));
const UploadTemplateManager = React.lazy(() => import('@/pages/system/UploadTemplateManager'));
const DataDomainList        = React.lazy(() => import('@/pages/system/DataDomainList'));
const DataDictionary        = React.lazy(() => import('@/pages/system/DataDictionary'));
const ExternalCallLogList   = React.lazy(() => import('@/pages/system/ExternalCallLogList'));

// ── 로딩 폴백 ────────────────────────────────────────────
const PageFallback = (
  <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '60vh' }}>
    <Spin size="large" />
  </div>
);

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

export default function App() {
  return (
    <Suspense fallback={PageFallback}>
      <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 />} />

          {/* P8: 운영 7도메인 */}
          <Route path="settle/step-close"       element={<StepClose />} />
          <Route path="settle/hq-settle"        element={<HqSettle />} />
          <Route path="org/grade-eval"          element={<GradeEvaluation />} />
          <Route path="contracts/joint"         element={<JointContract />} />
          <Route path="org/guarantee"           element={<GuaranteeInsurance />} />
          <Route path="commission/reserve"      element={<ReserveFund />} />
          <Route path="commission/simulator"    element={<CommissionSimulator />} />

          {/* P9: 환수채권 */}
          <Route path="commission/clawback-receivable" element={<ClawbackReceivable />} />

          {/* P7: 수수료 계산 7도메인 */}
          <Route path="commission/income"           element={<IncomeCommission />} />
          <Route path="commission/referral"         element={<ReferralCommission />} />
          <Route path="commission/settling-support" element={<SettlingSupport />} />
          <Route path="commission/recognized"       element={<RecognizedPerformance />} />
          <Route path="commission/award"            element={<Award />} />
          <Route path="commission/life-support"     element={<LifeSupport />} />
          <Route path="commission/branch-allowance" element={<BranchAllowance />} />

          {/* 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/successions"  element={<ContractSuccessions />} />
          <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>
    </Suspense>
  );
}
