import { Suspense, useState, useEffect } from 'react'
import { Routes, Route, Navigate } from 'react-router-dom'
import { Toaster } from 'sonner'
import { useAuthStore } from './store/authStore'
import TopNav from './components/layout/TopNav'
import SidebarNav from './components/layout/SidebarNav'
import MobileTabBar from './components/layout/MobileTabBar'
import OnboardingGuide from './components/OnboardingGuide'
import PortalLayout from './components/layout/PortalLayout'
import PageContainer from './components/layout/PageContainer'
import { CommandPalette } from './components/ui/CommandPalette'
import { SkeletonPage } from './components/ui/Skeleton'
import ErrorBoundary from './components/ui/ErrorBoundary'
import { lazyRetry } from './lib/lazyRetry'

const Login = lazyRetry(() => import('./pages/auth/Login'))
const Register = lazyRetry(() => import('./pages/auth/Register'))
const ForgotPassword = lazyRetry(() => import('./pages/auth/ForgotPassword'))
const Dashboard = lazyRetry(() => import('./pages/Dashboard'))
const Money = lazyRetry(() => import('./pages/Money'))
const SocialInsurance = lazyRetry(() => import('./pages/SocialInsurance'))
const Overtime = lazyRetry(() => import('./pages/Overtime'))
const Roster = lazyRetry(() => import('./pages/Roster'))
const OrgChart = lazyRetry(() => import('./pages/OrgChart'))
const SupportDashboard = lazyRetry(() => import('./pages/support/SupportDashboard'))
const Termination = lazyRetry(() => import('./pages/Termination'))
const AIAssistant = lazyRetry(() => import('./pages/AIAssistant'))
const Settings = lazyRetry(() => import('./pages/Settings'))
const Evidence = lazyRetry(() => import('./pages/Evidence'))
const Policies = lazyRetry(() => import('./pages/Policies'))
const Attendance = lazyRetry(() => import('./pages/Attendance'))
const Schedule = lazyRetry(() => import('./pages/Schedule'))
const Templates = lazyRetry(() => import('./pages/Templates'))
const AuditLog = lazyRetry(() => import('./pages/AuditLog'))
const Notifications = lazyRetry(() => import('./pages/Notifications'))
const PortalLogin = lazyRetry(() => import('./pages/portal/PortalLogin'))
const Payslip = lazyRetry(() => import('./pages/portal/Payslip'))
const MyContract = lazyRetry(() => import('./pages/portal/MyContract'))
const Onboarding = lazyRetry(() => import('./pages/portal/Onboarding'))
const ContractConfirm = lazyRetry(() => import('./pages/portal/ContractConfirm'))
const MyPolicies = lazyRetry(() => import('./pages/portal/MyPolicies'))
const AutoLogin = lazyRetry(() => import('./pages/portal/AutoLogin'))
const MedicalPeriodCalculator = lazyRetry(() => import('./pages/tools/MedicalPeriodCalculator'))
const HealthCheck = lazyRetry(() => import('./pages/tools/HealthCheck'))
const AnnualValueReport = lazyRetry(() => import('./pages/tools/AnnualValueReport'))
const CalendarPage = lazyRetry(() => import('./pages/Calendar'))
const MyAttendance = lazyRetry(() => import('./pages/portal/MyAttendance'))
const MyLeave = lazyRetry(() => import('./pages/portal/MyLeave'))
const SpecialStatus = lazyRetry(() => import('./pages/SpecialStatus'))
const CompanyFiles = lazyRetry(() => import('./pages/CompanyFiles'))
const LeaveApproval = lazyRetry(() => import('./pages/LeaveApproval'))
const TrainingRecords = lazyRetry(() => import('./pages/roster/TrainingRecords'))
const PerformanceRecords = lazyRetry(() => import('./pages/roster/PerformanceRecords'))
const DisciplinaryRecords = lazyRetry(() => import('./pages/roster/DisciplinaryRecords'))

