import React, { useEffect } from 'react';
import { BrowserRouter, Routes, Route, Navigate, useLocation } from 'react-router-dom';
import LoginPage from './pages/LoginPage';
import DashboardPage from './pages/DashboardPage';
import QuestsPage from './pages/QuestsPage';
import MapPage from './pages/MapPage';
import InventoryPage from './pages/InventoryPage';
import { apiService } from './services/api';
import { analyticsService } from './services/analyticsService';
import { useQuestStore } from './store/questStore';
import { useCharacterStore } from './store/characterStore';
import { getRandomQuote } from './utils/easterEggs';
import { User } from './types';
import { GuidedWalkthrough } from './components/ui/GuidedWalkthrough';
import './App.css';
import './animations.css';

function App() {
  const { currentUser, setCurrentUser, fetchAllData } = useQuestStore((state) => ({
    currentUser: state.currentUser,
    setCurrentUser: state.setCurrentUser,
    fetchAllData: state.fetchAllData,
  }));

  const { isLoading } = useQuestStore((state) => ({
    isLoading: state.isLoading,
  }));

  useEffect(() => {
    // Check if user is already logged in
    apiService
      .getCurrentUser()
      .then((user) => {
        setCurrentUser(user);
        // Set user properties in analytics after successful login
        analyticsService.setUserId(user.id);
        analyticsService.setUserProperties({
          [analyticsService.constructor.name]: user.username, // Map username to character name
        });
        // Load all quest data after user is authenticated
        fetchAllData();
      })
      .catch(() => {
        setCurrentUser(null);
      })
      .finally(() => {
        // Display a random Tolkien quote on app load
        console.log(
          `%c${getRandomQuote()}`,
          'font-size: 14px; color: #DAA520; font-style: italic; font-family: Lora, serif;'
        );
      });
  }, [setCurrentUser, fetchAllData]);

  const handleLogin = (user: User) => {
    setCurrentUser(user);
    // Set user properties in analytics after login
    analyticsService.setUserId(user.id);
    analyticsService.setUserProperties({
      [analyticsService.constructor.name]: user.username,
    });
    fetchAllData();
  };

  const handleLogout = async () => {
    try {
      await apiService.logout();
      analyticsService.trackLogout();
    } catch (error) {
      console.error('Logout error:', error);
      analyticsService.trackLogout();
    } finally {
      setCurrentUser(null);
      useCharacterStore.getState().clearDialogueHistory();
    }
  };

  return (
    <BrowserRouter future={{ v7_startTransition: true, v7_relativeSplatPath: true }}>
      <AppContent
        currentUser={currentUser}
        isLoading={isLoading}
        onLogin={handleLogin}
        onLogout={handleLogout}
      />
    </BrowserRouter>
  );
}

/**
 * AppContent component to handle route and page view tracking
 */
function AppContent({
  currentUser,
  isLoading,
  onLogin,
  onLogout,
}: {
  currentUser: User | null;
  isLoading: boolean;
  onLogin: (user: User) => void;
  onLogout: () => void;
}) {
  const location = useLocation();

  // Track page views when location changes
  useEffect(() => {
    const pageNames: Record<string, { title: string; trackEvent?: string }> = {
      '/login': { title: 'Login' },
      '/dashboard': { title: 'The Council Chamber', trackEvent: 'trackDashboardViewed' },
      '/quests': { title: 'Quests', trackEvent: 'trackQuestsPageViewed' },
      '/map': { title: 'Middle-earth Map', trackEvent: 'trackMapViewed' },
      '/inventory': { title: 'Inventory' },
    };

    const currentPage = pageNames[location.pathname] || { title: location.pathname };
    analyticsService.trackPageView(location.pathname, currentPage.title);

    // Track specific page events
    if (currentPage.trackEvent && currentPage.trackEvent === 'trackDashboardViewed') {
      analyticsService.trackDashboardViewed();
    } else if (currentPage.trackEvent && currentPage.trackEvent === 'trackQuestsPageViewed') {
      analyticsService.trackQuestsPageViewed();
    } else if (currentPage.trackEvent && currentPage.trackEvent === 'trackMapViewed') {
      analyticsService.trackMapViewed();
    }
  }, [location]);

  return (
    <div className="app min-h-screen bg-background-primary text-text-primary">
      {isLoading && (
        <div className="fixed inset-0 bg-background-primary/80 backdrop-blur-sm flex items-center justify-center z-50 animate-fadeIn">
          <div className="text-center">
            <div className="text-6xl mb-4 animate-bounce">🧙‍♂️</div>
            <p className="text-parchment-light font-epic text-2xl">Loading your Fellowship...</p>
          </div>
        </div>
      )}

      <Routes>
        <Route
          path="/login"
          element={
            currentUser ? <Navigate to="/dashboard" replace /> : <LoginPage onLogin={onLogin} />
          }
        />
        <Route
          path="/dashboard"
          element={
            currentUser ? (
              <DashboardPage user={currentUser} onLogout={onLogout} />
            ) : (
              <Navigate to="/login" replace />
            )
          }
        />
        <Route
          path="/quests"
          element={
            currentUser ? (
              <QuestsPage user={currentUser} onLogout={onLogout} />
            ) : (
              <Navigate to="/login" replace />
            )
          }
        />
        <Route
          path="/map"
          element={
            <MapPage user={currentUser} onLogout={onLogout} />
          }
        />
        <Route
          path="/inventory"
          element={
            currentUser ? (
              <InventoryPage user={currentUser} onLogout={onLogout} />
            ) : (
              <Navigate to="/login" replace />
            )
          }
        />
        <Route path="/" element={<Navigate to={currentUser ? '/dashboard' : '/login'} replace />} />
      </Routes>
      {/* Disable walkthrough during tests (navigator.webdriver is true in Playwright) */}
      {!navigator.webdriver && <GuidedWalkthrough isEnabled={Boolean(currentUser)} />}
    </div>
  );
}

export default App;
