import { useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';
import App from './app/App';
import { AdminDashboardPage } from './app/admin/AdminDashboardPage';
import { AdminLoginPage } from './app/admin/AdminLoginPage';
import { isAdminAuthenticated } from './app/utils/auth';
import { Toaster } from './app/components/ui/sonner';
import './styles/index.css';

function getCurrentRoute() {
  const hash = window.location.hash.replace(/^#/, '');
  return hash || '/';
}

function navigate(path: string) {
  window.location.hash = path;
}

function RouterApp() {
  const [path, setPath] = useState(getCurrentRoute());
  const [isAuthed, setIsAuthed] = useState(isAdminAuthenticated());

  useEffect(() => {
    const sync = () => {
      setPath(getCurrentRoute());
      setIsAuthed(isAdminAuthenticated());
    };

    window.addEventListener('hashchange', sync);
    window.addEventListener('popstate', sync);

    if (!window.location.hash) {
      navigate('/');
    }

    return () => {
      window.removeEventListener('hashchange', sync);
      window.removeEventListener('popstate', sync);
    };
  }, []);

  const onLoginSuccess = () => {
    setIsAuthed(true);
    navigate('/admin');
  };

  const onLogout = () => {
    setIsAuthed(false);
    navigate('/admin');
  };

  const isAdminRoute = path.startsWith('/admin');

  return (
    <>
      {isAdminRoute ? (
        isAuthed ? <AdminDashboardPage onLogout={onLogout} /> : <AdminLoginPage onSuccess={onLoginSuccess} />
      ) : (
        <App />
      )}
      <Toaster position="top-center" richColors />
    </>
  );
}

createRoot(document.getElementById('root')!).render(<RouterApp />);
