<?php

declare(strict_types=1);

namespace PpPhp\Plugins;

use PpPhp\Core\EditPlugin;
use PpPhp\Core\PluginSupport;

/**
 * A numeric range slider (native input) with a live value read-out. The slider is
 * the stored value; a self-invoking inline enhancer keeps the read-out in sync.
 */
class RangeSlider implements EditPlugin
{
    use PluginSupport;

    public static function id(): string { return 'RangeSlider'; }
    public static function label(): string { return 'Range Slider'; }
    public static function version(): string { return '1.0.0'; }
    public static function description(): string { return 'Pick a number on a slider with a live value read-out and configurable min/max/step.'; }

    public static function render(string $fieldName, mixed $value, array $settings): string
    {
        $name = self::e($fieldName);
        $min  = (float) ($settings['min'] ?? 0);
        $max  = (float) ($settings['max'] ?? 100);
        if ($max <= $min) $max = $min + 100;
        $step = (float) ($settings['step'] ?? 1);
        if ($step <= 0) $step = 1;

        $cur = ($value === null || $value === '') ? ($min + ($max - $min) / 2) : (float) $value;
        if ($cur < $min) $cur = $min;
        if ($cur > $max) $cur = $max;
        $curStr = self::e(rtrim(rtrim(number_format($cur, 4, '.', ''), '0'), '.'));

        $showValue = !in_array(strtolower((string) ($settings['showValue'] ?? 'yes')), ['0', 'no', 'false', 'off'], true);

        $html = '<span class="pp-range">'
            . '<input type="range" name="' . $name . '" id="field_' . $name . '" class="pp-range-in"'
            . ' min="' . self::e($min) . '" max="' . self::e($max) . '" step="' . self::e($step) . '" value="' . $curStr . '">'
            . ($showValue ? '<output class="pp-range-out">' . $curStr . '</output>' : '')
            . '</span>';

        return $html . self::enhancer();
    }

    public static function settingsSchema(): array
    {
        return [
            ['key' => 'min',       'type' => 'number', 'label' => 'Minimum', 'default' => 0],
            ['key' => 'max',       'type' => 'number', 'label' => 'Maximum', 'default' => 100],
            ['key' => 'step',      'type' => 'number', 'label' => 'Step', 'default' => 1],
            ['key' => 'showValue', 'type' => 'bool',   'label' => 'Show value', 'default' => 'yes'],
        ];
    }

    public static function assets(): array
    {
        return ['js' => [], 'css' => ['plugins/Edit/RangeSlider/range.css']];
    }

    private static function enhancer(): string
    {
        return <<<'HTML'
<script>
(function(){
  if (!window.__ppRangeInit) {
    window.__ppRangeInit = function(root){
      (root || document).querySelectorAll('.pp-range').forEach(function(box){
        if (box._ppRange) return; box._ppRange = true;
        var input = box.querySelector('.pp-range-in');
        var out = box.querySelector('.pp-range-out');
        if (!input || !out) return;
        var upd = function(){ out.textContent = input.value; };
        input.addEventListener('input', upd);
        upd();
      });
    };
  }
  if (document.readyState !== 'loading') window.__ppRangeInit();
  else document.addEventListener('DOMContentLoaded', function(){ window.__ppRangeInit(); });
})();
</script>
HTML;
    }
}
