package game

import (
	"math"

	rl "github.com/gen2brain/raylib-go/raylib"
)

var (
	cameraDistance = float32(20.0)
	cameraYaw      = float32(145.0)
	cameraPitch    = float32(45.0)
	lastMousePos   rl.Vector2 // Add this to track mouse movement
)

func UpdateCamera(camera *rl.Camera3D, player rl.Vector3, deltaTime float32) {
	// Adjust target position to be at character's torso height (about half character height)
	characterHeight := float32(32.0) // Assuming character is roughly 32 units tall
	targetPos := rl.Vector3{
		X: player.X,
		Y: player.Y + characterHeight*0.5, // Focus on middle of character
		Z: player.Z,
	}

	wheelMove := rl.GetMouseWheelMove()
	if wheelMove != 0 {
		cameraDistance += -wheelMove * 5
		if cameraDistance < 10 {
			cameraDistance = 10
		}
		if cameraDistance > 250 {
			cameraDistance = 250
		}
	}

	// Handle middle mouse camera rotation
	if rl.IsMouseButtonDown(rl.MouseMiddleButton) {
		currentMousePos := rl.GetMousePosition()

		// If we just started holding the button, initialize last position
		if !rl.IsMouseButtonPressed(rl.MouseMiddleButton) {
			mouseDelta := rl.Vector2{
				X: currentMousePos.X - lastMousePos.X,
				Y: currentMousePos.Y - lastMousePos.Y,
			}

			// Adjust rotation speed as needed
			cameraYaw += mouseDelta.X * 0.5 * deltaTime * 60
			cameraPitch += mouseDelta.Y * 0.5 * deltaTime * 60

			// Clamp pitch to prevent camera flipping
			if cameraPitch < 20 {
				cameraPitch = 20
			}
			if cameraPitch > 85 {
				cameraPitch = 85
			}
		}

		lastMousePos = currentMousePos
	}

	// Keep the keyboard controls too
	if rl.IsKeyDown(rl.KeyRight) {
		cameraYaw += 100 * deltaTime
	}
	if rl.IsKeyDown(rl.KeyLeft) {
		cameraYaw -= 100 * deltaTime
	}
	if rl.IsKeyDown(rl.KeyUp) {
		cameraPitch -= 50 * deltaTime
		if cameraPitch < 20 {
			cameraPitch = 20
		}
	}
	if rl.IsKeyDown(rl.KeyDown) {
		cameraPitch += 50 * deltaTime
		if cameraPitch > 85 {
			cameraPitch = 85
		}
	}

	cameraYawRad := float64(cameraYaw) * rl.Deg2rad
	cameraPitchRad := float64(cameraPitch) * rl.Deg2rad

	camera.Position = rl.Vector3{
		X: targetPos.X + cameraDistance*float32(math.Cos(cameraYawRad))*float32(math.Cos(cameraPitchRad)),
		Y: targetPos.Y + cameraDistance*float32(math.Sin(cameraPitchRad)),
		Z: targetPos.Z + cameraDistance*float32(math.Sin(cameraYawRad))*float32(math.Cos(cameraPitchRad)),
	}
	camera.Target = targetPos
}
