import React from 'react'
import {
  RouterProvider,
  createBrowserRouter,
  Navigate,
  NavLink,
  useLocation,
  Outlet,
} from 'react-router-dom'
import { AuthProvider, useAuth } from './context/AuthContext'
import { ToastProvider } from './context/ToastContext'
import { OrgInboxProvider, useOrgInbox } from './context/OrgInboxContext'
import DesktopSidebar from './components/DesktopSidebar'
import { getMainNavItems } from './config/appNav'
import LoginPage from './pages/LoginPage'
import VerifyPage from './pages/VerifyPage'
import Dashboard from './pages/Dashboard'
import AccountSettingsPage from './pages/AccountSettingsPage'
import SettingsSystemInfoPage from './pages/SettingsSystemInfoPage'
import ExercisesListPage from './pages/ExercisesListPage'
import ExerciseDetailPage from './pages/ExerciseDetailPage'
import ExerciseFormPage from './pages/ExerciseFormPage'
import ClubsPage from './pages/ClubsPage'
import InboxPage from './pages/InboxPage'
import SkillsPage from './pages/SkillsPage'
import TrainingPlanningPage from './pages/TrainingPlanningPage'
import TrainingFrameworkProgramsListPage from './pages/TrainingFrameworkProgramsListPage'
import TrainingFrameworkProgramEditPage from './pages/TrainingFrameworkProgramEditPage'
import TrainingModulesListPage from './pages/TrainingModulesListPage'
import TrainingModuleEditPage from './pages/TrainingModuleEditPage'
import TrainingUnitRunPage from './pages/TrainingUnitRunPage'
import TrainingCoachPage from './pages/TrainingCoachPage'
import AdminCatalogsPage from './pages/AdminCatalogsPage'
import AdminHierarchyPage from './pages/AdminHierarchyPage'
import AdminMaturityModelsPage from './pages/AdminMaturityModelsPage'
import TrainerContextsPage from './pages/TrainerContextsPage'
import MediaWikiImportPage from './pages/MediaWikiImportPage'
import AdminUsersPage from './pages/AdminUsersPage'
import AdminHomeRedirect from './components/AdminHomeRedirect'
import PlatformAdminRoute from './components/PlatformAdminRoute'
import MediaLibraryPage from './pages/MediaLibraryPage'
import LegalPage from './pages/LegalPage'
import AdminLegalDocumentsPage from './pages/AdminLegalDocumentsPage'
import SettingsLegalPage from './pages/SettingsLegalPage'
import ActiveClubSwitcher from './components/ActiveClubSwitcher'
import InactiveMembershipBanner from './components/InactiveMembershipBanner'
import './app.css'

/** Shield „Admin“: nur Super-Admin (global). Vereinsorga: Vereine → Mitglieder. */
function computeShowAdminNav(currentUser) {
  return currentUser?.role === 'superadmin'
}

// Bottom Navigation (Mobile)
function Nav({ showAdminNav }) {
  const { canAccessOrgInbox, inboxCount } = useOrgInbox()
  const items = getMainNavItems(showAdminNav, { showInbox: canAccessOrgInbox })
  const loc = useLocation()

  const navItemActive = (pathname, item, routerIsActive) => {
    if (item.to.startsWith('/admin')) return pathname.startsWith('/admin')
    return routerIsActive
  }

  return (
    <nav className="bottom-nav">
      {items.map((item) => (
        <NavLink
          key={item.to}
          to={item.to}
          end={!!item.end}
          className={({ isActive }) =>
            'nav-item' + (navItemActive(loc.pathname, item, isActive) ? ' active' : '')
          }
        >
          <item.Icon size={26} strokeWidth={2} />
          {item.to === '/inbox' && inboxCount > 0 ? (
            <span className="nav-item__badge" aria-label={`${inboxCount} offen`}>
              {inboxCount > 99 ? '99+' : inboxCount}
            </span>
          ) : null}
          <span>{item.shortLabel || item.label}</span>
        </NavLink>
      ))}
    </nav>
  )
}

function ProtectedLayout() {
  const { isAuthenticated, loading, user, logout } = useAuth()

  const handleLogout = () => {
    if (confirm('Wirklich abmelden?')) {
      logout()
      window.location.href = '/'
    }
  }

  if (loading) {
    return (
      <div
        style={{
          minHeight: '100vh',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          background: 'var(--bg)',
        }}
      >
        <div className="spinner"></div>
      </div>
    )
  }

  if (!isAuthenticated) {
    return <Navigate to="/login" replace />
  }

  const showAdminNav = computeShowAdminNav(user)

  return (
    <OrgInboxProvider user={user}>
      <DesktopSidebar showAdminNav={showAdminNav} user={user} onLogout={handleLogout} />
      <div className="app-shell">
        <div className="app-shell__column">
          <div className="app-header app-header--mobile app-header--mobile-stack">
            <div className="app-header-mobile__top">
              <div className="app-logo">🥋 Shinkan</div>
            </div>
            <ActiveClubSwitcher variant="mobile" />
          </div>
          <div className="app-main">
            <InactiveMembershipBanner />
            <Outlet />
          </div>
          <Nav showAdminNav={showAdminNav} />
        </div>
      </div>
    </OrgInboxProvider>
  )
}

