// A belépési pont: útvonaltábla, hozzáférés-ellenőrzés (belépés, szerepkör) és a megjelenítés indítása.
(() => {
  // Ki melyik oldalt láthatja: auth = csak belépve, roles = csak ezek a szerepkörök.
  const ROUTES = [
    { path: '/', page: HomePage, bare: true },
    { path: '/login', page: LoginPage },
    { path: '/register', page: RegisterPage },
    { path: '/electricians/:id', page: ElectricianPublicPage },

    { path: '/customer', page: CustomerJobsPage, roles: ['CUSTOMER'] },
    { path: '/customer/jobs/new', page: NewJobPage, roles: ['CUSTOMER'] },
    { path: '/customer/jobs/:id', page: CustomerJobDetailPage, roles: ['CUSTOMER'] },

    { path: '/electrician', page: NearbyJobsPage, roles: ['ELECTRICIAN'] },
    { path: '/electrician/jobs/:id', page: ElectricianJobPage, roles: ['ELECTRICIAN'] },
    { path: '/electrician/my-jobs', page: MyJobsPage, roles: ['ELECTRICIAN'] },
    { path: '/electrician/profile', page: ProfilePage, roles: ['ELECTRICIAN'] },

    { path: '/notifications', page: NotificationsPage, auth: true },

    { path: '/admin', page: AdminElectriciansPage, roles: ['ADMIN'] },
    { path: '/admin/categories', page: AdminCategoriesPage, roles: ['ADMIN'] },
  ];

  function Router() {
    const path = useHashPath();
    const { user, loading } = useAuth();

    let params = null;
    const route = ROUTES.find((candidate) => {
      params = matchPath(candidate.path, path);
      return params !== null;
    });

    let content;
    if (!route) {
      content = <NotFoundPage />;
    } else if ((route.auth || route.roles) && loading) {
      content = <Loading />;
    } else if ((route.auth || route.roles) && !user) {
      sessionStorage.setItem('afterLogin', path);
      content = <Redirect to="/login" />;
    } else if (route.roles && !route.roles.includes(user.role)) {
      // A rossz szerepkörű látogató a saját főoldalára kerül.
      content = <Redirect to={homePathFor(user.role)} />;
    } else {
      const Page = route.page;
      content = <Page />;
    }

    return (
      <RouteContext.Provider value={{ params: params ?? {}, path }}>
        <Layout bare={Boolean(route?.bare)}>{content}</Layout>
      </RouteContext.Provider>
    );
  }

  ReactDOM.createRoot(document.getElementById('root')).render(
    <AuthProvider>
      <Router />
    </AuthProvider>,
  );
})();
