<?php

namespace PHPNative\Ui\Widget;

use PHPNative\Framework\TextRenderer;
use PHPNative\Ui\Component;

class ProgressBar extends Component
{
    private float $value = 0.0; // 0.0 - 1.0

    public function __construct(string $style = '')
    {
        // Basis: volle Breite, kleine Höhe
        $defaultStyle = 'w-full h-[8]';
        parent::__construct(trim($defaultStyle . ' ' . $style));
    }

    public function setValue(float $value): void
    {
        $clamped = max(0.0, min(1.0, $value));
        if ($this->value === $clamped) {
            return;
        }
        $this->value = $clamped;
        $this->markDirty(false);
    }

    public function getValue(): float
    {
        return $this->value;
    }

    public function layout(null|TextRenderer $textRenderer = null): void
    {
        parent::layout($textRenderer);

        // Mindesthöhe sicherstellen
        if ($this->viewport->height < 4) {
            $this->viewport->height = 4;
            $this->contentViewport->height = 4;
        }
    }

    public function renderContent(&$renderer, null|TextRenderer $textRenderer = null): void
    {
        if (!$this->visible) {
            return;
        }

        $x = (int) $this->contentViewport->x;
        $y = (int) $this->contentViewport->y;
        $w = (int) $this->contentViewport->width;
        $h = (int) $this->contentViewport->height;

        if ($w <= 0 || $h <= 0) {
            return;
        }

        // Hintergrund (Track)
        sdl_set_render_draw_color($renderer, 220, 220, 220, 255);
        sdl_render_fill_rect($renderer, [
            'x' => $x,
            'y' => $y,
            'w' => $w,
            'h' => $h,
        ]);

        // Fortschrittsbalken
        $fillWidth = (int) floor($w * $this->value);
        if ($fillWidth <= 0) {
            return;
        }

        sdl_set_render_draw_color($renderer, 59, 130, 246, 255); // Tailwind blue-500
        sdl_render_fill_rect($renderer, [
            'x' => $x,
            'y' => $y,
            'w' => $fillWidth,
            'h' => $h,
        ]);
    }
}

