import { Component, Match, Switch } from 'solid-js';
import { Navigate, RouteSectionProps, useIsRouting } from '@solidjs/router';
import { useAuth } from '../../lib/auth';

export const ProtectedRoute: Component<RouteSectionProps> = (props) => {
  const auth = useAuth();
  const isRouting = useIsRouting();
  const authState = auth();

  return (
    <Switch>
      <Match when={isRouting()}>
        <div class="freno-loading">
          <div class="freno-spinner" />
        </div>
      </Match>
      <Match when={authState.isLoading}>
        <Navigate href="/sign-in" />
      </Match>
      <Match when={!authState.isAuthenticated}>
        <Navigate href="/sign-in" />
      </Match>
      <Match when={authState.isAuthenticated}>
        <div>{props.children}</div>
      </Match>
    </Switch>
  );
};
