package com.example.livingai.ui.overlay

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Matrix
import android.util.AttributeSet
import android.view.View
import kotlin.math.max
import kotlin.math.min

class MaskOverlay(context: Context, attrs: AttributeSet?) : View(context, attrs) {

    enum class ScaleType {
        CENTER_CROP,
        FIT_CENTER
    }

    private var maskBitmap: Bitmap? = null
    private val matrix = Matrix()
    var scaleType: ScaleType = ScaleType.CENTER_CROP

    fun updateMask(bitmap: Bitmap?) {
        maskBitmap = bitmap
        invalidate()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val bmp = maskBitmap ?: return
        if (bmp.width == 0 || bmp.height == 0) return

        val viewWidth = width.toFloat()
        val viewHeight = height.toFloat()
        val bmpWidth = bmp.width.toFloat()
        val bmpHeight = bmp.height.toFloat()

        matrix.reset()

        val scaleX = viewWidth / bmpWidth
        val scaleY = viewHeight / bmpHeight

        val scale = if (scaleType == ScaleType.FIT_CENTER) {
            min(scaleX, scaleY)
        } else {
            max(scaleX, scaleY)
        }

        val scaledWidth = bmpWidth * scale
        val scaledHeight = bmpHeight * scale

        val dx = (viewWidth - scaledWidth) / 2f
        val dy = (viewHeight - scaledHeight) / 2f

        matrix.postScale(scale, scale)
        matrix.postTranslate(dx, dy)

        canvas.drawBitmap(bmp, matrix, null)
    }
}
