package me.khodak.claudeusage

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF

/**
 * Draws a usage bar as a Bitmap: rounded track + rounded fill + an optional vertical pace tick.
 * Used both in the home-screen widget (setImageViewBitmap) and the in-app card, so the two render
 * identically. Bitmaps are rendered at a fixed width and stretched horizontally via ImageView
 * scaleType=fitXY; height is fixed so there is no vertical distortion.
 */
object BarRenderer {

    private const val TRACK_COLOR = 0xFF252525.toInt()

    fun render(
        usedPct: Int,
        markerPct: Int?,
        fillColor: Int,
        markerColor: Int?,
        wPx: Int = 500,
        hPx: Int = 14,
        cornerPx: Float = 7f
    ): Bitmap {
        val bmp = Bitmap.createBitmap(wPx, hPx, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bmp)
        val paint = Paint(Paint.ANTI_ALIAS_FLAG)

        // Track
        paint.color = TRACK_COLOR
        val full = RectF(0f, 0f, wPx.toFloat(), hPx.toFloat())
        canvas.drawRoundRect(full, cornerPx, cornerPx, paint)

        // Fill
        val pct = usedPct.coerceIn(0, 100)
        if (pct > 0) {
            paint.color = fillColor
            val fillW = (wPx * pct / 100f).coerceAtLeast(cornerPx * 2)
            val fill = RectF(0f, 0f, fillW, hPx.toFloat())
            canvas.drawRoundRect(fill, cornerPx, cornerPx, paint)
        }

        // Pace marker — a single clean tick showing "where you should be right now".
        // One color (no tiers); rounded ends to match the bar.
        if (markerPct != null && markerColor != null) {
            val m = markerPct.coerceIn(0, 100)
            val tickW = (wPx * 0.016f).coerceIn(6f, 10f)
            var x = wPx * m / 100f
            x = x.coerceIn(tickW / 2f, wPx - tickW / 2f)
            paint.color = markerColor
            val tick = RectF(x - tickW / 2f, 0f, x + tickW / 2f, hPx.toFloat())
            canvas.drawRoundRect(tick, tickW / 2f, tickW / 2f, paint)
        }

        return bmp
    }
}
