package main

import (
	"fmt"
	"image/color"
	"log"
	"math"

	"github.com/hajimehoshi/ebiten/v2"
	"github.com/hajimehoshi/ebiten/v2/inpututil"
	"github.com/hajimehoshi/ebiten/v2/text"
	"github.com/hajimehoshi/ebiten/v2/vector"
	"golang.org/x/image/font/basicfont"
)

// --- INPUT & UPDATE LOGIC ---

func (g *Game) UpdateGame() {
	// --- 1. KEYBOARD INPUT ---
	keyLeft := ebiten.IsKeyPressed(ebiten.KeyA) || ebiten.IsKeyPressed(ebiten.KeyLeft)
	keyRight := ebiten.IsKeyPressed(ebiten.KeyD) || ebiten.IsKeyPressed(ebiten.KeyRight)
	keyDown := inpututil.IsKeyJustPressed(ebiten.KeyS) || inpututil.IsKeyJustPressed(ebiten.KeyDown)
	keyJump := inpututil.IsKeyJustPressed(ebiten.KeySpace) || inpututil.IsKeyJustPressed(ebiten.KeyW) || inpututil.IsKeyJustPressed(ebiten.KeyUp)

	// --- 2. TOUCH INPUT HANDLING ---
	g.handleTouchInput()

	// --- 3. INPUT STATE ERSTELLEN ---
	joyDir := 0.0
	if g.joyActive {
		diffX := g.joyStickX - g.joyBaseX
		if diffX < -20 {
			joyDir = -1
		}
		if diffX > 20 {
			joyDir = 1
		}
	}

	isJoyDown := g.joyActive && (g.joyStickY-g.joyBaseY) > 40

	// Input State zusammenbauen
	input := InputState{
		Sequence: g.inputSequence,
		Left:     keyLeft || joyDir == -1,
		Right:    keyRight || joyDir == 1,
		Jump:     keyJump || g.btnJumpActive,
		Down:     keyDown || isJoyDown,
	}
	g.btnJumpActive = false

	// --- 4. CLIENT PREDICTION ---
	if g.connected {
		// Sequenznummer erhöhen
		g.inputSequence++
		input.Sequence = g.inputSequence

		// Input speichern für später Reconciliation
		g.pendingInputs[input.Sequence] = input

		// Lokale Physik sofort anwenden (Prediction)
		g.ApplyInput(input)

		// Input an Server senden
		g.SendInputWithSequence(input)
	}

	// --- 5. KAMERA LOGIK ---
	g.stateMutex.Lock()
	defer g.stateMutex.Unlock()

	// Wir folgen strikt dem Server-Scroll.
	targetCam := g.gameState.ScrollX

	// Negative Kamera verhindern
	if targetCam < 0 {
		targetCam = 0
	}

	// Kamera hart setzen
	g.camX = targetCam
}

// Verarbeitet Touch-Eingaben für Joystick und Buttons
func (g *Game) handleTouchInput() {
	touches := ebiten.TouchIDs()

	// Reset, wenn keine Finger mehr auf dem Display sind
	if len(touches) == 0 {
		g.joyActive = false
		g.joyStickX = g.joyBaseX
		g.joyStickY = g.joyBaseY
		return
	}

	joyFound := false

	for _, id := range touches {
		x, y := ebiten.TouchPosition(id)
		fx, fy := float64(x), float64(y)

		// 1. RECHTE SEITE: JUMP BUTTON
		// Alles rechts der Bildschirmmitte ist "Springen"
		if fx > ScreenWidth/2 {
			// Prüfen, ob dieser Touch gerade NEU dazu gekommen ist
			for _, justID := range inpututil.JustPressedTouchIDs() {
				if id == justID {
					g.btnJumpActive = true
					break
				}
			}
			continue
		}

		// 2. LINKE SEITE: JOYSTICK
		// Wenn wir noch keinen Joystick-Finger haben, prüfen wir, ob dieser Finger startet
		if !g.joyActive {
			// Prüfen ob Touch in der Nähe der Joystick-Basis ist (Radius 150 Toleranz)
			dist := math.Sqrt(math.Pow(fx-g.joyBaseX, 2) + math.Pow(fy-g.joyBaseY, 2))
			if dist < 150 {
				g.joyActive = true
				g.joyTouchID = id
			}
		}

		// Wenn das der Joystick-Finger ist -> Stick bewegen
		if g.joyActive && id == g.joyTouchID {
			joyFound = true

			// Vektor berechnen (Wie weit ziehen wir weg?)
			dx := fx - g.joyBaseX
			dy := fy - g.joyBaseY
			dist := math.Sqrt(dx*dx + dy*dy)
			maxDist := 60.0 // Maximaler Radius des Sticks

			// Begrenzen auf Radius
			if dist > maxDist {
				scale := maxDist / dist
				dx *= scale
				dy *= scale
			}

			g.joyStickX = g.joyBaseX + dx
			g.joyStickY = g.joyBaseY + dy
		}
	}

	// Wenn der Joystick-Finger losgelassen wurde, Joystick resetten
	if !joyFound {
		g.joyActive = false
		g.joyStickX = g.joyBaseX
		g.joyStickY = g.joyBaseY
	}
}

