import { BrowserRouter, HashRouter, Routes, Route, Navigate, useLocation } from 'react-router-dom'
import { useEffect } from 'react'
import { AuthProvider } from './contexts/AuthContext'
import { useAuth } from './hooks/useAuth'
import { AudioProvider } from './contexts/AudioContext'
import BackgroundMusic from './components/BackgroundMusic'
import LandingPage from './components/LandingPage'
import Login from './components/Login'
import Register from './components/Register'
import CharacterSelection from './components/CharacterSelection'
import CharacterCreation from './components/CharacterCreation'
import Game from './components/Game'
import Profile from './components/Profile'
import Leaderboards from './components/Leaderboards'
import GameLayout from './components/GameLayout'
import AccountPage from './components/AccountPage'
import PublicLayout from './components/PublicLayout'
import AuthenticatedLayout from './components/AuthenticatedLayout'
import PrivacyPolicy from './components/PrivacyPolicy'
import TermsOfService from './components/TermsOfService'
import './App.css'
import { NotificationProvider } from './contexts/NotificationContext'
import { NotificationContainer } from './components/common/NotificationContainer'

// Use HashRouter for Electron (file:// protocol), BrowserRouter for web
const isElectron = window.location.protocol === 'file:'
const Router = isElectron ? HashRouter : BrowserRouter

function PrivateRoute({ children }: { children: React.ReactNode }) {
  const { isAuthenticated, loading } = useAuth()

  if (loading) {
    return <div className="loading">Loading...</div>
  }

  return isAuthenticated ? <>{children}</> : <Navigate to="/login" />
}

function CharacterRoute({ children }: { children: React.ReactNode }) {
  const { isAuthenticated, currentCharacter, loading } = useAuth()

  if (loading) {
    return <div className="loading">Loading...</div>
  }

  if (!isAuthenticated) {
    return <Navigate to="/login" />
  }

  if (!currentCharacter) {
    return <Navigate to="/characters" />
  }

  return <>{children}</>
}

function ZoomManager() {
  const location = useLocation();

  useEffect(() => {
    const updateZoom = () => {
      const isGamePage = location.pathname.includes('/game');
      window.scrollTo(0, 0);

      if (isGamePage) {
        const scale = window.innerWidth / 1920;
        (document.documentElement.style as any).zoom = `${scale}`;
        document.documentElement.style.setProperty('--zoom-factor', `${scale}`);
        document.body.style.overflow = 'hidden';
        document.documentElement.style.overflow = 'hidden';
      } else {
        (document.documentElement.style as any).zoom = '1';
        document.documentElement.style.setProperty('--zoom-factor', '1');
        document.body.style.overflow = 'auto';
        document.documentElement.style.overflow = 'auto';
        document.body.style.height = 'auto';
        document.documentElement.style.height = 'auto';
      }
    };

    updateZoom();
    window.addEventListener('resize', updateZoom);

    return () => {
      window.removeEventListener('resize', updateZoom);
    };
  }, [location.pathname]);

  return null;
}

function App() {
  return (
    <NotificationProvider>
      <AuthProvider>
        <AudioProvider>
          <Router>
            <ZoomManager />
            <BackgroundMusic />
            <NotificationContainer />
            <div className="app">
              <Routes>
                <Route element={<PublicLayout />}>
                  <Route path="/" element={<LandingPage />} />
                  <Route path="/login" element={<Login />} />
                  <Route path="/register" element={<Register />} />
                  <Route path="/privacy" element={<PrivacyPolicy />} />
                  <Route path="/terms" element={<TermsOfService />} />
                </Route>

                <Route element={<AuthenticatedLayout />}>
                  <Route
                    path="/characters"
                    element={
                      <PrivateRoute>
                        <CharacterSelection />
                      </PrivateRoute>
                    }
                  />

                  <Route
                    path="/create-character"
                    element={
                      <PrivateRoute>
                        <CharacterCreation />
                      </PrivateRoute>
                    }
                  />

                  <Route
                    path="/account"
                    element={
                      <PrivateRoute>
                        <AccountPage />
                      </PrivateRoute>
                    }
                  />
                </Route>

                <Route element={<GameLayout />}>
                  <Route
                    path="/game"
                    element={
                      <CharacterRoute>
                        <Game />
                      </CharacterRoute>
                    }
                  />

                  <Route
                    path="/profile/:playerId"
                    element={
                      <PrivateRoute>
                        <Profile />
                      </PrivateRoute>
                    }
                  />

                  <Route
                    path="/leaderboards"
                    element={
                      <PrivateRoute>
                        <Leaderboards />
                      </PrivateRoute>
                    }
                  />
                </Route>
              </Routes>
            </div>
          </Router>
        </AudioProvider>
      </AuthProvider>
    </NotificationProvider>
  )
}

export default App

