/**
 * CameraController - handles camera movement and focus
 */
import { useEffect, useRef } from 'react';
import { useFrame, useThree } from '@react-three/fiber';
import { Vector3 } from 'three';
import type { CelestialBody } from '../types';
import { calculateRenderPosition, findParentPlanet } from '../utils/renderPosition';

interface CameraControllerProps {
  focusTarget: CelestialBody | null;
  allBodies: CelestialBody[];
  onAnimationComplete?: () => void;
}

export function CameraController({ focusTarget, allBodies, onAnimationComplete }: CameraControllerProps) {
  const { camera } = useThree();
  const targetPosition = useRef(new Vector3());
  const isAnimating = useRef(false);
  const animationProgress = useRef(0);
  const startPosition = useRef(new Vector3());

  useEffect(() => {
    if (focusTarget) {
      // Focus on target - use smart rendered position
      const pos = focusTarget.positions[0];
      const renderPos = calculateRenderPosition(focusTarget, allBodies);
      const scaledPos = { x: renderPos.x, y: renderPos.y, z: renderPos.z };

      const distance = Math.sqrt(pos.x ** 2 + pos.y ** 2 + pos.z ** 2);
      const parentInfo = findParentPlanet(focusTarget, allBodies);

      // Calculate camera position based on target type and context
      let offset: number;
      let heightMultiplier = 1; // For adjusting vertical position
      let sideMultiplier = 1; // For adjusting horizontal offset

      if (focusTarget.type === 'planet') {
        // For planets, use closer view from above
        offset = 4;
        heightMultiplier = 1.5;
        sideMultiplier = 1;
      } else if (focusTarget.type === 'probe') {
        // For probes, determine view based on context
        if (parentInfo) {
          // Probe near a planet - use closer view to see both probe and planet
          offset = 3; // Closer view (was 5)
          heightMultiplier = 0.8;
          sideMultiplier = 1.2;
        } else if (distance < 10) {
          // Inner solar system probe (not near a planet)
          offset = 5; // Closer view (was 8)
          heightMultiplier = 0.6;
          sideMultiplier = 1.5;
        } else if (distance > 50) {
          // Far probes (Voyagers, New Horizons) - need even closer view since they're so far
          offset = 4; // Much closer (was 12)
          heightMultiplier = 0.8;
          sideMultiplier = 1;
        } else {
          // Medium distance probes
          offset = 6; // Closer view (was 10)
          heightMultiplier = 0.8;
          sideMultiplier = 1.2;
        }
      } else {
        offset = 10;
        heightMultiplier = 1;
        sideMultiplier = 1;
      }

      targetPosition.current.set(
        scaledPos.x + (offset * sideMultiplier),
        scaledPos.z + (offset * heightMultiplier),
        scaledPos.y + offset
      );

      // Start animation
      startPosition.current.copy(camera.position);
      isAnimating.current = true;
      animationProgress.current = 0;
    } else {
      // Return to solar system overview (angled view)
      targetPosition.current.set(50, 40, 50);
      startPosition.current.copy(camera.position);
      isAnimating.current = true;
      animationProgress.current = 0;
    }
  }, [focusTarget, allBodies, camera]);

  useFrame((_, delta) => {
    if (isAnimating.current) {
      // Smooth animation using easing
      animationProgress.current += delta * 0.8; // Animation speed

      if (animationProgress.current >= 1) {
        animationProgress.current = 1;
        isAnimating.current = false;
        if (onAnimationComplete) onAnimationComplete();
      }

      // Easing function (ease-in-out)
      const t = animationProgress.current;
      const eased = t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;

      // Interpolate camera position
      camera.position.lerpVectors(startPosition.current, targetPosition.current, eased);

      // Look at target - use smart rendered position (only during animation)
      if (focusTarget) {
        const renderPos = calculateRenderPosition(focusTarget, allBodies);
        camera.lookAt(renderPos.x, renderPos.z, renderPos.y);
      } else {
        camera.lookAt(0, 0, 0);
      }
    }
    // After animation completes, OrbitControls will take over
  });

  return null;
}
