import React from 'react'
import {
  BrowserRouter as Router,
  Routes,
  Route,
  Navigate,
  NavLink,
  useLocation,
  Outlet,
} from 'react-router-dom'
import { AuthProvider, useAuth } from './context/AuthContext'
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 />
}

function AppRoutes() {
  return (
    <Routes>
      <Route path="/verify" element={<VerifyPage />} />

      <Route
        path="/login"
        element={
          <PublicRoute>
            <LoginPage />
          </PublicRoute>
        }
      />

      {/* P-01: Öffentliche Rechtstextseiten — kein Auth erforderlich */}
      <Route path="/impressum" element={<LegalPage type="impressum" />} />
      <Route path="/datenschutz" element={<LegalPage type="datenschutz" />} />
      <Route path="/nutzungsbedingungen" element={<LegalPage type="nutzungsbedingungen" />} />
      <Route path="/medienrichtlinie" element={<LegalPage type="medienrichtlinie" />} />

      <Route element={<ProtectedLayout />}>
        <Route index element={<Dashboard />} />
        <Route path="profile" element={<Navigate to="/settings" replace />} />
        <Route path="settings" element={<AccountSettingsPage />} />
        <Route path="settings/system" element={<SettingsSystemInfoPage />} />
        <Route path="settings/legal" element={<SettingsLegalPage />} />
        <Route path="media" element={<MediaLibraryPage />} />
        <Route path="exercises">
          <Route index element={<ExercisesListPage />} />
          <Route path="new" element={<ExerciseFormPage />} />
          <Route path=":id/edit" element={<ExerciseFormPage />} />
          <Route path=":id" element={<ExerciseDetailPage />} />
        </Route>
        <Route path="clubs" element={<ClubsPage />} />
        <Route path="inbox" element={<InboxPage />} />
        <Route path="skills" element={<SkillsPage />} />
        <Route path="planning/framework-programs/new" element={<TrainingFrameworkProgramEditPage />} />
        <Route path="planning/framework-programs/:id" element={<TrainingFrameworkProgramEditPage />} />
        <Route path="planning/framework-programs" element={<TrainingFrameworkProgramsListPage />} />
        <Route path="planning/training-modules/new" element={<TrainingModuleEditPage />} />
        <Route path="planning/training-modules/:id" element={<TrainingModuleEditPage />} />
        <Route path="planning/training-modules" element={<TrainingModulesListPage />} />
        <Route path="planning/run/:unitId/coach" element={<TrainingCoachPage />} />
        <Route path="planning/run/:unitId" element={<TrainingUnitRunPage />} />
        <Route path="planning" element={<TrainingPlanningPage />} />
        <Route path="admin" element={<AdminHomeRedirect />} />
        <Route
          path="admin/users"
          element={
            <PlatformAdminRoute>
              <AdminUsersPage />
            </PlatformAdminRoute>
          }
        />
        <Route
          path="admin/hierarchy"
          element={
            <PlatformAdminRoute>
              <AdminHierarchyPage />
            </PlatformAdminRoute>
          }
        />
        <Route
          path="admin/maturity-models"
          element={
            <PlatformAdminRoute>
              <AdminMaturityModelsPage />
            </PlatformAdminRoute>
          }
        />
        <Route
          path="admin/catalogs"
          element={
            <PlatformAdminRoute>
              <AdminCatalogsPage />
            </PlatformAdminRoute>
          }
        />
        <Route
          path="admin/mediawiki-import"
          element={
            <PlatformAdminRoute>
              <MediaWikiImportPage />
            </PlatformAdminRoute>
          }
        />
        <Route
          path="admin/legal-documents"
          element={
            <PlatformAdminRoute>
              <AdminLegalDocumentsPage />
            </PlatformAdminRoute>
          }
        />
        <Route path="trainer-contexts" element={<TrainerContextsPage />} />
      </Route>

      <Route path="*" element={<Navigate to="/" replace />} />
    </Routes>
  )
}

function App() {
  return (
    <AuthProvider>
      <Router>
        <AppRoutes />
      </Router>
    </AuthProvider>
  )
}

export default App
