package main

import (
	"bytes"
	"fmt"
	"image"
	_ "image/png"
	"image/color"
	"math/rand"
	"strings"
	"time"

	"github.com/hajimehoshi/ebiten/v2"
	"github.com/hajimehoshi/ebiten/v2/text"
	"github.com/skip2/go-qrcode"
	"golang.org/x/image/font/basicfont"

	"git.zb-server.de/ZB-Server/EscapeFromTeacher/pkg/game"
)

type presAssetInstance struct {
	AssetID string
	X, Y    float64
	VX      float64
	Scale   float64
}

// generateQRCode erstellt ein ebiten.Image aus einem QR-Code
func generateQRCode(url string) *ebiten.Image {
	pngData, err := qrcode.Encode(url, qrcode.Medium, 256)
	if err != nil {
		fmt.Println("Error generating QR code:", err)
		return nil
	}

	img, _, err := image.Decode(bytes.NewReader(pngData))
	if err != nil {
		fmt.Println("Error decoding QR code:", err)
		return nil
	}
	return ebiten.NewImageFromImage(img)
}

// updatePresentation verarbeitet die Logik für den Präsentationsmodus.
func (g *Game) updatePresentation() {
	now := time.Now()

	// Auto-Start Presentation Room when connected
	g.stateMutex.Lock()
	status := g.gameState.Status
	g.stateMutex.Unlock()

	if g.connected && status == "LOBBY" && g.isHost {
		g.SendCommand("START_PRESENTATION")
	}

	// 1. Zitat-Wechsel alle 6 Sekunden
	if now.After(g.presQuoteTime) {
		g.presQuote = game.GetRandomQuote()
		g.presQuoteTime = now.Add(6 * time.Second)
	}

	// 2. Assets spawnen (wenn zu wenige da sind)
	if len(g.presAssets) < 8 && rand.Float64() < 0.05 {
		// Wähle zufälliges Asset (Schüler, Lehrer, Items)
		assetList := []string{"player", "coin", "eraser", "pc-trash", "godmode", "jumpboost", "magnet"}
		id := assetList[rand.Intn(len(assetList))]
		
		g.presAssets = append(g.presAssets, presAssetInstance{
			AssetID: id,
			X:       float64(ScreenWidth + 100),
			Y:       float64(ScreenHeight - 150 - rand.Intn(100)),
			VX:      -(2.0 + rand.Float64()*4.0),
			Scale:   1.0 + rand.Float64()*0.5,
		})
	}

	// 3. Assets bewegen
	newAssets := g.presAssets[:0]
	for _, a := range g.presAssets {
		a.X += a.VX
		if a.X > -200 { // Noch im Bildbereich (mit Puffer)
			newAssets = append(newAssets, a)
		}
	}
	g.presAssets = newAssets
}

// DrawWrappedText zeichnet Text mit automatischem Zeilenumbruch.
func (g *Game) DrawWrappedText(screen *ebiten.Image, str string, x, y, maxWidth int, col color.Color) {
	words := strings.Split(str, " ")
	line := ""
	currY := y

	for _, w := range words {
		testLine := line + w + " "
		if len(testLine)*7 > maxWidth { // Grobe Schätzung Breite
			text.Draw(screen, line, basicfont.Face7x13, x-len(line)*7/2, currY, col)
			line = w + " "
			currY += 20
		} else {
			line = testLine
		}
	}
	text.Draw(screen, line, basicfont.Face7x13, x-len(line)*7/2, currY, col)
}
