import React, { useState, useEffect } from 'react';
import './App.css';
import RPGGame from './components/RPGGame';
import FlappyDODO from './components/FlappyDODO';
import DODOTRIS from './components/DODOTRIS';
import DodoGuessr from './components/DodoGuessr';
import MusicalSnake from './components/MusicalSnake/MusicalSnake';
import DateTimeDisplay from './components/DateTimeDisplay';
import HomePage from './components/HomePage';
import SubPage from './components/SubPage';
import { useAudioData } from './hooks/useAudioData';
import { useAudioPlayer } from './hooks/useAudioPlayer';

type ActiveView = 'home' | 'rpg' | 'flappydodo' | 'dodotris' | 'dodoguessr' | 'musicalsnake' | 'page';

function App() {
  const [currentPage, setCurrentPage] = useState<number | null>(null);
  const [activeView, setActiveView] = useState<ActiveView>('home');
  
  const { pages, isLoading, error } = useAudioData();
  const {
    playedSongs,
    currentlyPlaying,
    pageDurations,
    audioDurations,
    setPageDurations,
    handlePlay,
    handleNext,
    handlePrev,
    handleEnded,
    handleLoadedMetadata,
    setIsPlaying
  } = useAudioPlayer();

  useEffect(() => {
    if (currentPage !== null && pages.length > 0) {
      const currentPageAudioFiles = pages[currentPage].audioFiles;
      const totalDuration = currentPageAudioFiles.reduce((sum, _, index) => {
        return sum + (audioDurations[`${currentPage}-${index}`] || 0);
      }, 0);
      setPageDurations(prev => ({
        ...prev,
        [currentPage]: Math.round(totalDuration / 60)
      }));
    }
  }, [audioDurations, currentPage, pages, setPageDurations]);

  useEffect(() => {
    const gradientElement = document.querySelector('.gradient-animation') as HTMLElement;
    if (gradientElement) {
      let position = 0;
      let direction = 1;
      let animationFrame: number;

      const animateGradient = () => {
        position += 0.5 * direction;
        if (position > 100 || position < 0) {
          direction *= -1;
        }
        gradientElement.style.backgroundPosition = `${position}% 50%`;
        animationFrame = requestAnimationFrame(animateGradient);
      };

      animationFrame = requestAnimationFrame(animateGradient);

      return () => {
        cancelAnimationFrame(animationFrame);
      };
    }
  }, [currentlyPlaying]);

  const getCurrentPageAudioFiles = () => {
    return currentPage !== null && pages[currentPage] ? pages[currentPage].audioFiles : [];
  };

  const handleNextClick = () => handleNext(getCurrentPageAudioFiles());
  const handleEndedClick = () => handleEnded(getCurrentPageAudioFiles());

  // Handle URL-based navigation
  useEffect(() => {
    const routeMap: Record<string, ActiveView> = {
      '/flappydodo': 'flappydodo',
      '/dodotris': 'dodotris',
      '/rpg': 'rpg',
      '/dodoguessr': 'dodoguessr',
      '/musicalsnake': 'musicalsnake',
      '/': 'home'
    };

    const checkPath = () => {
      const path = window.location.pathname;
      const view = routeMap[path] || 'home';
      setActiveView(view);
      if (view !== 'page') {
        setCurrentPage(null);
      }
    };

    checkPath();
    window.addEventListener('popstate', checkPath);
    return () => window.removeEventListener('popstate', checkPath);
  }, []);

  const handleBackToHome = () => {
    setCurrentPage(null);
    setActiveView('home');
    window.history.pushState({}, '', '/');
  };

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

  if (error) {
    return (
      <div className="error">
        <p>{error}</p>
      </div>
    );
  }

  return (
    <div className="App">
      <header className="App-header">
        <h1 className="clickable-title" onClick={handleBackToHome}>🎧 🎵 Tony's Dev Tunes  🧪 🎉</h1>
        <DateTimeDisplay />
      </header>
      <main>
        {activeView === 'rpg' ? (
          <RPGGame onBack={() => setActiveView('home')} />
        ) : activeView === 'flappydodo' ? (
          <FlappyDODO onBack={() => setActiveView('home')} />
        ) : activeView === 'dodotris' ? (
          <DODOTRIS onBack={() => setActiveView('home')} />
        ) : activeView === 'dodoguessr' ? (
          <DodoGuessr onBack={() => setActiveView('home')} />
        ) : activeView === 'musicalsnake' ? (
          <MusicalSnake onBack={() => setActiveView('home')} />
        ) : activeView === 'home' ? (
          <HomePage
            pages={pages}
            onPageSelect={(page) => {
              setCurrentPage(page);
              setActiveView('page');
            }}
            onRPGClick={() => setActiveView('rpg')}
            onFlappyDODOClick={() => setActiveView('flappydodo')}
            onDODOTRISClick={() => setActiveView('dodotris')}
            onDodoGuessrClick={() => setActiveView('dodoguessr')}
            onMusicalSnakeClick={() => setActiveView('musicalsnake')}
          />
        ) : activeView === 'page' && currentPage !== null ? (
          <SubPage
            page={pages[currentPage]}
            pageIndex={currentPage}
            pageDurations={pageDurations}
            playedSongs={playedSongs}
            currentlyPlaying={currentlyPlaying}
            onPlay={handlePlay}
            onEnded={handleEndedClick}
            onNext={handleNextClick}
            onPrev={handlePrev}
            onLoadedMetadata={handleLoadedMetadata}
            onSetIsPlaying={setIsPlaying}
            onBack={() => setActiveView('home')}
          />
        ) : null}
      </main>
    </div>
  );
}

export default App;
