import React, { useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate, useNavigate, useLocation } from 'react-router-dom';
import { AlertTriangle } from 'lucide-react';
import LandingPage from './pages/LandingPage';
import LoginPage from './pages/LoginPage';
import RegisterPage from './pages/RegisterPage';
import Dashboard from './pages/Dashboard';
import './index.css';

// Wrapper component to handle auto-redirect for logged-in users
const AuthRedirect = ({ children, redirectTo }) => {
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    const userData = localStorage.getItem('hilmanhost_user');
    const isMaintenance = localStorage.getItem('hilmanhost_maintenance') === 'true';

    if (userData) {
      try {
        const user = JSON.parse(userData);
        if (user && user.id && !user.banned) {
          // If maintenance is on and user is not admin, they should go to maintenance page
          if (isMaintenance && user.role !== 'admin' && location.pathname !== '/maintenance') {
            navigate('/maintenance', { replace: true });
            return;
          }
          // User is logged in, redirect to dashboard if they are on landing/login/register
          if (location.pathname === '/' || location.pathname === '/login' || location.pathname === '/register') {
            navigate(redirectTo || '/dashboard', { replace: true });
          }
        }
      } catch (e) {
        localStorage.removeItem('hilmanhost_user');
      }
    } else if (isMaintenance && location.pathname !== '/maintenance' && location.pathname !== '/login') {
      // Not logged in and maintenance is on
      navigate('/maintenance', { replace: true });
    }
  }, [location.pathname]);

  return children;
};

function App() {
  // Track online status
  useEffect(() => {
    const userData = localStorage.getItem('hilmanhost_user');
    if (userData) {
      try {
        const user = JSON.parse(userData);
        if (user?.id) {
          // Set online status
          localStorage.setItem(`hilmanhost_online_${user.id}`, Date.now().toString());
          const heartbeat = setInterval(() => {
            localStorage.setItem(`hilmanhost_online_${user.id}`, Date.now().toString());
          }, 10000);

          // Clean up on unload
          const onUnload = () => {
            localStorage.removeItem(`hilmanhost_online_${user.id}`);
          };
          window.addEventListener('beforeunload', onUnload);
          return () => {
            clearInterval(heartbeat);
            window.removeEventListener('beforeunload', onUnload);
          };
        }
      } catch (e) {}
    }
  }, []);

  return (
    <Router>
      <Routes>
        <Route path="/" element={
          <AuthRedirect redirectTo="/dashboard">
            <LandingPage />
          </AuthRedirect>
        } />
        <Route path="/login" element={
          <AuthRedirect redirectTo="/dashboard">
            <LoginPage />
          </AuthRedirect>
        } />
        <Route path="/register" element={
          <AuthRedirect redirectTo="/dashboard">
            <RegisterPage />
          </AuthRedirect>
        } />
        <Route path="/dashboard/*" element={<Dashboard />} />
        <Route path="/maintenance" element={<MaintenancePage />} />
        <Route path="*" element={<Navigate to="/" />} />
      </Routes>
    </Router>
  );
}

const MaintenancePage = () => (
  <div style={{ height: '100vh', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', background: 'var(--bg)', textAlign: 'center', padding: '2rem' }}>
    <div style={{ background: 'rgba(249,115,22,0.1)', padding: '2rem', borderRadius: '24px', marginBottom: '2rem', border: '1px solid rgba(249,115,22,0.2)' }}>
      <AlertTriangle size={64} color="var(--primary)" />
    </div>
    <h1 style={{ fontSize: '2.5rem', fontWeight: 800, marginBottom: '1rem' }}>Sistem Bakımda 🛠️</h1>
    <p style={{ color: 'var(--text-dim)', maxWidth: '500px', lineHeight: '1.6' }}>
      Size daha iyi hizmet verebilmek için kısa süreli bir bakım çalışması yapıyoruz. 
      Lütfen daha sonra tekrar deneyiniz.
    </p>
    <div style={{ marginTop: '3rem', fontSize: '0.8rem', color: 'var(--text-dim)', opacity: 0.5 }}>
      &copy; 2026 HilmanHost Infrastructure
    </div>
  </div>
);

export default App;
