/**
 * App.tsx
 *
 * Haupt-App-Komponente mit Multi-Tenant Router-Setup.
 *
 * URL-Struktur:
 * - /                                    → Dashboard/Übersicht
 * - /settings                            → Benutzer-Einstellungen
 * - /gdpr                                → GDPR / Datenschutz
 * - /mandates/:mandateId/:featureCode/:instanceId/* → Feature-Instanz-Routen
 * - /admin/*                             → System-Administration (nur SysAdmin)
 */

import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { useEffect } from 'react';

// Import global CSS reset first
import './index.css';

// Auth Pages (Public)
import Login from './pages/Login';
import Register from './pages/Register';
import PasswordResetRequest from './pages/PasswordResetRequest';
import Reset from './pages/Reset';
import { InvitePage } from './pages/InvitePage';

// Providers
import { AuthProvider } from './providers/auth/AuthProvider';
import { ProtectedRoute } from './providers/auth/ProtectedRoute';
import { LanguageProvider } from './providers/language/LanguageContext';
import { ToastProvider } from './contexts/ToastContext';
import { WorkflowSelectionProvider } from './contexts/WorkflowSelectionContext';
import { FileProvider } from './contexts/FileContext';
import { MainLayout } from './layouts/MainLayout';
import { FeatureLayout } from './layouts/FeatureLayout';
import { DashboardPage } from './pages/Dashboard';
import { SettingsPage } from './pages/Settings';
import { GDPRPage } from './pages/GDPR';
import StorePage from './pages/Store';
import { IntegrationsOverviewPage } from './pages/IntegrationsOverviewPage';
import { FeatureViewPage } from './pages/FeatureView';
import { AccessManagementHub, AdminMandatesPage, AdminUsersPage, AdminUserMandatesPage, AdminFeatureAccessPage, AdminInvitationsPage, AdminMandateRolesPage, AdminFeatureRolesPage, AdminFeatureInstanceUsersPage, AdminMandateRolePermissionsPage, AdminUserAccessOverviewPage, AdminLogsPage, AdminDemoConfigPage } from './pages/admin';
import { AdminMandateWizardPage, AdminInvitationWizardPage } from './pages/admin/wizards';
import { PromptsPage, FilesPage, ConnectionsPage } from './pages/basedata';
import { BillingDataView, BillingAdmin, BillingMandateView, AdminSubscriptionsPage } from './pages/billing';
import { AutomationsDashboardPage } from './pages/AutomationsDashboardPage';
import { ComplianceAuditPage } from './pages/ComplianceAuditPage';
function App() {
    // Load saved theme preference and set app name on app mount
    useEffect(() => {
        // Set app name globally using configuration
        import('../config/config').then(({ getAppName }) => {
            const appName = getAppName();
            document.title = appName;
        });
        
        // Load saved theme preference
        const savedTheme = localStorage.getItem('theme');
        const prefersDark = savedTheme === 'dark' || (!savedTheme && window.matchMedia('(prefers-color-scheme: dark)').matches);
        
        if (prefersDark) {
            document.documentElement.classList.add('dark-theme');
            document.documentElement.classList.remove('light-theme');
        } else {
            document.documentElement.classList.add('light-theme');
            document.documentElement.classList.remove('dark-theme');
        }
        document.documentElement.setAttribute('data-theme', prefersDark ? 'dark' : 'light');
    }, []);
    
    return (
        <LanguageProvider>
            <AuthProvider>
                <ToastProvider>
                    <WorkflowSelectionProvider>
                    <Router>
                        <Routes>
                        {/* ================================================== */}
                        {/* PUBLIC AUTH ROUTES - NO AUTHENTICATION REQUIRED    */}
                        {/* ================================================== */}
                        <Route path="/login" element={<Login />} />
                        <Route path="/register" element={<Register />} />
                        <Route path="/password-reset-request" element={<PasswordResetRequest />} />
                        <Route path="/reset" element={<Reset />} />
                        <Route path="/invite/:token" element={<InvitePage />} />
                        
                        {/* ================================================== */}
                        {/* PROTECTED ROUTES - REQUIRE AUTHENTICATION          */}
                        {/* ================================================== */}
                        <Route path="/" element={
                            <ProtectedRoute>
                                <FileProvider>
                                <MainLayout />
                                </FileProvider>
                            </ProtectedRoute>
                        }>
                            {/* Dashboard (Root) */}
                            <Route index element={<DashboardPage />} />
                            
                            {/* System-Seiten (ohne Instanz-Kontext) */}
                            <Route path="store" element={<StorePage />} />
                            <Route path="integrations" element={<IntegrationsOverviewPage />} />
                            <Route path="compliance-audit" element={<ComplianceAuditPage />} />
                            <Route path="settings" element={<SettingsPage />} />
                            <Route path="gdpr" element={<GDPRPage />} />
                            
                            {/* ============================================== */}
                            {/* BASISDATEN ROUTES (global)                     */}
                            {/* ============================================== */}
                            <Route path="basedata">
                                <Route path="prompts" element={<PromptsPage />} />
                                <Route path="files" element={<FilesPage />} />
                                <Route path="connections" element={<ConnectionsPage />} />
                            </Route>
                            
                            {/* ============================================== */}
                            {/* BILLING ROUTES                                 */}
                            {/* ============================================== */}
                            <Route path="billing">
                                <Route index element={<Navigate to="/billing/transactions" replace />} />
                                <Route path="transactions" element={<BillingDataView />} />
                                <Route path="admin" element={<BillingAdmin />} />
                            </Route>
                            
                            {/* ============================================== */}
                            {/* AUTOMATIONS DASHBOARD                          */}
                            {/* ============================================== */}
                            <Route path="automations" element={<AutomationsDashboardPage />} />
                            
                            {/* Legacy top-level routes – redirect to dashboard (migrated to feature-instance routes) */}
                            <Route path="chatbot" element={<Navigate to="/" replace />} />
                            <Route path="pek" element={<Navigate to="/" replace />} />
                            <Route path="speech" element={<Navigate to="/" replace />} />
                            
                            {/* ============================================== */}
                            {/* FEATURE-INSTANZ ROUTES                         */}
                            {/* /mandates/:mandateId/:featureCode/:instanceId  */}
                            {/* ============================================== */}
                            <Route 
                                path="mandates/:mandateId/:featureCode/:instanceId" 
                                element={<FeatureLayout />}
                            >
                                {/* Feature Views - dynamisch basierend auf featureCode */}
                                <Route index element={<FeatureViewPage view="dashboard" />} />
                                <Route path="dashboard" element={<FeatureViewPage view="dashboard" />} />
                                <Route path="organisations" element={<FeatureViewPage view="organisations" />} />
                                <Route path="contracts" element={<FeatureViewPage view="contracts" />} />
                                <Route path="documents" element={<FeatureViewPage view="documents" />} />
                                <Route path="positions" element={<FeatureViewPage view="positions" />} />
                                <Route path="roles" element={<FeatureViewPage view="roles" />} />
                                <Route path="access" element={<FeatureViewPage view="access" />} />
                                <Route path="runs" element={<FeatureViewPage view="runs" />} />
                                <Route path="files" element={<FeatureViewPage view="files" />} />
                                <Route path="conversations" element={<FeatureViewPage view="conversations" />} />
                                <Route path="upload" element={<FeatureViewPage view="upload" />} />
                                <Route path="chat" element={<FeatureViewPage view="chat" />} />
                                <Route path="threads" element={<FeatureViewPage view="threads" />} />
                                <Route path="position-documents" element={<FeatureViewPage view="position-documents" />} />
                                <Route path="expense-import" element={<FeatureViewPage view="expense-import" />} />
                                <Route path="scan-upload" element={<FeatureViewPage view="scan-upload" />} />
                                <Route path="instance-roles" element={<FeatureViewPage view="instance-roles" />} />
                                <Route path="analyse" element={<FeatureViewPage view="analyse" />} />
                                <Route path="abschluss" element={<FeatureViewPage view="abschluss" />} />
                                
                                {/* Automation Feature Views */}
                                <Route path="definitions" element={<FeatureViewPage view="definitions" />} />
                                <Route path="templates" element={<FeatureViewPage view="templates" />} />
                                <Route path="logs" element={<FeatureViewPage view="logs" />} />
                                
                                {/* Workspace + Automation2 Editor */}
                                <Route path="editor" element={<FeatureViewPage view="editor" />} />
                                <Route path="rag-insights" element={<FeatureViewPage view="rag-insights" />} />
                                
                                {/* Automation2 Workflows & Tasks */}
                                <Route path="workflows" element={<FeatureViewPage view="workflows" />} />
                                <Route path="workflows-tasks" element={<FeatureViewPage view="workflows-tasks" />} />
                                
                                {/* Teams Bot Feature Views */}
                                <Route path="sessions" element={<FeatureViewPage view="sessions" />} />
                                <Route path="settings" element={<FeatureViewPage view="settings" />} />
                                
                                {/* Neutralization Feature Views */}
                                <Route path="playground" element={<FeatureViewPage view="playground" />} />
                                
                                {/* CommCoach Feature Views */}
                                <Route path="coaching" element={<FeatureViewPage view="coaching" />} />
                                <Route path="dossier" element={<FeatureViewPage view="dossier" />} />
                                
                                {/* Catch-all für unbekannte Sub-Pfade */}
                                <Route path="*" element={<FeatureViewPage view="not-found" />} />
                            </Route>
                            
                            {/* ============================================== */}
                            {/* ADMIN ROUTES (nur SysAdmin)                    */}
                            {/* ============================================== */}
                            <Route path="admin">
                                <Route index element={<Navigate to="/admin/access" replace />} />
                                <Route path="mandates" element={<AdminMandatesPage />} />
                                <Route path="users" element={<AdminUsersPage />} />
                                <Route path="user-mandates" element={<AdminUserMandatesPage />} />
                                <Route path="access" element={<AccessManagementHub />} />
                                <Route path="feature-instances" element={<AdminFeatureAccessPage />} />
                                <Route path="feature-roles" element={<AdminFeatureRolesPage />} />
                                <Route path="feature-users" element={<AdminFeatureInstanceUsersPage />} />
                                <Route path="invitations" element={<AdminInvitationsPage />} />
                                <Route path="mandate-roles" element={<AdminMandateRolesPage />} />
                                <Route path="mandate-role-permissions" element={<AdminMandateRolePermissionsPage />} />
                                <Route path="user-access-overview" element={<AdminUserAccessOverviewPage />} />
                                <Route path="billing">
                                    <Route index element={<Navigate to="/billing/admin" replace />} />
                                    <Route path="mandates" element={<BillingMandateView />} />
                                </Route>
                                <Route path="subscriptions" element={<AdminSubscriptionsPage />} />
                                <Route path="logs" element={<AdminLogsPage />} />
                                <Route path="languages" element={null} />
                                <Route path="demo-config" element={<AdminDemoConfigPage />} />
                                <Route path="mandate-wizard" element={<AdminMandateWizardPage />} />
                                <Route path="invitation-wizard" element={<AdminInvitationWizardPage />} />
                            </Route>
                        </Route>
                        
                        {/* ================================================== */}
                        {/* CATCH-ALL - Redirect to Dashboard                  */}
                        {/* ================================================== */}
                        <Route path="*" element={
                            <ProtectedRoute>
                                <MainLayout />
                            </ProtectedRoute>
                        } />
                        </Routes>
                    </Router>
                    </WorkflowSelectionProvider>
                </ToastProvider>
            </AuthProvider>
        </LanguageProvider>
    );
}

export default App;
