<?php

namespace App\VideoPlugins;

use App\Models\VideoPlugin;
use App\VideoPlugins\Contracts\BaseVideoPlugin;

class YouTubeVideo extends BaseVideoPlugin
{
    public function getCode(): string
    {
        return 'youtube';
    }

    public function getName(): string
    {
        return 'YouTube Video';
    }

    public function getDescription(): string
    {
        return 'Embed YouTube videos and manage your YouTube channel link. Supports standard embeds with responsive iframe.';
    }

    public function getConfigFields(): array
    {
        return [
            [
                'key' => 'channel_url',
                'label' => 'Channel URL',
                'type' => 'text',
                'placeholder' => 'https://www.youtube.com/@channel',
            ],
            [
                'key' => 'api_key',
                'label' => 'YouTube API Key',
                'type' => 'password',
                'placeholder' => 'AIzaSy...',
            ],
            [
                'key' => 'default_width',
                'label' => 'Default Embed Width',
                'type' => 'text',
                'placeholder' => '560',
            ],
            [
                'key' => 'default_height',
                'label' => 'Default Embed Height',
                'type' => 'text',
                'placeholder' => '315',
            ],
        ];
    }

    public function validateConfig(array $config): array
    {
        return [
            'channel_url' => trim($config['channel_url'] ?? ''),
            'api_key' => trim($config['api_key'] ?? ''),
            'default_width' => trim($config['default_width'] ?? '560'),
            'default_height' => trim($config['default_height'] ?? '315'),
        ];
    }

    public function isConfigured(VideoPlugin $plugin): bool
    {
        $config = $plugin->config ?? [];
        return !empty($config['channel_url']);
    }

    public function renderEmbed(VideoPlugin $plugin, string $url = ''): string
    {
        $videoId = $this->extractVideoId($url ?: ($plugin->config['channel_url'] ?? ''));
        if (!$videoId) return '';

        $width = $plugin->config['default_width'] ?? '560';
        $height = $plugin->config['default_height'] ?? '315';

        return <<<HTML
<div style="position:relative;padding-bottom:56.25%;height:0;overflow:hidden;max-width:100%;background:#000">
    <iframe src="https://www.youtube.com/embed/{$videoId}" 
        style="position:absolute;top:0;left:0;width:100%;height:100%" 
        frameborder="0" allowfullscreen 
        allow="accelerometer;autoplay;clipboard-write;encrypted-media;gyroscope;picture-in-picture">
    </iframe>
</div>
HTML;
    }

    protected function extractVideoId(string $url): ?string
    {
        if (preg_match('/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/', $url, $m)) {
            return $m[1];
        }
        return null;
    }
}
