package main

import (
	"fmt"
	"log"
	"path/filepath"
	"time"

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

// ShowUpdateWindow displays the update GUI.
func ShowUpdateWindow() {

	var sf StateFile
	sf = ReadState()

	if sf.IsUpdating == true {

		log.Println("Stage=Installing => show update window.")

		screenW := 300
		screenH := 450
		rl.SetConfigFlags(rl.FlagWindowUndecorated)
		rl.InitWindow(int32(screenW), int32(screenH), "Updating Spitfire")

		monitor := rl.GetCurrentMonitor()
		refreshRate := rl.GetMonitorRefreshRate(monitor)
		rl.SetTargetFPS(int32(refreshRate))

		InitBackground(screenW, screenH)

		logoPath := filepath.Join(getSpmDir(), "logo.png")
		logo := rl.LoadTexture(logoPath)
		defer rl.UnloadTexture(logo)

		var displayed float32
		scale := float32(0.5)

		// Update state asynchronously in a separate goroutine
		go func() {
			for {
				sf = ReadState()
				time.Sleep(1 * time.Second)
			}
		}()

		for {
			tgt := float32(sf.Progress)

			if rl.WindowShouldClose() {
				break
			}

			// Smooth interpolation for displayed progress
			displayed += (tgt - displayed) * 0.15

			rl.BeginDrawing()
			rl.ClearBackground(rl.Black)

			// 2 px inside border for visibility
			rl.DrawRectangleLinesEx(
				rl.Rectangle{X: 1, Y: 1, Width: float32(screenW - 2), Height: float32(screenH - 2)},
				2,
				rl.White,
			)

			UpdateBackground(screenW, screenH)
			DrawBackground(screenW, screenH)

			// Draw logo scaled
			lw := float32(logo.Width) * scale
			lx := float32(screenW)/2 - lw/2
			ly := float32(20)
			rl.DrawTextureEx(logo, rl.Vector2{X: lx, Y: ly}, 0, scale, rl.White)

			// Progress bar
			barW := float32(screenW - 60)
			barH := float32(20)
			barX := float32(30)
			barY := float32(screenH/2 + 40)
			frac := displayed / 100.0
			if frac < 0 {
				frac = 0
			} else if frac > 1 {
				frac = 1
			}

			fillRect := rl.Rectangle{X: barX, Y: barY, Width: barW * frac, Height: barH}
			fullRect := rl.Rectangle{X: barX, Y: barY, Width: barW, Height: barH}
			corner := float32(0.4)

			rl.DrawRectangleRounded(fillRect, corner, 6, rl.RayWhite)
			rl.DrawRectangleRoundedLines(fullRect, corner, 6, rl.White)

			// Display status text
			msg := updateStatusMsg
			if !sf.IsUpdating {
				msg = "Update complete!"
			}
			fontSize := int32(20)
			txtW := rl.MeasureText(msg, fontSize)
			txtX := (int32(screenW) - txtW) / 2
			txtY := int32(barY) - 30
			rl.DrawText(msg, txtX, txtY, fontSize, rl.White)

			// Display numeric progress
			progStr := fmt.Sprintf("%.0f%%", displayed)
			pw := rl.MeasureText(progStr, 20)
			px := (int32(screenW) - pw) / 2
			py := int32(barY) + 30
			rl.DrawText(progStr, px, py, 20, rl.White)

			rl.EndDrawing()

			// If no longer updating => break window loop
			if !sf.IsUpdating {
				break
			}
		}

		rl.CloseWindow()

	}

	LaunchBrowser()
}