import { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from '@/store';
import { setCredentials, logout as logoutAction, initializeAuth } from '@/store/slices/authSlice';
import { RoleGuard } from '@/features/auth/components/RoleGuard';
import { Routes, Route, Navigate, useLocation, useNavigate, Outlet } from 'react-router-dom';
import { ApplicationFormPage } from '@/components/public/ApplicationFormPage';
import PublicQuestionnairePage from '@/pages/public/PublicQuestionnairePage';
import { LoginPage } from '@/features/auth/pages/LoginPage';
import { ProspectiveLoginPage } from '@/features/auth/pages/ProspectiveLoginPage';
import { Sidebar } from '@/components/layout/Sidebar';
import { Header } from '@/components/layout/Header';
import { Dashboard } from '@/features/dashboard/pages/Dashboard';
import { FinanceDashboard } from '@/features/dashboard/pages/FinanceDashboard';
import { DealerDashboard } from '@/features/dashboard/pages/DealerDashboard';
import { ProspectiveDashboardPage } from '@/features/dashboard/pages/ProspectiveDashboardPage';
import { FDDDashboardPage } from '@/features/dashboard/pages/FDDDashboardPage';
import { FDDApplicationDetails } from '@/features/onboarding/pages/FDDApplicationDetails';
import { ApplicationsPage } from '@/features/onboarding/pages/ApplicationsPage';
import { AllApplicationsPage } from '@/features/onboarding/pages/AllApplicationsPage';
import { OpportunityRequestsPage } from '@/features/onboarding/pages/OpportunityRequestsPage';
import { NonOpportunitiesPage } from '@/features/onboarding/pages/NonOpportunitiesPage';
import { ApplicationDetails } from '@/features/onboarding/pages/ApplicationDetails';
import { ResignationPage } from '@/features/resignation/pages/ResignationPage';
import { TerminationPage } from '@/features/termination/pages/TerminationPage';
import { FnFPage } from '@/features/fnf/pages/FnFPage';
import { ResignationDetails } from '@/features/resignation/pages/ResignationDetails';
import { TerminationDetails } from '@/features/termination/pages/TerminationDetails';
import { FnFDetails } from '@/features/fnf/pages/FnFDetails';
import { FinanceOnboardingPage } from '@/features/onboarding/pages/FinanceOnboardingPage';
import { FinanceFnFPage } from '@/features/fnf/pages/FinanceFnFPage';
import { FinancePaymentDetailsPage } from '@/features/fnf/pages/FinancePaymentDetailsPage';

import { FinanceFnFDetailsPage } from '@/features/fnf/pages/FinanceFnFDetailsPage';
import { MasterPage } from '@/features/master/pages/MasterPage';
import { UserManagementPage } from '@/components/admin/UserManagementPage';
import { ApprovalPoliciesPage } from '@/components/admin/ApprovalPoliciesPage';
import { SLAConfigPage } from '@/features/master/pages/SLAConfigPage';
import { ConstitutionalChangePage } from '@/features/constitutional/pages/ConstitutionalChangePage';
import { ConstitutionalChangeDetails } from '@/features/constitutional/pages/ConstitutionalChangeDetails';
import { RelocationRequestPage } from '@/features/relocation/pages/RelocationRequestPage';
import { RelocationRequestDetails } from '@/features/relocation/pages/RelocationRequestDetails';
import { DealerResignationPage } from '@/features/resignation/pages/DealerResignationPage';
import { DealerResignationDetailsPage } from '@/features/resignation/pages/DealerResignationDetailsPage';
import { DealerConstitutionalChangePage } from '@/features/constitutional/pages/DealerConstitutionalChangePage';
import { DealerRelocationPage } from '@/features/relocation/pages/DealerRelocationPage';
import QuestionnaireBuilder from '@/components/admin/QuestionnaireBuilder';
import QuestionnaireList from '@/components/admin/QuestionnaireList';
import InterviewConfigManagement from '@/features/master/components/InterviewConfigManagement';
import { SystemLogsPage } from '@/features/admin/pages/SystemLogsPage';
import { WorkNotesPage } from '@/features/onboarding/pages/WorkNotesPage';
import { NotificationsPage } from '@/pages/NotificationsPage';
import { Toaster } from '@/components/ui/sonner';
import { User } from '@/lib/mock-data';
import { toast } from 'sonner';
import { API } from '@/api/API';
import { SocketProvider } from '@/context/SocketContext';

// Layout Component
const AppLayout = ({
  onLogout,
  title,
  subtitle,
}: {
  onLogout: () => void;
  title: string;
  subtitle: string;
}) => {
  return (
    <div className="flex h-screen bg-slate-50 overflow-hidden">
      <Sidebar onLogout={onLogout} />
      <div className="flex-1 flex flex-col overflow-hidden">
        <Header title={title} subtitle={subtitle} onRefresh={() => window.location.reload()} />
        <main className="flex-1 overflow-y-auto p-6">
          <Outlet />
        </main>
      </div>
    </div>
  );
};

export default function App() {
  const dispatch = useDispatch<any>();
  const { user: currentUser, isAuthenticated, loading } = useSelector((state: RootState) => state.auth);
  const [showAdminLogin, setShowAdminLogin] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  const currentRole = currentUser?.role || currentUser?.roleCode || '';
  const hasRole = (roles: string[]) => {
    const normalizedTargetRoles = roles.map((r) => r.toLowerCase());
    const userRole = String(currentUser?.role || '').toLowerCase();
    const userRoleCode = String(currentUser?.roleCode || '').toLowerCase();
    return normalizedTargetRoles.includes(userRole) || normalizedTargetRoles.includes(userRoleCode);
  };
  const resignationRoles = ['DD Admin', 'DD_ADMIN', 'ASM', 'RBM', 'DD-ZM', 'DD_ZM', 'DD Lead', 'DD_LEAD', 'DD Head', 'DD_HEAD', 'ZBH', 'NBH', 'Legal', 'Legal Admin', 'LEGAL_ADMIN', 'Super Admin', 'SUPER_ADMIN'];
  const terminationRoles = ['ASM', 'RBM', 'DD-ZM', 'DD_ZM', 'ZBH', 'DD Lead', 'DD_LEAD', 'DD Head', 'DD_HEAD', 'NBH', 'Legal Admin', 'LEGAL_ADMIN', 'Legal', 'DD Admin', 'DD_ADMIN', 'CCO', 'CEO', 'Super Admin', 'SUPER_ADMIN'];
  const fnfRoles = ['DD Admin', 'DD_ADMIN', 'DD-ZM', 'DD_ZM', 'DD Lead', 'DD_LEAD', 'DD Head', 'DD_HEAD', 'NBH', 'Finance', 'Finance Admin', 'FINANCE_ADMIN', 'Super Admin', 'SUPER_ADMIN'];
  const financeRoles = ['Finance', 'Finance Admin'];

  useEffect(() => {
    dispatch(initializeAuth());
  }, [dispatch]);

  const handleLogin = async (email: string, password: string) => {
    try {
      const response = await API.login({ email, password });
      if (response.ok && response.data) {
        const { token, user } = response.data as any;
        localStorage.setItem('token', token);
        const simplifiedUser: User = {
          id: user.id,
          name: user.fullName || email.split('@')[0],
          email: user.email,
          password: password, // Note: storing password in state is not ideal, but keeping existing structure
          role: typeof user.role === 'string' ? user.role : (user.roleCode || 'User')
        };
        dispatch(setCredentials({ user: simplifiedUser, token }));
        toast.success(`Welcome back, ${simplifiedUser.name}!`);
        setShowAdminLogin(false);
      } else {
        const errorMsg = (response.data as any)?.message || 'Invalid credentials';
        toast.error(errorMsg);
      }
    } catch (error) {
      console.error('Login error:', error);
      toast.error('Something went wrong. Please try again.');
    }
  };

  const handleLogout = () => {
    dispatch(logoutAction());
    setShowAdminLogin(false);
    toast.info('Logged out successfully');
    navigate('/');
  };

  // Listen for 401 logout events from API client
  useEffect(() => {
    const onLogout = () => {
      handleLogout();
      toast.error('Session expired. Please login again.');
    };
    window.addEventListener('auth:logout', onLogout);
    return () => window.removeEventListener('auth:logout', onLogout);
  }, [dispatch, navigate]);

  // Helper to determine page title based on path
  const getPageTitle = (pathname: string) => {
    if (pathname.startsWith('/applications/') && pathname.length > 14) return 'Application Details';
    if (pathname.startsWith('/resignation/') && !pathname.startsWith('/dealer-resignation')) return 'Resignation Details';
    if (pathname.startsWith('/dealer-resignation/')) return 'Resignation Request Details';
    if (pathname.startsWith('/termination/')) return 'Termination Details';
    if (pathname.startsWith('/fnf/')) return 'F&F Request Details';
    if (pathname.startsWith('/constitutional-change/')) return 'Constitutional Change Details';
    if (pathname.startsWith('/relocation-requests/')) return 'Relocation Request Details';
    if (pathname.startsWith('/finance-onboarding/')) return 'Payment Details';
    if (pathname.startsWith('/finance-audit/')) return 'Finance Audit';
    if (pathname.startsWith('/finance-fnf/')) return 'F&F Settlement Details';
    if (pathname.startsWith('/fdd-details/')) return 'FDD Audit Workspace';
    if (pathname.startsWith('/questionnaire-builder/')) return 'Questionnaire Builder';
    if (pathname.startsWith('/worknotes/')) return 'Work Notes';
    const titles: Record<string, string> = {
      '/dashboard': 'Dashboard',
      '/applications': 'Dealership Requests',
      '/all-applications': 'All Applications',
      '/opportunity-requests': 'Opportunity Requests',
      '/non-opportunities': 'Non-opportunities',
      '/tasks': 'My Tasks',
      '/reports': 'Reports & Analytics',
      '/settings': 'Settings',
      '/users': 'User Management',
      '/resignation': 'Resignation Management',
      '/termination': 'Termination Management',
      '/fnf': 'Full & Final Settlement',
      '/finance-onboarding': 'Payment Verification',
      '/finance-fnf': 'F&F Financial Settlement',
      '/master': 'Master Configuration',
      '/constitutional-change': 'Constitutional Change',
      '/relocation-requests': 'Relocation Requests',
      '/dealer-resignation': 'Dealer Resignation Management',
      '/dealer-constitutional': 'Dealer Constitutional Change',
      '/dealer-relocation': 'Dealer Relocation Requests',
      '/questionnaire-builder': 'Questionnaire Builder',
      '/approval-policies': 'Approval Policies',
      '/fdd-dashboard': 'FDD Dashboard',
      '/fdd-details': 'Audit Workspace',
      '/questions': 'Questionnaires',
      '/questionnaires': 'Questionnaire Templates',
      '/interview-configs': 'Interview Configuration',
      '/system-logs': 'System Logs',
      '/sla-configurations': 'SLA Matrix',
      '/notifications': 'Notifications',
    };
    return titles[pathname] || 'Dashboard';
  };

  /** Short context line under the main header title — varies by route (and sometimes role). */
  const getPageSubtitle = (pathname: string, role: string) => {
    const rl = (role || '').toLowerCase();
    const isDealerRole = rl === 'dealer' || rl.includes('dealer');
    const isFinanceRole = rl.includes('finance');

    if (pathname.startsWith('/worknotes/')) {
      return 'Collaborative notes and clarifications linked to this onboarding or offboarding record.';
    }
    if (pathname.startsWith('/applications/') && pathname !== '/applications') {
      return 'Review stages, documents, interviews, and decisions for this single dealership onboarding application.';
    }
    if (pathname === '/applications') {
      return 'Search, filter, and open dealership applications your role can work on.';
    }
    if (pathname === '/all-applications') {
      return 'Cross-team view of every dealership application in the pipeline.';
    }
    if (pathname === '/opportunity-requests') {
      return 'Applications tied to an opportunity location for DD prioritisation.';
    }
    if (pathname === '/non-opportunities') {
      return 'Applications without a mapped opportunity; track for future reference or follow-up.';
    }
    if (pathname === '/dashboard') {
      if (isDealerRole) {
        return 'Your home for outlet actions: constitutional change (how your business is legally registered), relocation, and resignation requests.';
      }
      if (isFinanceRole) {
        return 'Payment verification, finance audits, and F&F settlement work for dealership accounts.';
      }
      return 'Operational snapshot for dealership onboarding: workloads, alerts, and shortcuts for your role.';
    }
    if (pathname.startsWith('/dealer-resignation/')) {
      return 'Read-only summary of the resignation you submitted for this outlet.';
    }
    if (pathname === '/dealer-resignation') {
      return 'Start a new outlet resignation or open a request you already submitted.';
    }
    if (pathname === '/dealer-constitutional') {
      return 'Constitutional change updates your outlet’s registered legal structure (for example sole proprietorship to private limited). Submit one request per outlet; Royal Enfield teams review documents and approve before records change.';
    }
    if (pathname === '/dealer-relocation') {
      return 'Request a move of your dealership to a new address or territory, and track requests in progress.';
    }
    if (pathname.startsWith('/constitutional-change/')) {
      return 'Review evidence, comments, and workflow for this constitutional change case.';
    }
    if (pathname === '/constitutional-change') {
      return 'Process dealer requests to change registered legal constitution, supporting documents, and approvals.';
    }
    if (pathname.startsWith('/relocation-requests/')) {
      return 'Assess feasibility, documents, and approvals for this relocation request.';
    }
    if (pathname === '/relocation-requests') {
      return 'Manage dealer relocation proposals: new sites, handovers, and compliance checks.';
    }
    if (pathname.startsWith('/resignation/') && !pathname.startsWith('/dealer-resignation')) {
      return 'HR workflow: clearances, handovers, and settlement steps for this resignation.';
    }
    if (pathname === '/resignation') {
      return 'Queue of dealership resignation cases across your authorised outlets.';
    }
    if (pathname.startsWith('/termination/')) {
      return 'Contractual exit details, evidence, and approvals for this termination case.';
    }
    if (pathname === '/termination') {
      return 'Monitor dealership terminations, disputes, and mandated approvals.';
    }
    if (pathname.startsWith('/fnf/')) {
      return 'Line items, deductions, and payout status for this full & final settlement.';
    }
    if (pathname === '/fnf') {
      return 'Track F&F batches from clearance through finance payout.';
    }
    if (pathname.startsWith('/finance-onboarding/')) {
      return 'Payment schedule, proofs, and audit notes for this onboarding application.';
    }
    if (pathname === '/finance-onboarding') {
      return 'Validate security deposits, first fills, and related onboarding payments.';
    }
    if (pathname.startsWith('/finance-audit/')) {
      return 'Finance audit trail and checklist for this application.';
    }
    if (pathname.startsWith('/finance-fnf/')) {
      return 'Settlement calculations and release steps for this F&F record.';
    }
    if (pathname === '/finance-fnf') {
      return 'Finance queue for F&F approvals and disbursements.';
    }
    if (pathname.startsWith('/fdd-details/')) {
      return 'Field Development Director audit workspace for this application.';
    }
    if (pathname === '/fdd-dashboard') {
      return 'FDD workload: audits due, flags raised, and follow-up actions.';
    }
    if (pathname.startsWith('/questionnaire-builder/') || pathname === '/questionnaire-builder') {
      return 'Author and publish questionnaire versions used in dealership assessments.';
    }
    if (pathname === '/questionnaires' || pathname === '/questions') {
      return 'List of published questionnaire templates and versions.';
    }
    if (pathname === '/master') {
      return 'Hierarchy, geography, templates, and reference data shared across onboarding.';
    }
    if (pathname === '/users') {
      return 'Create and maintain internal users, roles, and access for this portal.';
    }
    if (pathname === '/approval-policies') {
      return 'Configure who must approve each onboarding stage or document type.';
    }
    if (pathname === '/sla-configurations') {
      return 'Define turnaround targets and escalations for onboarding milestones.';
    }
    if (pathname === '/interview-configs') {
      return 'Set up interview templates, panels, and scoring used during selection.';
    }
    if (pathname === '/system-logs') {
      return 'Immutable record of configuration and administrative actions for compliance.';
    }
    if (pathname === '/notifications') {
      return 'System and workflow alerts for your account.';
    }
    if (pathname === '/tasks') {
      return 'Tasks assigned to you (placeholder module).';
    }
    if (pathname === '/reports') {
      return 'Analytics and exports for onboarding performance (placeholder module).';
    }
    if (pathname === '/settings') {
      return 'Profile, notifications, and security preferences for your account.';
    }

    const title = getPageTitle(pathname);
    return title === 'Dashboard'
      ? 'Operational snapshot for dealership onboarding: workloads, alerts, and shortcuts for your role.'
      : `You are viewing: ${title}.`;
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen bg-slate-50">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-red-600"></div>
      </div>
    );
  }

  // Public Routes
  if (!isAuthenticated) {
    return (
      <>
        <Routes>
          <Route path="/admin-login" element={<LoginPage onLogin={handleLogin} />} />
          <Route path="/prospective-login" element={<ProspectiveLoginPage />} />
          <Route path="/questionnaire/:applicationId" element={<PublicQuestionnairePage />} />
          <Route path="*" element={showAdminLogin ? <LoginPage onLogin={handleLogin} /> :
            <ApplicationFormPage onAdminLogin={() => setShowAdminLogin(true)} />}
          />
        </Routes>
        <Toaster />
      </>
    )
  }

  // Protected Routes
  return (
    <SocketProvider>
      <Routes>
        {/* Prospective Dealer Route - STRICTLY ISOLATED */}
        <Route
          path="/prospective-dashboard/*"
          element={
            <RoleGuard allowedRoles={['Prospective Dealer']}>
              <ProspectiveDashboardPage />
            </RoleGuard>
          }
        />



        {/* Internal & Dealer Routes - EXCLUDES Prospective Dealers */}
        <Route element={
          <RoleGuard excludeRoles={['Prospective Dealer']} redirectTo="/prospective-dashboard">
            <AppLayout
              onLogout={handleLogout}
              title={getPageTitle(location.pathname)}
              subtitle={getPageSubtitle(location.pathname, currentRole)}
            />
          </RoleGuard>
        }>
          <Route path="/" element={<Navigate to="/dashboard" replace />} />

          {/* Dashboards */}
          <Route path="/dashboard" element={
            hasRole(financeRoles) ?
              <FinanceDashboard currentUser={currentUser} onNavigate={(path: string) => navigate(`/${path}`)} onViewPaymentDetails={(id: string) => navigate(`/finance-onboarding/${id}`)} onViewAuditDetails={(id: string) => navigate(`/finance-audit/${id}`)} onViewFnFDetails={(id: string) => navigate(`/finance-fnf/${id}`)} /> :
              hasRole(['Dealer']) ?
                <DealerDashboard currentUser={currentUser} onNavigate={(path: string) => navigate(`/${path}`)} /> :
                <Dashboard onNavigate={(path: string) => navigate(`/${path}`)} />
          } />

          {/* Applications */}
          <Route path="/applications" element={<ApplicationsPage onViewDetails={(id: string) => navigate(`/applications/${id}`)} initialFilter="all" />} />
          <Route path="/applications/:id" element={<ApplicationDetails />} />
          
          {/* Centralized Work Notes Route */}
          <Route path="/worknotes/:type/:id" element={
            <WorkNotesPage
              onBack={() => window.history.back()}
            />
          } />

          {/* All Applications */}
          <Route path="/all-applications" element={
            hasRole(['DD', 'DD Admin', 'Super Admin']) ? <AllApplicationsPage onViewDetails={(id: string) => navigate(`/applications/${id}`)} initialFilter="all" /> : <Navigate to="/dashboard" />
          } />

          {/* FDD Routes - Integrated into Layout */}
          <Route path="/fdd-dashboard" element={<FDDDashboardPage />} />
          <Route path="/fdd-details/:id" element={<FDDApplicationDetails />} />

          {/* Admin/Lead Routes */}
          <Route path="/opportunity-requests" element={<OpportunityRequestsPage onViewDetails={(id: string) => navigate(`/applications/${id}`)} />} />
          <Route path="/non-opportunities" element={<NonOpportunitiesPage onViewDetails={(id: string) => navigate(`/applications/${id}`)} />} />

          {/* Other Modules */}
          <Route path="/users" element={<UserManagementPage />} />
          <Route path="/notifications" element={<NotificationsPage />} />
          <Route path="/approval-policies" element={
            (hasRole(['Super Admin', 'DD Admin']))
              ? <ApprovalPoliciesPage />
              : <Navigate to="/dashboard" />
          } />
          <Route path="/sla-configurations" element={
            (hasRole(['Super Admin', 'DD Admin', 'DD Lead']))
              ? <SLAConfigPage />
              : <Navigate to="/dashboard" />
          } />
          <Route path="/master" element={<MasterPage />} />
          <Route path="/questions" element={<QuestionnaireList />} />
          <Route path="/questionnaire-builder" element={<QuestionnaireBuilder />} />
          <Route path="/questionnaire-builder/:id" element={<QuestionnaireBuilder />} />
          <Route path="/questionnaires" element={<QuestionnaireList />} />
          <Route path="/interview-configs" element={
            hasRole(['Super Admin', 'DD Admin', 'DD Head'])
              ? <InterviewConfigManagement />
              : <Navigate to="/dashboard" />
          } />
          <Route path="/system-logs" element={
            hasRole(['Super Admin'])
              ? <SystemLogsPage />
              : <Navigate to="/dashboard" />
          } />

          {/* HR/Finance Modules (Simplified for brevity, following pattern) */}
          <Route path="/resignation" element={
            hasRole(resignationRoles)
              ? <ResignationPage currentUser={currentUser} onViewDetails={(id: string) => navigate(`/resignation/${id}`)} />
              : <Navigate to="/dashboard" />
          } />
          <Route path="/resignation/:id" element={
            hasRole(resignationRoles)
              ? <ResignationDetails resignationId={window.location.pathname.split('/').pop() || ''} onBack={() => navigate('/resignation')} currentUser={currentUser} />
              : <Navigate to="/dashboard" />
          } />

          <Route path="/termination" element={
            hasRole(terminationRoles)
              ? <TerminationPage currentUser={currentUser} onViewDetails={(id: string) => navigate(`/termination/${id}`)} />
              : <Navigate to="/dashboard" />
          } />
          <Route path="/termination/:id" element={
            hasRole(terminationRoles)
              ? <TerminationDetails terminationId={window.location.pathname.split('/').pop() || ''} onBack={() => navigate('/termination')} currentUser={currentUser} />
              : <Navigate to="/dashboard" />
          } />

          <Route path="/fnf" element={
            hasRole(fnfRoles)
              ? <FnFPage currentUser={currentUser} onViewDetails={(id: string) => navigate(`/fnf/${id}`)} />
              : <Navigate to="/dashboard" />
          } />
          <Route path="/fnf/:id" element={
            hasRole(fnfRoles)
              ? <FnFDetails fnfId={window.location.pathname.split('/').pop() || ''} onBack={() => navigate('/fnf')} currentUser={currentUser} />
              : <Navigate to="/dashboard" />
          } />

          <Route path="/finance-onboarding" element={
            hasRole(financeRoles)
              ? <FinanceOnboardingPage onViewPaymentDetails={(id: string) => navigate(`/finance-onboarding/${id}`)} onViewAuditDetails={(id: string) => navigate(`/finance-audit/${id}`)} />
              : <Navigate to="/dashboard" />
          } />
          <Route path="/finance-onboarding/:id" element={
            hasRole(financeRoles)
              ? <FinancePaymentDetailsPage applicationId={window.location.pathname.split('/').pop() || ''} onBack={() => navigate('/finance-onboarding')} />
              : <Navigate to="/dashboard" />
          } />
          <Route path="/finance-audit/:id" element={<ApplicationDetails />} />

          <Route path="/finance-fnf" element={
            hasRole(financeRoles)
              ? <FinanceFnFPage onViewFnFDetails={(id: string) => navigate(`/finance-fnf/${id}`)} />
              : <Navigate to="/dashboard" />
          } />
          <Route path="/finance-fnf/:id" element={
            hasRole(financeRoles)
              ? <FinanceFnFDetailsPage fnfId={window.location.pathname.split('/').pop() || ''} onBack={() => navigate('/finance-fnf')} />
              : <Navigate to="/dashboard" />
          } />

          <Route path="/constitutional-change" element={<ConstitutionalChangePage currentUser={currentUser} onViewDetails={(id: string) => navigate(`/constitutional-change/${id}`)} />} />
          <Route path="/constitutional-change/:id" element={<ConstitutionalChangeDetails requestId={window.location.pathname.split('/').pop() || ''} onBack={() => navigate('/constitutional-change')} currentUser={currentUser} />} />

          <Route path="/relocation-requests" element={<RelocationRequestPage currentUser={currentUser} onViewDetails={(id: string) => navigate(`/relocation-requests/${id}`)} />} />
          <Route path="/relocation-requests/:id" element={<RelocationRequestDetails requestId={window.location.pathname.split('/').pop() || ''} onBack={() => navigate('/relocation-requests')} currentUser={currentUser} />} />

          {/* Dealer Routes */}
          <Route path="/dealer-resignation" element={<DealerResignationPage currentUser={currentUser} onViewDetails={(id: string) => navigate(`/dealer-resignation/${id}`)} />} />
          <Route path="/dealer-resignation/:id" element={
            hasRole(['Dealer'])
              ? <DealerResignationDetailsPage resignationId={window.location.pathname.split('/').pop() || ''} onBack={() => navigate('/dealer-resignation')} />
              : <Navigate to="/dashboard" />
          } />
          <Route path="/dealer-constitutional" element={<DealerConstitutionalChangePage currentUser={currentUser} onViewDetails={(id: string) => navigate(`/constitutional-change/${id}`)} />} />
          <Route path="/dealer-relocation" element={<DealerRelocationPage currentUser={currentUser} onViewDetails={(id: string) => navigate(`/relocation-requests/${id}`)} />} />

          {/* Placeholder Routes */}
          <Route path="/tasks" element={
            <div className="bg-white rounded-lg border border-slate-200 p-8 text-center">
              <h2 className="text-slate-900 mb-2">My Tasks</h2>
              <p className="text-slate-600">Task management interface would be displayed here</p>
              <p className="text-slate-500 mt-4">Shows applications assigned to the current user</p>
            </div>
          } />
          <Route path="/reports" element={
            <div className="bg-white rounded-lg border border-slate-200 p-8 text-center">
              <h2 className="text-slate-900 mb-2">Reports & Analytics</h2>
              <p className="text-slate-600">Advanced reporting and analytics dashboard</p>
              <p className="text-slate-500 mt-4">Charts, export capabilities, and custom filters</p>
            </div>
          } />
          <Route path="/settings" element={
            <div className="bg-white rounded-lg border border-slate-200 p-8">
              <h2 className="text-slate-900 mb-4">Settings</h2>
              <div className="space-y-4">
                <div>
                  <h3 className="text-slate-900 mb-2">Profile Settings</h3>
                  <p className="text-slate-600">Update your profile information and preferences</p>
                </div>
                <div>
                  <h3 className="text-slate-900 mb-2">Notification Preferences</h3>
                  <p className="text-slate-600">Configure email and system notifications</p>
                </div>
                <div>
                  <h3 className="text-slate-900 mb-2">Security</h3>
                  <p className="text-slate-600">Change password and manage security settings</p>
                </div>
              </div>
            </div>
          } />

          {/* Fallback */}
          <Route path="*" element={<Navigate to="/dashboard" replace />} />
        </Route>
      </Routes>
      <Toaster />
    </SocketProvider>
  );
}
