<?php

declare(strict_types=1);

namespace PpPhp\Plugins;

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

/**
 * Colour input: a native swatch picker paired with an editable hex field, kept in
 * two-way sync by a self-invoking inline enhancer. The hex field is the stored
 * value (may be blank). Pair with the "Colour Swatch" view.
 */
class ColorPicker implements EditPlugin
{
    use PluginSupport;

    public static function id(): string { return 'ColorPicker'; }
    public static function label(): string { return 'Colour Picker'; }
    public static function version(): string { return '1.0.0'; }
    public static function description(): string { return 'Pick a colour from a swatch or type a hex value (two-way synced).'; }

    public static function render(string $fieldName, mixed $value, array $settings): string
    {
        $name = self::e($fieldName);
        $hex  = trim((string) ($value ?? ''));
        $valid = preg_match('/^#[0-9a-fA-F]{6}$/', $hex) === 1;
        $swatch = $valid ? $hex : '#000000';

        $html = '<span class="pp-color">'
            . '<input type="color" class="pp-color-swatch" value="' . self::e($swatch) . '" aria-label="Pick colour" tabindex="-1">'
            . '<input type="text" name="' . $name . '" id="field_' . $name . '" class="pp-color-hex form-control" value="' . self::e($hex) . '"'
            . ' placeholder="#000000" maxlength="7" autocomplete="off" spellcheck="false">'
            . '</span>';

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

    public static function settingsSchema(): array { return []; }

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

    private static function enhancer(): string
    {
        return <<<'HTML'
<script>
(function(){
  if (!window.__ppColorInit) {
    window.__ppColorInit = function(root){
      (root || document).querySelectorAll('.pp-color').forEach(function(box){
        if (box._ppColor) return; box._ppColor = true;
        var sw = box.querySelector('.pp-color-swatch');
        var hex = box.querySelector('.pp-color-hex');
        if (!sw || !hex) return;
        sw.addEventListener('input', function(){ hex.value = sw.value; hex.dispatchEvent(new Event('change', {bubbles:true})); });
        hex.addEventListener('input', function(){ if (/^#[0-9a-fA-F]{6}$/.test(hex.value)) sw.value = hex.value; });
      });
    };
  }
  if (document.readyState !== 'loading') window.__ppColorInit();
  else document.addEventListener('DOMContentLoaded', function(){ window.__ppColorInit(); });
})();
</script>
HTML;
    }
}
