import React, { useRef, useEffect } from 'react';
import { GameState, StoryData, Choice, SystemStatus } from '../types';
import SaveLoadControls from './SaveLoadControls';
import PlayerInput from './PlayerInput';
import LoadingSpinner from './LoadingSpinner';
import SystemMonitor from './SystemMonitor';
import GuardianConsole from './GuardianConsole';
import ConstellationMap from './ConstellationMap';

interface GameScreenProps {
  gameState: GameState;
  story: StoryData;
  onChoice: (choice: Choice) => void;
  onCustomAction: (input: string) => void;
  isLoading: boolean;
  onSave: () => void;
  onLoad: () => void;
  onRestart: () => void;
  isSaveDataPresent: boolean;
  codexStatus: SystemStatus;
}

const GameScreen: React.FC<GameScreenProps> = ({ 
    gameState, story, onChoice, onCustomAction, isLoading, 
    onSave, onLoad, onRestart, isSaveDataPresent, codexStatus 
}) => {
  const currentScene = story[gameState.currentSceneId];
  const scrollRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [gameState.history, gameState.currentSceneId]);
  
  if (!currentScene) {
    return (
        <div className="min-h-screen flex flex-col items-center justify-center bg-gray-900 text-red-500 p-4">
            <div className="text-2xl">Error: Scene '{gameState.currentSceneId}' not found.</div>
            <button onClick={onRestart} className="mt-4 px-4 py-2 border rounded">Restart Journey</button>
        </div>
    )
  }

  return (
    <div className="min-h-screen w-full bg-gray-900 text-emerald-400 p-4 lg:p-8 flex items-center justify-center relative">
        <ConstellationMap />
        <div className="w-full h-full max-w-7xl mx-auto grid grid-cols-1 lg:grid-cols-4 gap-4 lg:gap-8 z-10">
            
            <div className="hidden lg:block lg:col-span-1">
                <SystemMonitor codexStatus={codexStatus} />
            </div>

            <div className="w-full h-[90vh] lg:h-full lg:col-span-2 flex flex-col bg-black/50 border border-emerald-900 rounded-lg shadow-2xl shadow-emerald-900/20 backdrop-blur-sm">
                <header className="p-4 border-b border-emerald-900 flex justify-between items-center">
                    <h1 className="text-xl md:text-2xl font-bold text-glow">{currentScene.title || gameState.currentPillar || 'Codex'}</h1>
                    <SaveLoadControls onSave={onSave} onLoad={onLoad} onRestart={onRestart} isSaveDataPresent={isSaveDataPresent} />
                </header>
                
                <main ref={scrollRef} className="flex-grow p-6 overflow-y-auto relative">
                  {gameState.history.map((hist, index) => {
                    const scene = story[hist.sceneId];
                    if (!scene) return null;
                    return (
                      <div key={index} className="mb-6 opacity-70">
                        {scene.text.map((p, i) => <p key={i} className="mb-2">{p}</p>)}
                        {hist.choiceText && (
                          <p className="mt-4 text-emerald-600 italic pl-4 border-l-2 border-emerald-800">
                            &gt; {hist.choiceText}
                          </p>
                        )}
                      </div>
                    )
                  })}

                  <div className="animate-fadeIn">
                    {currentScene.text.map((paragraph, index) => (
                      <p key={index} className="mb-4 text-lg text-gray-200">{paragraph}</p>
                    ))}
                  </div>
                  {isLoading && (
                     <div className="absolute inset-0 bg-black/70 flex flex-col items-center justify-center backdrop-blur-sm">
                        <LoadingSpinner />
                        <p className="mt-4 text-cyan-400 text-glow animate-pulse">Codex is processing...</p>
                     </div>
                  )}
                </main>
                
                {!gameState.isGameOver && currentScene.choices.length > 0 && (
                  <footer className="p-4 border-t border-emerald-900">
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                          {currentScene.choices.map((choice, index) => (
                              <button
                                  key={index}
                                  onClick={() => onChoice(choice)}
                                  disabled={isLoading}
                                  className="w-full text-left p-3 bg-gray-800/60 border border-emerald-800 rounded text-emerald-400 hover:bg-emerald-900/70 hover:border-emerald-500 transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
                              >
                                  {choice.text}
                              </button>
                          ))}
                      </div>
                  </footer>
                )}
                 {gameState.isGameOver && (
                  <footer className="p-4 border-t border-emerald-900">
                      <button
                        onClick={() => onChoice(currentScene.choices[0])}
                        className="w-full p-3 bg-yellow-800/60 border border-yellow-700 rounded text-yellow-300 hover:bg-yellow-900/70 hover:border-yellow-500 transition-colors duration-200"
                      >
                        {currentScene.choices[0].text}
                      </button>
                  </footer>
                )}
                {!gameState.isGameOver && <PlayerInput onSubmit={onCustomAction} disabled={isLoading} />}
            </div>

            <div className="hidden lg:block lg:col-span-1">
                <GuardianConsole />
            </div>
        </div>
    </div>
  );
};

export default GameScreen;