import { useState } from 'react';

import { LoginScreen } from '@/components/login/LoginScreen';
import { AppShell } from '@/components/layout/AppShell';
import { RouteView } from './routes';

const AUTH_KEY = 'lr-openwrt-tool.authenticated';

export default function App() {
  const [authenticated, setAuthenticated] =
    useState(() => localStorage.getItem(AUTH_KEY) === 'true');

  const [active, setActive] =
    useState('Painel');

  function handleLogin(keepLoggedIn: boolean) {
    setAuthenticated(true);

    if (keepLoggedIn) {
      localStorage.setItem(AUTH_KEY, 'true');
    } else {
      localStorage.removeItem(AUTH_KEY);
    }
  }

  function handleLogout() {
    localStorage.removeItem(AUTH_KEY);
    setAuthenticated(false);
    setActive('Painel');
  }

  if (!authenticated) {
    return <LoginScreen onLogin={handleLogin} />;
  }

  return (
    <AppShell
      active={active}
      onSelect={setActive}
      onLogout={handleLogout}
    >
      <RouteView active={active} />
    </AppShell>
  );
}