package screens

import (
	"image/color"
	"time"

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

var (
	basicFace       = text.NewGoXFace(basicfont.Face7x13)
	basicFaceAscent = basicFace.Metrics().HAscent
)

// Timing

const (
	splashDuration  = 2 * time.Second
	fadeInDuration  = 500 * time.Millisecond
	fadeOutDuration = 500 * time.Millisecond
)

type SplashScreen struct {
	startTime    time.Time
	fadeInEnd    time.Time
	fadeOutStart time.Time
	endTime      time.Time
}

func NewSplashScreen() *SplashScreen {
	now := time.Now()
	return &SplashScreen{
		startTime:    now,
		fadeInEnd:    now.Add(fadeInDuration),
		fadeOutStart: now.Add(splashDuration - fadeOutDuration),
		endTime:      now.Add(splashDuration),
	}
}

func (s *SplashScreen) Update() bool {
	if time.Now().After(s.endTime) {
		return true
	}

	if inpututil.IsKeyJustPressed(ebiten.KeySpace) ||
		inpututil.IsKeyJustPressed(ebiten.KeyEnter) ||
		inpututil.IsKeyJustPressed(ebiten.KeyEscape) {
		return true
	}

	return false
}

// Rendering

func (s *SplashScreen) Draw(screen *ebiten.Image, screenWidth, screenHeight int) {
	screen.Fill(color.RGBA{R: 0, G: 0, B: 0, A: 255})

	now := time.Now()
	alpha := 1.0

	if now.Before(s.fadeInEnd) {
		elapsed := now.Sub(s.startTime)
		alpha = float64(elapsed) / float64(fadeInDuration)
	} else if now.After(s.fadeOutStart) {
		elapsed := now.Sub(s.fadeOutStart)
		alpha = 1.0 - (float64(elapsed) / float64(fadeOutDuration))
	}

	if alpha < 0 {
		alpha = 0
	} else if alpha > 1 {
		alpha = 1
	}

	// Draw title
	titleText := "LIL GUY"

	scale := 4.0
	charWidth := 7.0 * scale
	textWidth := float64(len(titleText)) * charWidth

	x := float64(screenWidth)/2 - textWidth/2
	y := float64(screenHeight) / 2

	op := &text.DrawOptions{}
	op.GeoM.Scale(scale, scale)
	op.GeoM.Translate(x, y-basicFaceAscent*scale)
	op.ColorScale.ScaleWithColor(color.White)
	op.ColorScale.ScaleAlpha(float32(alpha))
	text.Draw(screen, titleText, basicFace, op)
}
