import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import Order from './Order.jsx'
import Auth from './Auth.jsx'
import MyOrders from './MyOrders.jsx'
import AdminDashboard from './AdminDashboard.jsx'
import './index.css'

function Router() {
  const [path, setPath] = React.useState(window.location.pathname);
  
  React.useEffect(() => {
    const handlePopState = () => setPath(window.location.pathname);
    window.addEventListener('popstate', handlePopState);
    return () => window.removeEventListener('popstate', handlePopState);
  }, []);

  window.navigate = (url) => {
    window.history.pushState({}, '', url);
    setPath(url);
  };
  
  // Check if user is admin and redirect to admin dashboard
  React.useEffect(() => {
    const userData = localStorage.getItem('user');
    if (userData) {
      const user = JSON.parse(userData);
      if (user.role === 'admin' && path === '/') {
        window.navigate('/admin');
      }
    }
  }, [path]);
  
  if (path === '/admin') return <AdminDashboard />;
  if (path === '/order') return <Order />;
  if (path === '/auth') return <Auth />;
  if (path === '/orders') return <MyOrders />;
  
  return <App />;
}

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <Router />
  </React.StrictMode>,
)
