// import React from "react";
import ReactDOM from "react-dom/client";
import {
  createBrowserRouter,
  Navigate,
  RouterProvider,
} from "react-router-dom";
import "./index.css";
import "./i18n";
import App from "./App";
import HistoryPage from "./HistoryPage";
import ScheduledPage from "./ScheduledPage";
import CalendarPage from "./CalendarPage";
import useAuthStore from "./stores/useAuthStore";
import PersonalAreaLoginPage from "./PersonalAreaLoginPage";
import PersonalAreaDashboardPage from "./PersonalAreaDashboardPage";
import StreamPage2 from "./pages/StreamPage2";
import ErrorBoundary from "./ErrorBoundary";

const router = createBrowserRouter([
  {
    path: "/",
    element: <App />,
    errorElement: <ErrorBoundary />,
  },
  {
    path: "/stream/:id",
    element: <StreamPage2 />,
  },
  {
    path: "/history",
    element: <HistoryPage />,
  },
  {
    path: "/scheduled/:sessionId",
    element: <ScheduledPage />,
  },
  {
    path: "/calendar/:username",
    element: <CalendarPage />,
  },
  {
    path: "/personal-area",
    element: <Navigate to="/personal-area/login" replace />,
  },
  {
    path: "/personal-area/login",
    element: (
      <ProtectedRoute>
        <PersonalAreaLoginPage />
      </ProtectedRoute>
    ),
  },
  {
    path: "/personal-area/dashboard",
    element: (
      <ProtectedRoute>
        <PersonalAreaDashboardPage />
      </ProtectedRoute>
    ),
  },
]);

export function ProtectedRoute({ children }: { children: JSX.Element }) {
  const accessToken = useAuthStore((state) => state.accessToken);

  if (accessToken) {
    if (location.pathname === "/personal-area/login") {
      return <Navigate to="/personal-area/dashboard" replace />;
    } else {
      return <>{children}</>;
    }
  } else {
    if (location.pathname !== "/personal-area/login") {
      return <Navigate to="/personal-area/login" replace />;
    } else {
      return <>{children}</>;
    }
  }
}

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
  // <React.StrictMode>
  <RouterProvider router={router} />
  // </React.StrictMode>,
);
