<?php

declare(strict_types=1);

namespace PpPhp\Plugins;

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

class Video implements ViewPlugin
{
    use PluginSupport;

    public static function id(): string { return 'Video'; }
    public static function label(): string { return 'Video Player'; }
    public static function version(): string { return '1.1.0'; }
    public static function description(): string { return 'Plays a video URL in a native player, with optional poster, width, autoplay/loop.'; }

    public static function render(mixed $value, array $settings): string
    {
        $src = self::safeUrl($value, true);
        if ($src === '') return '';
        $width = (int) ($settings['width'] ?? 320);
        if ($width < 0) $width = 0;
        $attrs = ' src="' . $src . '"';
        if ($width > 0) $attrs .= ' width="' . $width . '"';
        $poster = self::safeUrl($settings['poster'] ?? '', true);
        if ($poster !== '') $attrs .= ' poster="' . $poster . '"';
        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';
        $attrs .= ' preload="metadata" style="max-width:100%"';
        return '<video' . $attrs . '>Your browser cannot play this video.</video>';
    }

    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' => 'width',    'type' => 'number', 'label' => 'Width (px)', 'default' => 320, 'hint' => '0 = intrinsic; capped to 100% on mobile.'],
            ['key' => 'poster',   'type' => 'text',   'label' => 'Poster image URL', 'default' => ''],
            ['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'],
        ];
    }

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