function PublicRoute({ children }) {
  const { isAuthenticated, loading } = useAuth()

  if (loading) {
    return (
      <div
        style={{
          minHeight: '100vh',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          background: 'var(--bg)',
        }}
      >
        <div className="spinner"></div>
      </div>
    )
  }

  return !isAuthenticated ? children : <Navigate to="/" replace />
}

/**
 * Data Router — erforderlich für `useBlocker` (ungespeicherte Änderungen).
 * Klassisches `BrowserRouter` stellt keinen DataRouterContext bereit; ohne Migration
 * werfen Seiten mit `useUnsavedChangesBlocker` beim Rendern eine Invariante.
 */
const appRouter = createBrowserRouter([
  { path: '/verify', element: <VerifyPage /> },
  {
    path: '/login',
    element: (
      <PublicRoute>
        <LoginPage />
      </PublicRoute>
    ),
  },
  { path: '/impressum', element: <LegalPage type="impressum" /> },
  { path: '/datenschutz', element: <LegalPage type="datenschutz" /> },
  { path: '/nutzungsbedingungen', element: <LegalPage type="nutzungsbedingungen" /> },
  { path: '/medienrichtlinie', element: <LegalPage type="medienrichtlinie" /> },
  {
    element: <ProtectedLayout />,
    children: [
      { index: true, element: <Dashboard /> },
      { path: 'profile', element: <Navigate to="/settings" replace /> },
      { path: 'settings', element: <AccountSettingsPage /> },
      { path: 'settings/system', element: <SettingsSystemInfoPage /> },
      { path: 'settings/legal', element: <SettingsLegalPage /> },
      { path: 'media', element: <MediaLibraryPage /> },
      {
        path: 'exercises',
        children: [
          { index: true, element: <ExercisesListPage /> },
          { path: 'new', element: <ExerciseFormPage /> },
          { path: ':id/edit', element: <ExerciseFormPage /> },
          { path: ':id', element: <ExerciseDetailPage /> },
        ],
      },
      { path: 'clubs', element: <ClubsPage /> },
      { path: 'inbox', element: <InboxPage /> },
      { path: 'skills', element: <SkillsPage /> },
      { path: 'planning/framework-programs/new', element: <TrainingFrameworkProgramEditPage /> },
      { path: 'planning/framework-programs/:id', element: <TrainingFrameworkProgramEditPage /> },
      { path: 'planning/framework-programs', element: <TrainingFrameworkProgramsListPage /> },
      { path: 'planning/training-modules/new', element: <TrainingModuleEditPage /> },
      { path: 'planning/training-modules/:id', element: <TrainingModuleEditPage /> },
      { path: 'planning/training-modules', element: <TrainingModulesListPage /> },
      { path: 'planning/run/:unitId/coach', element: <TrainingCoachPage /> },
      { path: 'planning/run/:unitId', element: <TrainingUnitRunPage /> },
      { path: 'planning', element: <TrainingPlanningPage /> },
      { path: 'admin', element: <AdminHomeRedirect /> },
      {
        path: 'admin/users',
        element: (
          <PlatformAdminRoute>
            <AdminUsersPage />
          </PlatformAdminRoute>
        ),
      },
      {
        path: 'admin/hierarchy',
        element: (
          <PlatformAdminRoute>
            <AdminHierarchyPage />
          </PlatformAdminRoute>
        ),
      },
      {
        path: 'admin/maturity-models',
        element: (
          <PlatformAdminRoute>
            <AdminMaturityModelsPage />
          </PlatformAdminRoute>
        ),
      },
      {
        path: 'admin/catalogs',
        element: (
          <PlatformAdminRoute>
            <AdminCatalogsPage />
          </PlatformAdminRoute>
        ),
      },
      {
        path: 'admin/mediawiki-import',
        element: (
          <PlatformAdminRoute>
            <MediaWikiImportPage />
          </PlatformAdminRoute>
        ),
      },
      {
        path: 'admin/legal-documents',
        element: (
          <PlatformAdminRoute>
            <AdminLegalDocumentsPage />
          </PlatformAdminRoute>
        ),
      },
      { path: 'trainer-contexts', element: <TrainerContextsPage /> },
    ],
  },
  { path: '*', element: <Navigate to="/" replace /> },
])

function App() {
  return (
    <AuthProvider>
      <ToastProvider>
        <RouterProvider router={appRouter} />
      </ToastProvider>
    </AuthProvider>
  )
}

export default App
