<?php

declare(strict_types=1);

namespace PpPhp\Plugins;

use PpPhp\Core\PluginSupport;
use PpPhp\Core\ViewPlugin;

class Audio implements ViewPlugin
{
    use PluginSupport;

    public static function id(): string { return 'Audio'; }
    public static function label(): string { return 'Audio Player'; }
    public static function version(): string { return '1.1.0'; }
    public static function description(): string { return 'Plays an audio URL in a native player, with optional autoplay/loop/preload.'; }

    public static function render(mixed $value, array $settings): string
    {
        $src = self::safeUrl($value, true);
        if ($src === '') return '';
        $attrs = ' src="' . $src . '"';
        if (($settings['controls'] ?? 'yes') !== 'no') $attrs .= ' controls';
        if (self::on($settings['autoplay'] ?? null)) $attrs .= ' autoplay';
        if (self::on($settings['loop'] ?? null)) $attrs .= ' loop';
        if (self::on($settings['muted'] ?? null)) $attrs .= ' muted';
        $preload = (string) ($settings['preload'] ?? 'metadata');
        if (!in_array($preload, ['none', 'metadata', 'auto'], true)) $preload = 'metadata';
        $attrs .= ' preload="' . $preload . '"';
        return '<audio' . $attrs . '>Your browser cannot play this audio.</audio>';
    }

    private static function on(mixed $v): bool
    {
        return in_array(strtolower((string) ($v ?? '')), ['1', 'yes', 'true', 'on'], true);
    }

    public static function settingsSchema(): array
    {
        return [
            ['key' => 'controls', 'type' => 'bool', 'label' => 'Show controls', 'default' => 'yes'],
            ['key' => 'autoplay', 'type' => 'bool', 'label' => 'Autoplay', 'default' => 'no', 'hint' => 'Most browsers require muted to autoplay.'],
            ['key' => 'loop',     'type' => 'bool', 'label' => 'Loop', 'default' => 'no'],
            ['key' => 'muted',    'type' => 'bool', 'label' => 'Start muted', 'default' => 'no'],
            ['key' => 'preload',  'type' => 'select', 'label' => 'Preload', 'options' => ['none', 'metadata', 'auto'], 'default' => 'metadata'],
        ];
    }

    public static function assets(): array { return ['js' => [], 'css' => []]; }
}
