import * as THREE from 'three';
import { createModelFromPreloaded, resetMeshGeometry, cleanupGeometryData } from './modelManager.js';
import { startBoldRoughnessAnimation, startInnovationGlassAnimation } from './animationManager.js';

// Transition state management
export let currentScene = 0; // 0: bold, 1: innovation, 2: agility, 3: storytelling
export let isTransitioning = false;
export const fadeSpeed = 1; // Easily adjustable fade speed
export const transitionDuration = 1; // Easily adjustable transition duration (seconds)
export let scrollDownCount = 0;
export let scrollUpCount = 0;
export const scrollThreshold = 10; // Changed to 10 as requested
export let transitionStartTime = 0;
export let transitionDirection = 1; // 1 for forward, -1 for backward

// Camera-relative transition vectors
export let transitionUpVector = new THREE.Vector3();
export let transitionDownVector = new THREE.Vector3();
export const transitionDistance = 50; // Increased distance for more dramatic transitions

// Scene objects
export let currentModel = null;
export let nextModel = null;
export let mixer = null;
export let nextMixer = null;
export let autoRotationAngle = 0;

// Setter functions to modify exported variables safely
export function setCurrentModel(model) {
  currentModel = model;
}

export function setMixer(animMixer) {
  mixer = animMixer;
}

export function setNextModel(model) {
  nextModel = model;
}

export function setNextMixer(animMixer) {
  nextMixer = animMixer;
}

// Calculate camera-relative transition vectors for diagonal movement
export function calculateTransitionVectors(camera) {
  // Get camera's world direction
  const cameraDirection = new THREE.Vector3();
  camera.getWorldDirection(cameraDirection);
  // Get world up vector
  const worldUp = new THREE.Vector3(0, 1, 0);
  // Calculate camera's left vector - BACK TO ORIGINAL (this gave correct left direction)
  const cameraLeft = new THREE.Vector3();
  cameraLeft.crossVectors(worldUp, cameraDirection).normalize();
  // Calculate camera's local up vector
  const cameraUp = new THREE.Vector3();
  cameraUp.crossVectors(cameraLeft, cameraDirection).normalize();
  // Blend camera up with world up - BUT NEGATE to flip up/down direction
  const blendedUp = new THREE.Vector3();
  blendedUp.addVectors(
    cameraUp.clone().multiplyScalar(0.5),
    worldUp.clone().multiplyScalar(0.5)
  ).normalize().negate(); // ADD .negate() here to flip up to down
  // Create diagonal vector (up-left)
  const diagonalUpLeft = new THREE.Vector3();
  diagonalUpLeft.addVectors(
    blendedUp.clone().multiplyScalar(0.5),
    cameraLeft.clone().multiplyScalar(0.5)
  ).normalize();
  // Set transition vectors
  transitionUpVector = diagonalUpLeft.clone().multiplyScalar(transitionDistance);
  transitionDownVector = diagonalUpLeft.clone().multiplyScalar(-transitionDistance);
  console.log('Diagonal transition vectors calculated with distance:', transitionDistance);
}

// Start transition to next or previous scene
export function startTransition(direction = 1, preloadedModels, scene, camera, controls) {
  if (isTransitioning) return;
  // Check bounds - now 4 scenes (0-3)
  if (direction > 0 && currentScene >= 3) return; // Can't go forward from storytelling
  if (direction < 0 && currentScene <= 0) return; // Can't go backward from bold

  console.log(`Starting diagonal transition: direction=${direction}, currentScene=${currentScene}`);
  // Calculate camera-relative diagonal transition vectors
  calculateTransitionVectors(camera);

  isTransitioning = true;
  transitionStartTime = performance.now();
  transitionDirection = direction;

  // Determine next model based on direction and current scene
  let nextModelType = '';
  if (direction > 0) {
    // Moving forward
    if (currentScene === 0) {
      nextModelType = 'innovation';
    } else if (currentScene === 1) {
      nextModelType = 'agility';
    } else if (currentScene === 2) {
      nextModelType = 'storytelling';
    }
  } else {
    // Moving backward
    if (currentScene === 1) {
      nextModelType = 'bold';
    } else if (currentScene === 2) {
      nextModelType = 'innovation';
    } else if (currentScene === 3) {
      nextModelType = 'agility';
    }
  }

  console.log(`Next model type: ${nextModelType}`);
  if (nextModelType) {
    const { model, animMixer } = createModelFromPreloaded(nextModelType, preloadedModels, camera, controls);
    nextModel = model;
    nextMixer = animMixer;

    // Position next model based on transition direction
    if (transitionDirection === 1) {
      // Forward: next model starts from diagonal down position (bottom-right)
      nextModel.position.copy(transitionDownVector);
      console.log(`Next model positioned at diagonal down vector (bottom-right): x=${nextModel.position.x}, y=${nextModel.position.y}, z=${nextModel.position.z}`);
    } else {
      // Backward: next model starts from diagonal up position (top-left)
      nextModel.position.copy(transitionUpVector);
      console.log(`Next model positioned at diagonal up vector (top-left): x=${nextModel.position.x}, y=${nextModel.position.y}, z=${nextModel.position.z}`);
    }
    // Add next model to scene without opacity changes - it will appear instantly when it enters the camera view
    scene.add(nextModel);
  }
}