// Sprint 4-5 新增页面
const EmployeeHome = lazyRetry(() => import('./pages/portal/EmployeeHome'))
const OnboardingProgress = lazyRetry(() => import('./pages/portal/OnboardingProgress'))
const ResignationApply = lazyRetry(() => import('./pages/portal/ResignationApply'))
const MyEsign = lazyRetry(() => import('./pages/portal/MyEsign'))
const MyRecords = lazyRetry(() => import('./pages/portal/MyRecords'))
const MyProfile = lazyRetry(() => import('./pages/portal/MyProfile'))
const RiskCenter = lazyRetry(() => import('./pages/compliance/RiskCenter'))
const SalaryDashboard = lazyRetry(() => import('./pages/SalaryDashboard'))
const CommercialInsurance = lazyRetry(() => import('./pages/CommercialInsurance'))
const EmployeeBenefits = lazyRetry(() => import('./pages/EmployeeBenefits'))
const ESign = lazyRetry(() => import('./pages/ESign'))
const CommissionBonus = lazyRetry(() => import('./pages/CommissionBonus'))

// 平台管理端
const PlatformLogin = lazyRetry(() => import('./pages/platform/PlatformLogin'))
const PlatformDashboard = lazyRetry(() => import('./pages/platform/PlatformDashboard'))
const PlatformOrgs = lazyRetry(() => import('./pages/platform/PlatformOrgs'))
const PlatformUsers = lazyRetry(() => import('./pages/platform/PlatformUsers'))
const PlatformSidebar = lazyRetry(() => import('./components/layout/PlatformSidebar'))

function ProtectedRoute({ children }: { children: React.ReactNode }) {
  const isAuthenticated = useAuthStore((s) => s.isAuthenticated)
  if (!isAuthenticated) return <Navigate to="/login" replace />
  return <>{children}</>
}

function PublicRoute({ children }: { children: React.ReactNode }) {
  const isAuthenticated = useAuthStore((s) => s.isAuthenticated)
  if (isAuthenticated) return <Navigate to="/" replace />
  return <>{children}</>
}

function AdminLayout({ children }: { children: React.ReactNode }) {
  const [sidebarOpen, setSidebarOpen] = useState(false)
  return (
    <div className="flex min-h-screen bg-[#f8f9fb]">
      <SidebarNav mobileOpen={sidebarOpen} onClose={() => setSidebarOpen(false)} />
      <div className="flex-1 flex flex-col min-w-0">
        <TopNav onMenuClick={() => setSidebarOpen(true)} />
        <main className="flex-1 py-6 pb-20 md:pb-6">
          <PageContainer>
            <ErrorBoundary>
              <Suspense fallback={<SkeletonPage />}>{children}</Suspense>
            </ErrorBoundary>
          </PageContainer>
        </main>
        <MobileTabBar />
      </div>
      <OnboardingGuide />
    </div>
  )
}

function PlatformRoute({ children }: { children: React.ReactNode }) {
  const user = useAuthStore((s) => s.user)
  const isAuthenticated = useAuthStore((s) => s.isAuthenticated)
  if (!isAuthenticated || user?.role !== 'SUPER_ADMIN') return <Navigate to="/platform/login" replace />
  return <>{children}</>
}

function PlatformLayout({ children }: { children: React.ReactNode }) {
  const [sidebarOpen, setSidebarOpen] = useState(false)
  return (
    <div className="flex min-h-screen bg-[#f8f9fb]">
      <PlatformSidebar mobileOpen={sidebarOpen} onClose={() => setSidebarOpen(false)} />
      <div className="flex-1 flex flex-col min-w-0">
        <header className="h-14 bg-white border-b border-gray-200 flex items-center px-4 shrink-0">
          <button
            className="md:hidden mr-3 text-gray-400"
            onClick={() => setSidebarOpen(true)}
            aria-label="打开菜单"
          >
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
          </button>
          <span className="text-sm text-gray-500">平台管理后台</span>
          <span className="ml-2 px-2 py-0.5 rounded text-[10px] font-bold bg-primary text-white">ADMIN</span>
        </header>
        <main className="flex-1 py-6 px-4 md:px-6">
          <div className="max-w-7xl mx-auto">
            <ErrorBoundary>
              <Suspense fallback={<SkeletonPage />}>{children}</Suspense>
            </ErrorBoundary>
          </div>
        </main>
      </div>
    </div>
  )
}

function PortalLayoutWrapper({ children, showNav = true }: { children: React.ReactNode; showNav?: boolean }) {
  // 检查 portal token 是否存在，不存在则跳转登录页
  const portalToken = localStorage.getItem('portalToken')
  if (!portalToken) {
    window.location.href = '/portal/login'
    return null
  }
  if (!showNav) {
    return (
      <div className="min-h-screen bg-surface pt-safe pb-safe">
        <main className="max-w-md mx-auto py-6 px-4">
          <ErrorBoundary>
            <Suspense fallback={<SkeletonPage />}>{children}</Suspense>
          </ErrorBoundary>
        </main>
      </div>
    )
  }
  return (
    <PortalLayout>
      <ErrorBoundary>
        <Suspense fallback={<SkeletonPage />}>{children}</Suspense>
      </ErrorBoundary>
    </PortalLayout>
  )
}

