package com.performancecoachlab.posedetection.camera

import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.withTransform
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextMeasurer
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText

actual fun DrawScope.drawLabelTextPlatform(
    drawableObject: DrawableObject,
    textMeasurer: TextMeasurer?
) {
    val label =
        drawableObject.obj.labels.firstOrNull()?.text.let { if (it.isNullOrBlank()) "Object" else it }
    if (label.isEmpty() || textMeasurer == null) 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

    // Measure once at a base size and re-use that exact layout result for drawing.
    // On iOS, measuring and drawing can diverge if we re-measure or rely on fontSize conversions.
    val baseStyle = TextStyle(
        color = drawableObject.colour,
        // Use a stable base size; the final size will come from scaling the canvas.
        fontSize = 100f.toSp()
    )

    val layout: TextLayoutResult = textMeasurer.measure(
        text = label,
        style = baseStyle,
        maxLines = 1
    )

    val baseWidth = layout.size.width.toFloat()
    val baseHeight = layout.size.height.toFloat()
    if (baseWidth <= 0f || baseHeight <= 0f) return

    val scale = minOf(boxWidth / baseWidth, boxHeight / baseHeight)
    val scaledWidth = baseWidth * scale
    val scaledHeight = baseHeight * scale

    val centerX = boxLeft + boxWidth / 2f
    val centerY = boxTop + boxHeight / 2f
    val x = centerX - scaledWidth / 2f
    val y = centerY - scaledHeight / 2f

    withTransform({
        // Keep (x,y) fixed; scale relative to that same top-left.
        scale(scaleX = scale, scaleY = scale, pivot = Offset(x, y))
    }) {
        drawText(
            textLayoutResult = layout,
            topLeft = Offset(x, y)
        )
    }
}