// --- RENDERING LOGIC ---

func (g *Game) DrawGame(screen *ebiten.Image) {
	// 1. Hintergrund & Boden
	screen.Fill(ColSky)

	floorH := float32(ScreenHeight - RefFloorY)
	vector.DrawFilledRect(screen, 0, float32(RefFloorY), float32(ScreenWidth), floorH, ColGrass, false)
	vector.DrawFilledRect(screen, 0, float32(RefFloorY)+20, float32(ScreenWidth), floorH-20, ColDirt, false)

	// State Locken für Datenzugriff
	g.stateMutex.Lock()
	defer g.stateMutex.Unlock()

	// 2. Chunks (Welt-Objekte)
	for _, activeChunk := range g.gameState.WorldChunks {
		chunkDef, exists := g.world.ChunkLibrary[activeChunk.ChunkID]
		if !exists {
			log.Printf("⚠️ Chunk '%s' nicht in Library gefunden!", activeChunk.ChunkID)
			continue
		}

		// DEBUG: Chunk-Details loggen (nur einmal)
		if len(chunkDef.Objects) == 0 {
			log.Printf("⚠️ Chunk '%s' hat 0 Objekte! Width=%d", activeChunk.ChunkID, chunkDef.Width)
		}

		for _, obj := range chunkDef.Objects {
			// Asset zeichnen
			g.DrawAsset(screen, obj.AssetID, activeChunk.X+obj.X, obj.Y)
		}
	}

	// 3. Spieler
	// MyID ohne Lock holen (wir haben bereits den stateMutex)
	myID := ""
	for id, p := range g.gameState.Players {
		if p.Name == g.playerName {
			myID = id
			break
		}
	}

	for id, p := range g.gameState.Players {
		// Für lokalen Spieler: Verwende vorhergesagte Position
		posX, posY := p.X, p.Y
		if id == myID && g.connected {
			posX = g.predictedX
			posY = g.predictedY
		}

		g.DrawAsset(screen, "player", posX, posY)

		// Name Tag
		name := p.Name
		if name == "" {
			name = id
		}
		text.Draw(screen, name, basicfont.Face7x13, int(posX-g.camX), int(posY-25), ColText)

		// DEBUG: Rote Hitbox
		if def, ok := g.world.Manifest.Assets["player"]; ok {
			hx := float32(posX + def.DrawOffX + def.Hitbox.OffsetX - g.camX)
			hy := float32(posY + def.DrawOffY + def.Hitbox.OffsetY)
			vector.StrokeRect(screen, hx, hy, float32(def.Hitbox.W), float32(def.Hitbox.H), 2, color.RGBA{255, 0, 0, 255}, false)
		}
	}

	// 4. UI Status
	if g.gameState.Status == "COUNTDOWN" {
		msg := fmt.Sprintf("GO IN: %d", g.gameState.TimeLeft)
		text.Draw(screen, msg, basicfont.Face7x13, ScreenWidth/2-40, ScreenHeight/2, color.RGBA{255, 255, 0, 255})
	} else if g.gameState.Status == "RUNNING" {
		dist := fmt.Sprintf("Distance: %.0f m", g.camX/64.0)
		text.Draw(screen, dist, basicfont.Face7x13, ScreenWidth-150, 30, ColText)

		// Score anzeigen
		for _, p := range g.gameState.Players {
			if p.Name == g.playerName {
				scoreStr := fmt.Sprintf("Score: %d", p.Score)
				text.Draw(screen, scoreStr, basicfont.Face7x13, ScreenWidth-150, 50, ColText)
				break
			}
		}
	} else if g.gameState.Status == "GAMEOVER" {
		// Game Over Screen mit allen Scores
		text.Draw(screen, "GAME OVER", basicfont.Face7x13, ScreenWidth/2-50, 100, color.RGBA{255, 0, 0, 255})

		y := 150
		for _, p := range g.gameState.Players {
			scoreMsg := fmt.Sprintf("%s: %d pts", p.Name, p.Score)
			text.Draw(screen, scoreMsg, basicfont.Face7x13, ScreenWidth/2-80, y, color.White)
			y += 20
		}
	}

	// 5. DEBUG: TODES-LINIE
	vector.StrokeLine(screen, 0, 0, 0, float32(ScreenHeight), 10, color.RGBA{255, 0, 0, 128}, false)
	text.Draw(screen, "! DEATH ZONE !", basicfont.Face7x13, 10, ScreenHeight/2, color.RGBA{255, 0, 0, 255})

	// 6. TOUCH CONTROLS OVERLAY

	// A) Joystick Base
	baseCol := color.RGBA{255, 255, 255, 50}
	vector.DrawFilledCircle(screen, float32(g.joyBaseX), float32(g.joyBaseY), 60, baseCol, true)
	vector.StrokeCircle(screen, float32(g.joyBaseX), float32(g.joyBaseY), 60, 2, color.RGBA{255, 255, 255, 100}, true)

	// B) Joystick Knob
	knobCol := color.RGBA{255, 255, 255, 150}
	if g.joyActive {
		knobCol = color.RGBA{100, 255, 100, 200}
	}
	vector.DrawFilledCircle(screen, float32(g.joyStickX), float32(g.joyStickY), 30, knobCol, true)

	// C) Jump Button (Rechts)
	jumpX := float32(ScreenWidth - 150)
	jumpY := float32(ScreenHeight - 150)
	vector.DrawFilledCircle(screen, jumpX, jumpY, 50, color.RGBA{255, 0, 0, 50}, true)
	vector.StrokeCircle(screen, jumpX, jumpY, 50, 2, color.RGBA{255, 0, 0, 100}, true)
	text.Draw(screen, "JUMP", basicfont.Face7x13, int(jumpX)-15, int(jumpY)+5, color.White)

	// 7. DEBUG INFO (Oben Links)
	myPosStr := "N/A"
	for _, p := range g.gameState.Players {
		myPosStr = fmt.Sprintf("X:%.0f Y:%.0f", p.X, p.Y)
		break
	}

	debugMsg := fmt.Sprintf(
		"FPS: %.2f\nState: %s\nPlayers: %d\nCamX: %.0f\nPos: %s",
		ebiten.CurrentFPS(),
		g.gameState.Status,
		len(g.gameState.Players),
		g.camX,
		myPosStr,
	)

	vector.DrawFilledRect(screen, 10, 10, 200, 90, color.RGBA{0, 0, 0, 180}, false)
	text.Draw(screen, debugMsg, basicfont.Face7x13, 20, 30, color.White)
}