// Update transition animation
export function updateTransition(deltaTime, scene) {
  if (!isTransitioning) return;

  const elapsed = (performance.now() - transitionStartTime) / 1000;
  const transitionProgress = Math.min(elapsed / transitionDuration, 1);
  // Smooth easing function (ease-in-out)
  const easeInOut = (t) => t * t * (3 - 2 * t);
  const easedProgress = easeInOut(transitionProgress);

  if (currentModel) {
    // Move current model along diagonal vector based on transition direction
    let moveVector;
    if (transitionDirection === 1) {
      // Forward: current model moves top-left
      moveVector = transitionUpVector.clone().multiplyScalar(easedProgress);
      console.log('Current model moving top-left (forward transition)');
    } else {
      // Backward: current model moves bottom-right
      moveVector = transitionDownVector.clone().multiplyScalar(easedProgress);
      console.log('Current model moving bottom-right (backward transition)');
    }
    currentModel.position.copy(moveVector);
  }

  if (nextModel) {
    // Move next model from diagonal vector to center based on transition direction
    let moveVector;
    if (transitionDirection === 1) {
      // Forward: next model moves from bottom-right to center
      moveVector = transitionDownVector.clone().multiplyScalar(1 - easedProgress);
      console.log('Next model moving from bottom-right to center (forward transition)');
    } else {
      // Backward: next model moves from top-left to center
      moveVector = transitionUpVector.clone().multiplyScalar(1 - easedProgress);
      console.log('Next model moving from top-left to center (backward transition)');
    }
    nextModel.position.copy(moveVector);
  }

  // Complete transition
  if (transitionProgress >= 1) {
    console.log('Diagonal transition animation complete');
    // FIXED: Reset geometry before removing the model
    if (currentModel) {
      // Reset all geometry to original state before removal
      currentModel.traverse((object) => {
        if (object.isMesh) {
          resetMeshGeometry(object);
        }
      });
      // Clean up geometry user data completely
      cleanupGeometryData(currentModel);
      scene.remove(currentModel);
      console.log('Previous model removed from scene');
    }

    // Switch to next model
    if (nextModel) {
      currentModel = nextModel;
      mixer = nextMixer;
      // Reset position to center
      currentModel.position.set(0, 0, 0);
    }

    nextModel = null;
    nextMixer = null;
    isTransitioning = false;
    currentScene += transitionDirection; // Update scene based on direction
    scrollDownCount = 0;
    scrollUpCount = 0;

    // Start animations based on current scene
    if (currentScene === 0) {
      // Restart bold roughness animation when returning to bold section WITHOUT delay
      startBoldRoughnessAnimation(false);
    } else if (currentScene === 1) {
      startInnovationGlassAnimation();
    }

    console.log(`Diagonal transition complete. Current scene: ${currentScene}`);
  }
}

// Scroll event handler
export function onMouseScroll(event, preloadedModels, scene, camera, controls) {
  if (isTransitioning) return;

  if (event.deltaY > 0) {
    // Scrolling down - move forward
    scrollDownCount++;
    scrollUpCount = 0; // Reset up count
    console.log(`Scroll down count: ${scrollDownCount}`);
    if (scrollDownCount >= scrollThreshold) {
      startTransition(1, preloadedModels, scene, camera, controls); // Forward direction
    }
  } else if (event.deltaY < 0) {
    // Scrolling up - move backward
    scrollUpCount++;
    scrollDownCount = 0; // Reset down count
    console.log(`Scroll up count: ${scrollUpCount}`);
    if (scrollUpCount >= scrollThreshold) {
      startTransition(-1, preloadedModels, scene, camera, controls); // Backward direction
    }
  }
}
