<?php
use function App\Core\e;

$videos = $videos ?? [];
?>
<div class="video-link-builder" data-video-builder>
    <div class="inline-input-row">
        <input type="url" placeholder="YouTube veya Vimeo linki" data-video-url>
        <button class="pill" type="button" data-add-video>Video Ekle</button>
    </div>
    <div class="field-error" data-error-for="videos"></div>
    <div class="video-preview-list" data-video-list>
        <?php foreach ($videos as $video): ?>
            <?php $url = (string) ($video['video_url'] ?? $video['src'] ?? $video); ?>
            <?php if ($url === '') continue; ?>
            <?php
            $thumb = '';
            $parts = parse_url($url);
            $host = strtolower((string) ($parts['host'] ?? ''));
            if (str_contains($host, 'youtu.be')) {
                $id = trim((string) ($parts['path'] ?? ''), '/');
                $thumb = $id !== '' ? 'https://img.youtube.com/vi/' . rawurlencode($id) . '/hqdefault.jpg' : '';
            } elseif (str_contains($host, 'youtube.com') && !empty($parts['query'])) {
                parse_str((string) $parts['query'], $query);
                $id = (string) ($query['v'] ?? '');
                $thumb = $id !== '' ? 'https://img.youtube.com/vi/' . rawurlencode($id) . '/hqdefault.jpg' : '';
            }
            ?>
            <div class="video-preview-item">
                <span data-video-thumb <?= $thumb !== '' ? 'style="background-image:url(' . e($thumb) . ')"' : '' ?>></span>
                <strong><?= e(parse_url($url, PHP_URL_HOST) ?: 'Video') ?></strong>
                <small><?= e($url) ?></small>
                <input type="hidden" name="videos[]" value="<?= e($url) ?>">
                <button type="button" data-remove-video>Sil</button>
            </div>
        <?php endforeach; ?>
    </div>
</div>