// --- ASSET HELPER ---

func (g *Game) DrawAsset(screen *ebiten.Image, assetID string, worldX, worldY float64) {
	// 1. Definition laden
	def, ok := g.world.Manifest.Assets[assetID]
	if !ok {
		return
	}

	// 2. Screen Position berechnen (Welt - Kamera)
	screenX := worldX - g.camX
	screenY := worldY

	// Optimierung: Nicht zeichnen, wenn komplett außerhalb
	if screenX < -200 || screenX > ScreenWidth+200 {
		return
	}

	// 3. Bild holen
	img := g.assetsImages[assetID]

	if img != nil {
		op := &ebiten.DrawImageOptions{}

		// Filter für bessere Skalierung (besonders bei großen Sprites)
		op.Filter = ebiten.FilterLinear

		// Skalieren
		op.GeoM.Scale(def.Scale, def.Scale)

		// Positionieren: ScreenPos + DrawOffset
		op.GeoM.Translate(
			screenX+def.DrawOffX,
			screenY+def.DrawOffY,
		)

		// Farbe anwenden (nur wenn explizit gesetzt)
		// Wenn Color leer ist (R=G=B=A=0), nicht anwenden (Bild bleibt original)
		if def.Color.R != 0 || def.Color.G != 0 || def.Color.B != 0 || def.Color.A != 0 {
			op.ColorScale.ScaleWithColor(def.Color.ToRGBA())
		}

		screen.DrawImage(img, op)
	} else {
		// FALLBACK (Buntes Rechteck)
		vector.DrawFilledRect(screen,
			float32(screenX+def.Hitbox.OffsetX),
			float32(screenY+def.Hitbox.OffsetY),
			float32(def.Hitbox.W),
			float32(def.Hitbox.H),
			def.Color.ToRGBA(),
			false,
		)
	}
}
