package render

import (
	"math"

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

type ScaleFlags byte

const (
	// Use integer scaling (pixel-perfect). Implies SCALE_NO_DOWNSCALE because integer < 1 becomes 0.
	SCALE_INTEGER ScaleFlags = 1 << iota

	// Do not allow shrinking below 1 (clamp scale >= 1).
	SCALE_NO_DOWNSCALE

	// Use "cover" (crop) instead of "contain" (letterbox). Default is contain.
	SCALE_COVER
)

func scale(srcW, srcH, destW, destH int32, flags ScaleFlags) rl.Rectangle {
	scale := float64(1)
	sx := float64(destW) / float64(srcW)
	sy := float64(destH) / float64(srcH)

	// Contain (letterbox) uses min; Cover (crop) uses max.
	if flags&SCALE_COVER != 0 {
		scale = math.Max(sx, sy)
	} else {
		scale = math.Min(sx, sy)
	}

	if flags&SCALE_INTEGER != 0 {
		// For contain, floor; for cover, ceil.
		if flags&SCALE_COVER != 0 {
			scale = math.Ceil(scale)
		} else {
			scale = math.Floor(scale)
		}
		// IntegerScale implies no fractional; clamp at 1 to avoid zero.
		scale = max(1.0, scale)
	} else if flags&SCALE_NO_DOWNSCALE != 0 && scale < 1.0 {
		scale = 1.0
	}

	w := float64(srcW) * scale
	h := float64(srcH) * scale

	return rl.Rectangle{
		X:      float32(math.Floor((float64(destW) - w) / 2.0)),
		Y:      float32(math.Floor((float64(destH) - h) / 2.0)),
		Width:  float32(w),
		Height: float32(h),
	}
}