export default function App() {
  const [cmdOpen, setCmdOpen] = useState(false)
  const isAuthenticated = useAuthStore((s) => s.isAuthenticated)

  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
        e.preventDefault()
        if (isAuthenticated) setCmdOpen(true)
      }
    }
    window.addEventListener('keydown', handler)
    return () => window.removeEventListener('keydown', handler)
  }, [isAuthenticated])

  return (
    <>
    <CommandPalette open={cmdOpen} onClose={() => setCmdOpen(false)} />
    <Routes>
      {/* 管理端认证页面 */}
      <Route path="/login" element={<Suspense fallback={<SkeletonPage />}><PublicRoute><Login /></PublicRoute></Suspense>} />
      <Route path="/register" element={<Suspense fallback={<SkeletonPage />}><PublicRoute><Register /></PublicRoute></Suspense>} />
      <Route path="/forgot-password" element={<Suspense fallback={<SkeletonPage />}><PublicRoute><ForgotPassword /></PublicRoute></Suspense>} />

      {/* 管理端业务页面 */}
      <Route path="/" element={<ProtectedRoute><AdminLayout><Dashboard /></AdminLayout></ProtectedRoute>} />
      <Route path="/roster" element={<ProtectedRoute><AdminLayout><Roster /></AdminLayout></ProtectedRoute>} />
      <Route path="/org-chart" element={<ProtectedRoute><AdminLayout><OrgChart /></AdminLayout></ProtectedRoute>} />
      <Route path="/support" element={<ProtectedRoute><AdminLayout><SupportDashboard /></AdminLayout></ProtectedRoute>} />
      <Route path="/money" element={<ProtectedRoute><AdminLayout><Money /></AdminLayout></ProtectedRoute>} />
      <Route path="/social" element={<ProtectedRoute><AdminLayout><SocialInsurance /></AdminLayout></ProtectedRoute>} />
      <Route path="/overtime" element={<ProtectedRoute><AdminLayout><Overtime /></AdminLayout></ProtectedRoute>} />
      <Route path="/termination" element={<ProtectedRoute><AdminLayout><Termination /></AdminLayout></ProtectedRoute>} />
      <Route path="/ai-assistant" element={<ProtectedRoute><AdminLayout><AIAssistant /></AdminLayout></ProtectedRoute>} />
      <Route path="/settings" element={<ProtectedRoute><AdminLayout><Settings /></AdminLayout></ProtectedRoute>} />
      <Route path="/evidence" element={<ProtectedRoute><AdminLayout><Evidence /></AdminLayout></ProtectedRoute>} />
      <Route path="/policies" element={<ProtectedRoute><AdminLayout><Policies /></AdminLayout></ProtectedRoute>} />
      <Route path="/attendance" element={<ProtectedRoute><AdminLayout><Attendance /></AdminLayout></ProtectedRoute>} />
      <Route path="/schedule" element={<ProtectedRoute><AdminLayout><Schedule /></AdminLayout></ProtectedRoute>} />
      <Route path="/calendar" element={<ProtectedRoute><AdminLayout><CalendarPage /></AdminLayout></ProtectedRoute>} />
      <Route path="/templates" element={<ProtectedRoute><AdminLayout><Templates /></AdminLayout></ProtectedRoute>} />
      <Route path="/audit" element={<ProtectedRoute><AdminLayout><AuditLog /></AdminLayout></ProtectedRoute>} />
      <Route path="/notifications" element={<ProtectedRoute><AdminLayout><Notifications /></AdminLayout></ProtectedRoute>} />
      <Route path="/tools/medical-period" element={<ProtectedRoute><AdminLayout><MedicalPeriodCalculator /></AdminLayout></ProtectedRoute>} />
      <Route path="/tools/health-check" element={<ProtectedRoute><AdminLayout><HealthCheck /></AdminLayout></ProtectedRoute>} />
      <Route path="/tools/annual-value" element={<ProtectedRoute><AdminLayout><AnnualValueReport /></AdminLayout></ProtectedRoute>} />
      <Route path="/special-status" element={<ProtectedRoute><AdminLayout><SpecialStatus /></AdminLayout></ProtectedRoute>} />
      <Route path="/commission-bonus" element={<ProtectedRoute><AdminLayout><CommissionBonus /></AdminLayout></ProtectedRoute>} />
      <Route path="/company-files" element={<ProtectedRoute><AdminLayout><CompanyFiles /></AdminLayout></ProtectedRoute>} />
      <Route path="/leave-approval" element={<ProtectedRoute><AdminLayout><LeaveApproval /></AdminLayout></ProtectedRoute>} />
      <Route path="/training-records" element={<ProtectedRoute><AdminLayout><TrainingRecords /></AdminLayout></ProtectedRoute>} />
      <Route path="/performance-records" element={<ProtectedRoute><AdminLayout><PerformanceRecords /></AdminLayout></ProtectedRoute>} />
      <Route path="/disciplinary-records" element={<ProtectedRoute><AdminLayout><DisciplinaryRecords /></AdminLayout></ProtectedRoute>} />
      <Route path="/risk-center" element={<ProtectedRoute><AdminLayout><RiskCenter /></AdminLayout></ProtectedRoute>} />
      <Route path="/salary-dashboard" element={<ProtectedRoute><AdminLayout><SalaryDashboard /></AdminLayout></ProtectedRoute>} />
      <Route path="/commercial-insurance" element={<ProtectedRoute><AdminLayout><CommercialInsurance /></AdminLayout></ProtectedRoute>} />
      <Route path="/benefits" element={<ProtectedRoute><AdminLayout><EmployeeBenefits /></AdminLayout></ProtectedRoute>} />
      <Route path="/esign" element={<ProtectedRoute><AdminLayout><ESign /></AdminLayout></ProtectedRoute>} />

      {/* 平台管理端 */}
      <Route path="/platform/login" element={<Suspense fallback={<SkeletonPage />}><PlatformLogin /></Suspense>} />
      <Route path="/platform/dashboard" element={<PlatformRoute><PlatformLayout><PlatformDashboard /></PlatformLayout></PlatformRoute>} />
      <Route path="/platform/orgs" element={<PlatformRoute><PlatformLayout><PlatformOrgs /></PlatformLayout></PlatformRoute>} />
      <Route path="/platform/users" element={<PlatformRoute><PlatformLayout><PlatformUsers /></PlatformLayout></PlatformRoute>} />

      {/* 员工端 */}
      <Route path="/portal/login" element={<Suspense fallback={<SkeletonPage />}><PortalLogin /></Suspense>} />
      <Route path="/portal/payslip" element={<PortalLayoutWrapper><Payslip /></PortalLayoutWrapper>} />
      <Route path="/portal/contract" element={<PortalLayoutWrapper><MyContract /></PortalLayoutWrapper>} />
      <Route path="/portal/onboarding" element={<PortalLayoutWrapper showNav={false}><Onboarding /></PortalLayoutWrapper>} />
      <Route path="/portal/contract-confirm" element={<PortalLayoutWrapper showNav={false}><ContractConfirm /></PortalLayoutWrapper>} />
      <Route path="/portal/policies" element={<PortalLayoutWrapper><MyPolicies /></PortalLayoutWrapper>} />
      <Route path="/portal/attendance" element={<PortalLayoutWrapper><MyAttendance /></PortalLayoutWrapper>} />
      <Route path="/portal/leave" element={<PortalLayoutWrapper><MyLeave /></PortalLayoutWrapper>} />
      <Route path="/portal/auto-login" element={<Suspense fallback={<SkeletonPage />}><AutoLogin /></Suspense>} />
      <Route path="/portal/home" element={<PortalLayoutWrapper><EmployeeHome /></PortalLayoutWrapper>} />
      <Route path="/portal/onboarding-progress" element={<PortalLayoutWrapper><OnboardingProgress /></PortalLayoutWrapper>} />
      <Route path="/portal/resignation" element={<PortalLayoutWrapper><ResignationApply /></PortalLayoutWrapper>} />
      <Route path="/portal/esign" element={<PortalLayoutWrapper><MyEsign /></PortalLayoutWrapper>} />
      <Route path="/portal/records" element={<PortalLayoutWrapper><MyRecords /></PortalLayoutWrapper>} />
      <Route path="/portal/profile" element={<PortalLayoutWrapper><MyProfile /></PortalLayoutWrapper>} />

      {/* 兜底 */}
      <Route path="*" element={<Navigate to="/" replace />} />
    </Routes>
    <Toaster position="top-center" richColors closeButton />
    </>
  )
}
