package com.example.livingai.ui.overlay

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.View

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

    private val paint = Paint().apply {
        color = Color.GREEN
        style = Paint.Style.STROKE
        strokeWidth = 5f
    }

    private val silhouettePaint = Paint().apply {
        alpha = 128 // 50% opacity
    }

    private var silhouette: Bitmap? = null

    fun setSilhouette(drawableId: Int) {
        try {
            if (drawableId != 0) {
                silhouette = BitmapFactory.decodeResource(resources, drawableId)
            } else {
                silhouette = null
            }
            invalidate()
        } catch (e: Exception) {
            Log.e("SilhouetteOverlay", "Error loading silhouette", e)
        }
    }

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

        silhouette?.let { bmp ->

            val viewW = width.toFloat()
            val viewH = height.toFloat()
            val bmpW = bmp.width.toFloat()
            val bmpH = bmp.height.toFloat()

            // Calculate scale to fit (FIT_CENTER)
            val scale = kotlin.math.min(viewW / bmpW, viewH / bmpH)

            val scaledW = bmpW * scale
            val scaledH = bmpH * scale

            val left = (viewW - scaledW) / 2f
            val top = (viewH - scaledH) / 2f

            val destRect = RectF(left, top, left + scaledW, top + scaledH)
            val srcRect = Rect(0, 0, bmp.width, bmp.height)

            canvas.drawBitmap(bmp, srcRect, destRect, silhouettePaint)
        }
    }
}