<?php

declare(strict_types=1);

namespace Builder\Core\Foundation\Dashboard\Widgets;

use Builder\Core\Foundation\Dashboard\Enums\WidgetWidth;
use Closure;

/**
 * A chart widget supporting bar, line, or pie chart types.
 *
 * The dataset Closure should return a Chart.js-compatible dataset array.
 *
 * Example:
 *   new ChartWidget('signups', 'Signups', 'line', fn() => [
 *       'labels' => ['Jan', 'Feb', 'Mar'],
 *       'datasets' => [['data' => [10, 20, 15]]],
 *   ])
 */
class ChartWidget extends Widget
{
    protected WidgetWidth $width = WidgetWidth::Half;

    /**
     * @param  'bar'|'line'|'pie'  $chartType
     * @param  Closure():array<string, mixed>  $datasetResolver
     */
    public function __construct(
        private readonly string $key,
        private readonly string $label,
        private readonly string $chartType,
        private readonly Closure $datasetResolver,
    ) {}

    public function getKey(): string
    {
        return $this->key;
    }

    public function getLabel(): string
    {
        return $this->label;
    }

    public function getComponent(): string
    {
        return 'ChartWidget';
    }

    /** @return array<string, mixed> */
    public function getData(): array
    {
        return [
            'type' => $this->chartType,
            'dataset' => ($this->datasetResolver)(),
        ];
    }
}
