/**
 * Cosmo - Deep Space Explorer
 * Main application component
 */
import { useState, useCallback } from 'react';
import { useSpaceData } from './hooks/useSpaceData';
import { useHistoricalData } from './hooks/useHistoricalData';
import { useTrajectory } from './hooks/useTrajectory';
import { Header } from './components/Header';
import { Scene } from './components/Scene';
import { ProbeList } from './components/ProbeList';
import { TimelineController } from './components/TimelineController';
import { Loading } from './components/Loading';
import type { CelestialBody } from './types';

// Timeline configuration - will be fetched from backend later
const TIMELINE_DAYS = 30; // Total days in timeline range

function App() {
  const [selectedDate, setSelectedDate] = useState<Date | null>(null);
  const [isTimelineMode, setIsTimelineMode] = useState(false);

  // Use real-time data or historical data based on mode
  const { bodies: realTimeBodies, loading: realTimeLoading, error: realTimeError } = useSpaceData();
  const { bodies: historicalBodies, loading: historicalLoading, error: historicalError } = useHistoricalData(selectedDate);

  const bodies = isTimelineMode ? historicalBodies : realTimeBodies;
  const loading = isTimelineMode ? historicalLoading : realTimeLoading;
  const error = isTimelineMode ? historicalError : realTimeError;

  const [selectedBody, setSelectedBody] = useState<CelestialBody | null>(null);
  const { trajectoryPositions } = useTrajectory(selectedBody);

  // Handle time change from timeline controller
  const handleTimeChange = useCallback((date: Date) => {
    setSelectedDate(date);
  }, []);

  // Toggle timeline mode
  const toggleTimelineMode = useCallback(() => {
    setIsTimelineMode((prev) => !prev);
    if (!isTimelineMode) {
      // Entering timeline mode, set initial date to now (will play backward)
      setSelectedDate(new Date());
    } else {
      setSelectedDate(null);
    }
  }, [isTimelineMode]);

  // Filter probes and planets from all bodies
  const probes = bodies.filter((b) => b.type === 'probe');
  const planets = bodies.filter((b) =>
    b.type === 'planet' || b.type === 'dwarf_planet' || b.type === 'satellite'
  );

  const handleBodySelect = (body: CelestialBody | null) => {
    setSelectedBody(body);
  };

  // Only show full screen loading when we have no data
  // This prevents flashing when timeline is playing and fetching new data
  if (loading && bodies.length === 0) {
    return <Loading />;
  }

  if (error) {
    return (
      <div className="w-full h-full flex items-center justify-center bg-black text-white">
        <div className="text-center">
          <h1 className="text-2xl font-bold mb-4">数据加载失败</h1>
          <p className="text-red-400">{error}</p>
          <p className="mt-4 text-sm text-gray-400">
            请确保后端 API 运行在 http://localhost:8000
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="w-full h-full relative">
      {/* Header with navigation and controls */}
      <Header
        isTimelineMode={isTimelineMode}
        onToggleTimeline={toggleTimelineMode}
        bodyCount={bodies.length}
        selectedBodyName={selectedBody?.name}
      />

      {/* Probe List Sidebar */}
      <ProbeList
        probes={probes}
        planets={planets}
        onBodySelect={handleBodySelect}
        selectedBody={selectedBody}
      />

      {/* 3D Scene */}
      <Scene
        bodies={bodies}
        selectedBody={selectedBody}
        trajectoryPositions={trajectoryPositions}
      />

      {/* Timeline Controller */}
      {isTimelineMode && (
        <TimelineController
          onTimeChange={handleTimeChange}
          maxDate={new Date()} // Start point (now)
          minDate={new Date(Date.now() - TIMELINE_DAYS * 24 * 60 * 60 * 1000)} // End point (past)
        />
      )}

      {/* Instructions overlay */}
      <div className="absolute bottom-4 right-4 z-50 text-white text-xs bg-black bg-opacity-70 p-3 rounded">
        {selectedBody ? (
          <>
            <p className="text-cyan-400 font-bold mb-2">聚焦模式</p>
            <p>点击侧边栏的"返回太阳系视图"按钮</p>
          </>
        ) : (
          <>
            <p className="font-bold mb-2">太阳系俯视图</p>
            <p>🖱️ 左键拖动: 旋转</p>
            <p>🖱️ 右键拖动: 平移</p>
            <p>🖱️ 滚轮: 缩放</p>
            <p className="mt-2 text-gray-400">点击左侧天体列表查看详情</p>
          </>
        )}
      </div>
    </div>
  );
}

export default App;
