import React from 'react';
import { createBrowserRouter, Outlet, Navigate, useLocation } from 'react-router-dom';
import LoginPage from './pages/LoginPage';
import EventsPage from './pages/EventsPage';
import SettingsPage from './pages/SettingsPage';
import EventFormPage from './pages/EventFormPage';
import EventPhotosPage from './pages/EventPhotosPage';
import EventDetailPage from './pages/EventDetailPage';
import AuthCallbackPage from './pages/AuthCallbackPage';
import { useAuth } from './auth/context';
import { ADMIN_AUTH_CALLBACK_PATH, ADMIN_BASE_PATH, ADMIN_LOGIN_PATH } from './constants';

function RequireAuth() {
  const { status } = useAuth();
  const location = useLocation();

  if (status === 'loading') {
    return (
      <div className="flex min-h-screen items-center justify-center text-sm text-muted-foreground">
        Bitte warten ...
      </div>
    );
  }

  if (status === 'unauthenticated') {
    return <Navigate to={ADMIN_LOGIN_PATH} state={{ from: location }} replace />;
  }

  return <Outlet />;
}

export const router = createBrowserRouter([
  { path: ADMIN_LOGIN_PATH, element: <LoginPage /> },
  { path: ADMIN_AUTH_CALLBACK_PATH, element: <AuthCallbackPage /> },
  {
    path: ADMIN_BASE_PATH,
    element: <RequireAuth />,
    children: [
      { index: true, element: <EventsPage /> },
      { path: 'events', element: <EventsPage /> },
      { path: 'events/new', element: <EventFormPage /> },
      { path: 'events/edit', element: <EventFormPage /> },
      { path: 'events/view', element: <EventDetailPage /> },
      { path: 'events/photos', element: <EventPhotosPage /> },
      { path: 'settings', element: <SettingsPage /> },
    ],
  },
  { path: '*', element: <Navigate to={ADMIN_BASE_PATH} replace /> },
]);


