import Main from './components/Main.jsx';
import React from "react";
import { useRoutes, Outlet, BrowserRouter } from 'react-router-dom';
import Employees from './components/Employees.jsx';
import Header from "./components/commons/Header.jsx"
import 'bootstrap/dist/css/bootstrap.min.css';
import Companies from './components/Companies.jsx';
import Positions from './components/Positions.jsx';
import OneCompany from './components/OneCompany.jsx';
import ReportEmployeePosition from './components/ReportEmployeePosition.jsx';
import Login from './components/Login.jsx';
import Logout from './components/Logout.jsx';
import { useState, useEffect } from 'react';
function Router(props) {
    return useRoutes(props.rootRoute);
  }
  
function App() {
  const routes = [
    { index: true, element: <Companies /> },
    { path: '/', element: <Companies />, label: 'ГЛАВНОЕ' },
    { path: '/employees', element: <Employees />, label: 'Сотрудники' },
    { path: '/companies', element: <Companies />, label: 'Компании' },
    { path: '/positions', element: <Positions />, label: 'Должности' },
    { path: '/report', element: <ReportEmployeePosition />, label: 'Сотрудники по должностям' },
    { path: '/company/:id', element: <OneCompany />},
    { path: '/login', element: <Login />},
    { path: '/logout', element: <Logout />},
  ];
  const links = routes.filter(route => route.hasOwnProperty('label'));
  const [token, setToken] = useState(localStorage.getItem('token'));

  useEffect(() => {
    
    function handleStorageChange() {
      setToken(localStorage.getItem('token'));
    }

    window.addEventListener('storage', handleStorageChange);

    return () => {
      window.removeEventListener('storage', handleStorageChange);
    };
  }, []);

  const rootRoute = [
    { path: '/', element: render(links), children: routes }
  ];
  
  function render(links) {
  
    return (
      <div className="App">
        <Header token={token} links={links} />         
        <div className="w-100">
          <Outlet />
        </div>        
    </div>
  );
}

  return (
    <BrowserRouter>
      <Router rootRoute={ rootRoute } />
    </BrowserRouter>
  );
}

export default App;