package com.performancecoachlab.posedetection.camera

import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.text.TextMeasurer

actual fun DrawScope.drawLabelTextPlatform(
    drawableObject: DrawableObject,
    textMeasurer: TextMeasurer?
) {
    val label = drawableObject.obj.labels.firstOrNull()?.text ?: "Object"
    if (label.isEmpty()) return

    val box = drawableObject.obj.boundingBox
    val boxLeft = box.left
    val boxTop = box.top
    val boxWidth = box.width
    val boxHeight = box.height

    if (boxWidth <= 0f || boxHeight <= 0f) return

    // Padding inside the box so text doesn't touch the edges
    val paddingX = boxWidth * 0.08f
    val paddingY = boxHeight * 0.12f

    val availableWidth = (boxWidth - 2 * paddingX).coerceAtLeast(1f)
    val availableHeight = (boxHeight - 2 * paddingY).coerceAtLeast(1f)

    // Start with a reasonable text size relative to box height
    val baseTextSizePx = (boxHeight * 0.5f).coerceAtLeast(8f)

    val paint = android.graphics.Paint().apply {
        isAntiAlias = true
        color = drawableObject.colour.toArgb()
        textAlign = android.graphics.Paint.Align.LEFT
        textSize = baseTextSizePx
    }

    val textBounds = android.graphics.Rect()
    paint.getTextBounds(label, 0, label.length, textBounds)
    var textWidth = textBounds.width().toFloat().coerceAtLeast(1f)
    var textHeight = textBounds.height().toFloat().coerceAtLeast(1f)

    // Compute scale factors to fit text within available area
    val scaleX = availableWidth / textWidth
    val scaleY = availableHeight / textHeight
    val scale = minOf(scaleX, scaleY, 1f) // never scale up, only down

    if (scale < 1f) {
        paint.textSize = baseTextSizePx * scale
        paint.getTextBounds(label, 0, label.length, textBounds)
        textWidth = textBounds.width().toFloat()
        textHeight = textBounds.height().toFloat()
    }

    // Center text within the box, respecting padding
    val x = boxLeft + paddingX + (availableWidth - textWidth) / 2f
    val y = boxTop + paddingY + (availableHeight + textHeight) / 2f

    drawContext.canvas.nativeCanvas.drawText(label, x, y, paint)
}
