<?php
$formAction = !empty($video) ? '/admin/videos/' . (int)$video['id'] . '/update' : '/admin/videos/store';
$isEdit = !empty($video);
$uploadLimit = class_exists('AdminVideoController') ? AdminVideoController::uploadLimitBytes() : 0;
$uploadLimitLabel = $uploadLimit > 0 ? AdminVideoController::formatBytes($uploadLimit) : '';

$catJson    = json_encode(array_map(fn($c) => ['id' => (int)$c['id'], 'n' => $c['name']], $categories ?? []), JSON_HEX_APOS);
$tagJson    = json_encode(array_map(fn($t) => ['id' => (int)$t['id'], 'n' => $t['name']], $tags ?? []), JSON_HEX_APOS);
$perfJson   = json_encode(array_map(fn($p) => ['id' => (int)$p['id'], 'n' => $p['name']], $performers ?? []), JSON_HEX_APOS);
$channelJson = json_encode(array_map(fn($s) => ['id' => (int)$s['id'], 'n' => $s['name']], $channels ?? []), JSON_HEX_APOS);

$selCats    = json_encode(array_map('intval', $selectedCategories ?? []));
$selTags    = json_encode(array_map('intval', $selectedTags ?? []));
$selPerfs   = json_encode(array_map('intval', $selectedPerformers ?? []));
$selChannels = json_encode(array_map('intval', $selectedChannels ?? []));

$dur = (int)($video['duration'] ?? 0);
$durMin = intdiv($dur, 60);
$durSec = $dur % 60;
$durFmt = sprintf('%02d:%02d', $durMin, $durSec);
$curStatus = $video['status'] ?? 'draft';
$vtype = $video['video_type'] ?? 'hetero';

if ($isEdit) {
    $thumbSrc      = VideoAsset::thumbUrl($video);
    $thumbSmallSrc = VideoAsset::thumbUrl($video, true);
    $previewSrc    = VideoAsset::previewUrl($video);
} else {
    $thumbSrc = $thumbSmallSrc = $previewSrc = '';
}

$hasEmbed = !empty($video['embed_code']);
$hasFile  = !empty($video['video_folder']);
$defaultSrc = $hasFile ? 'upload' : 'embed';

$inputCls = 'w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none';
?>

<?php require __DIR__ . '/_tok_picker.php'; ?>

<style>
.thumb-zone{border:2px dashed #d1d5db;border-radius:8px;padding:20px;text-align:center;cursor:pointer;transition:border-color .15s,background .15s;position:relative}
.thumb-zone:hover{border-color:#3b82f6;background:#eff6ff}
.thumb-zone.has-preview{border-style:solid;padding:0;overflow:hidden}
.thumb-zone.has-preview img{width:100%;display:block;border-radius:6px}
.thumb-zone input[type=file]{position:absolute;inset:0;opacity:0;cursor:pointer}
.vf-tab-panel{display:none}.vf-tab-panel.active{display:block}
</style>

<form method="POST" action="<?= htmlspecialchars($formAction) ?>" enctype="multipart/form-data" id="videoForm">
    <?= Router::csrfField() ?>

    
    <div class="border-b border-gray-200 mb-6">
        <nav class="flex gap-0 -mb-px" id="vfTabNav">
            <button type="button" class="vf-tab-btn px-5 py-3 text-sm font-medium border-b-2 transition-colors border-blue-600 text-blue-600" data-tab="content">
                <span class="flex items-center gap-1.5">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
                    Content
                </span>
            </button>
            <button type="button" class="vf-tab-btn px-5 py-3 text-sm font-medium border-b-2 transition-colors border-transparent text-gray-500 hover:text-gray-700" data-tab="media">
                <span class="flex items-center gap-1.5">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><rect x="2" y="2" width="20" height="20" rx="2.18" ry="2.18"/><polygon points="10 8 16 12 10 16 10 8"/></svg>
                    Media
                </span>
            </button>
            <button type="button" class="vf-tab-btn px-5 py-3 text-sm font-medium border-b-2 transition-colors border-transparent text-gray-500 hover:text-gray-700" data-tab="relations">
                <span class="flex items-center gap-1.5">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>
                    Relations
                </span>
            </button>
        </nav>
    </div>

    
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

        
        <div class="lg:col-span-2">

            
            <div class="vf-tab-panel active" id="tabContent">
                <div class="bg-white rounded-lg shadow-sm border border-gray-200">
                    <div class="px-4 py-3 border-b border-gray-100 flex items-center justify-between">
                        <h3 class="text-sm font-semibold text-gray-700 flex items-center gap-2">
                            <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
                            Information
                        </h3>
                        <div class="flex items-center gap-1">
                            <?php if ($isEdit && count($videoLanguages ?? []) > 1): ?>
                            <button type="button" onclick="vtlOpen()" class="inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium text-indigo-600 hover:bg-indigo-50 transition-colors" title="Manage translations">
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
                                Translations
                            </button>
                            <?php endif; ?>
                            <?php if ($isEdit && !empty($video['slug'])): ?>
                            <a href="/video/<?= htmlspecialchars($video['slug']) ?>" target="_blank" class="inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium text-blue-600 hover:bg-blue-50 transition-colors" title="View on site">
                                <svg width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>
                                View
                            </a>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="p-4 space-y-4">
                        <div>
                            <label for="title" class="block text-sm font-medium text-gray-700 mb-1">Title <span class="text-red-500">*</span></label>
                            <input type="text" id="title" name="title" value="<?= htmlspecialchars($video['title'] ?? '') ?>" required
                                   class="<?= $inputCls ?>" placeholder="Enter video title...">
                            <?php if ($isEdit && !empty($video['original_title']) && $video['original_title'] !== $video['title']): ?>
                            <p class="mt-1 text-xs text-gray-400 italic">Original: <?= htmlspecialchars($video['original_title']) ?></p>
                            <?php endif; ?>
                        </div>
                        <div>
                            <label for="slug" class="block text-sm font-medium text-gray-700 mb-1">Slug</label>
                            <div class="flex items-center gap-0">
                                <span class="px-3 py-2 bg-gray-50 border border-r-0 border-gray-300 rounded-l-lg text-xs text-gray-400 whitespace-nowrap">/video/</span>
                                <input type="text" id="slug" name="slug" value="<?= htmlspecialchars($video['slug'] ?? '') ?>"
                                       class="flex-1 px-3 py-2 border border-gray-300 rounded-r-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none"
                                       placeholder="auto-generated-from-title">
                            </div>
                            <p class="mt-1 text-xs text-gray-500">Leave empty to auto-generate from title.</p>
                        </div>
                        <div>
                            <label for="description" class="block text-sm font-medium text-gray-700 mb-1">Description</label>
                            <textarea id="description" name="description" rows="4"
                                      class="<?= $inputCls ?> min-h-[120px] resize-y"
                                      placeholder="Describe this video..."><?= htmlspecialchars($video['description'] ?? '') ?></textarea>
                            <?php if ($isEdit && !empty($video['original_description']) && $video['original_description'] !== $video['description']): ?>
                            <p class="mt-1 text-xs text-gray-400 italic">Original: <?= htmlspecialchars(mb_strimwidth($video['original_description'], 0, 200, '...')) ?></p>
                            <?php endif; ?>
                        </div>
                        <?php if ($isEdit): ?>
                        <div class="pt-3 border-t border-gray-100 flex flex-wrap gap-x-5 gap-y-1.5 text-xs text-gray-400">
                            <?php if (!empty($video['published_at'])): ?>
                            <span>Published <strong class="text-gray-500"><?= date('M j, Y H:i', strtotime($video['published_at'])) ?></strong></span>
                            <?php endif; ?>
                            <span>Created <strong class="text-gray-500"><?= date('M j, Y H:i', strtotime($video['created_at'])) ?></strong></span>
                            <span>Updated <strong class="text-gray-500"><?= date('M j, Y H:i', strtotime($video['updated_at'])) ?></strong></span>
                            <?php if (!empty($video['external_id'])): ?>
                            <span>Ext ID <strong class="text-gray-500 font-mono"><?= htmlspecialchars($video['external_id']) ?></strong></span>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            
            <div class="vf-tab-panel" id="tabMedia">
                <div class="space-y-6">
                    
                    <div class="bg-white rounded-lg shadow-sm border border-gray-200">
                        <div class="px-4 py-3 border-b border-gray-100 flex items-center justify-between">
                            <h3 class="text-sm font-semibold text-gray-700 flex items-center gap-2">
                                <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><rect x="2" y="2" width="20" height="20" rx="2.18" ry="2.18"/><polygon points="10 8 16 12 10 16 10 8"/></svg>
                                Video Source
                            </h3>
                            <div class="flex rounded-lg border border-gray-200 overflow-hidden" id="sourceToggle">
                                <button type="button" data-source="embed" class="px-3 py-1.5 text-xs font-medium transition-colors <?= $defaultSrc === 'embed' ? 'bg-blue-600 text-white' : 'bg-white text-gray-600 hover:bg-gray-50' ?>">Embed Code</button>
                                <button type="button" data-source="upload" class="px-3 py-1.5 text-xs font-medium transition-colors border-l border-gray-200 <?= $defaultSrc === 'upload' ? 'bg-blue-600 text-white' : 'bg-white text-gray-600 hover:bg-gray-50' ?>">Upload File</button>
                            </div>
                        </div>
                        <div class="p-4">
                            <div id="sourceEmbed" class="<?= $defaultSrc !== 'embed' ? 'hidden' : '' ?>">
                                <label for="embed_code" class="block text-sm font-medium text-gray-700 mb-1">Embed Code</label>
                                <textarea id="embed_code" name="embed_code" rows="3"
                                          class="<?= $inputCls ?> font-mono resize-y"
                                          placeholder="<iframe src=&quot;...&quot;></iframe>"><?= htmlspecialchars($video['embed_code'] ?? '') ?></textarea>
                                <p class="mt-1 text-xs text-gray-500">Paste an iframe embed code or a direct video URL.</p>
                            </div>
                            <div id="sourceUpload" class="<?= $defaultSrc !== 'upload' ? 'hidden' : '' ?>">
                                <label for="video_file" class="block text-sm font-medium text-gray-700 mb-1">Upload Video File</label>
                                <?php if ($hasFile): ?>
                                <div class="mb-2 flex items-center gap-2 px-3 py-2 bg-gray-50 rounded-lg text-xs text-gray-600">
                                    <svg class="w-4 h-4 text-green-500" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
                                    Video uploaded — <code class="text-gray-500"><?= htmlspecialchars($video['video_folder']) ?></code>
                                </div>
                                <?php endif; ?>
                                <input type="file" id="video_file" name="video_file" accept="video/*"
                                       class="w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-medium file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100">
                                    <?php if ($uploadLimitLabel !== ''): ?>
                                    <p class="mt-1 text-[11px] text-gray-400">Maximum accepted by this server: <?= htmlspecialchars($uploadLimitLabel) ?></p>
                                    <?php endif; ?>
                                    <?php if (!$isEdit): ?>
                                    <p class="mt-1 text-[11px] text-gray-400">Several files to upload? <a href="/admin/videos/bulk-upload" class="text-blue-600 hover:underline">Upload them in bulk</a>.</p>
                                    <?php endif; ?>

                                    <div id="vupPanel" class="hidden mt-3 rounded-lg border border-gray-200 bg-white p-3" data-limit="<?= (int)$uploadLimit ?>">
                                        <div class="flex items-start justify-between gap-3">
                                            <div class="flex items-center gap-2 min-w-0">
                                                <span class="relative flex h-2.5 w-2.5 shrink-0">
                                                    <span id="vupPing" class="absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75 animate-ping"></span>
                                                    <span id="vupCore" class="relative inline-flex h-2.5 w-2.5 rounded-full bg-blue-600"></span>
                                                </span>
                                                <span id="vupPhase" class="text-sm font-medium text-gray-800">Uploading</span>
                                                <span id="vupFile" class="text-xs text-gray-500 truncate"></span>
                                            </div>
                                            <span id="vupPct" class="shrink-0 text-sm font-semibold text-gray-900 tabular-nums">0%</span>
                                        </div>
                                        <div id="vupTrack" class="mt-2 h-2 w-full overflow-hidden rounded-full bg-gray-200" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" aria-labelledby="vupPhase">
                                            <div id="vupBar" class="h-full w-0 rounded-full bg-blue-600 transition-all duration-200 ease-out"></div>
                                        </div>
                                        <div class="mt-2 flex items-center justify-between gap-3">
                                            <p id="vupStats" class="text-xs text-gray-500 tabular-nums" aria-live="polite">Preparing…</p>
                                            <button type="button" id="vupCancel" class="shrink-0 text-xs font-medium text-gray-500 transition-colors hover:text-red-600">Cancel</button>
                                        </div>
                                        <ol id="vupSteps" class="mt-2 flex items-center gap-1.5 text-[11px] text-gray-400">
                                            <li data-step="upload">Uploading</li>
                                            <li aria-hidden="true">→</li>
                                            <li data-step="process">Processing</li>
                                            <li aria-hidden="true">→</li>
                                            <li data-step="done">Completed</li>
                                        </ol>
                                        <p id="vupError" class="hidden mt-2 text-xs text-red-600"></p>
                                    </div>
                            </div>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        
                        <div class="bg-white rounded-lg shadow-sm border border-gray-200">
                            <div class="px-4 py-3 border-b border-gray-100 flex items-center justify-between">
                                <h3 class="text-sm font-semibold text-gray-700 flex items-center gap-2">
                                    <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                                    Thumbnail
                                </h3>
                                <?php if ($isEdit && $thumbSrc && $thumbSmallSrc && $thumbSrc !== $thumbSmallSrc): ?>
                                <div class="flex rounded-lg border border-gray-200 overflow-hidden" id="thumbSizeToggle">
                                    <button type="button" data-size="large" class="px-2.5 py-1 text-[11px] font-medium transition-colors bg-blue-600 text-white">Full</button>
                                    <button type="button" data-size="small" class="px-2.5 py-1 text-[11px] font-medium transition-colors border-l border-gray-200 bg-white text-gray-600 hover:bg-gray-50">Small</button>
                                </div>
                                <?php endif; ?>
                            </div>
                            <div class="p-4">
                                <?php $thumbSrcForm = $isEdit ? $thumbSrc : ''; ?>
                                <div class="thumb-zone<?php if ($thumbSrcForm !== ''): ?> has-preview<?php endif; ?>" id="thumbZone">
                                    <?php if ($thumbSrcForm !== ''): ?>
                                        <img src="<?= htmlspecialchars($thumbSrcForm) ?>" alt="" id="thumbPreview"
                                             data-large="<?= htmlspecialchars($thumbSrc) ?>"
                                             data-small="<?= htmlspecialchars($thumbSmallSrc) ?>">
                                    <?php else: ?>
                                        <div id="thumbPlaceholder">
                                            <svg class="w-8 h-8 mx-auto text-gray-300 mb-2" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                                            <p class="text-sm text-gray-400 mb-1">Click to upload</p>
                                            <p class="text-xs text-gray-300">JPG, PNG, WebP</p>
                                        </div>
                                        <img src="" alt="" id="thumbPreview" class="hidden">
                                    <?php endif; ?>
                                    <input type="file" id="thumbnail" name="thumbnail" accept="image/*">
                                </div>
                                <?php if ($isEdit && $thumbSrc && $thumbSmallSrc && $thumbSrc !== $thumbSmallSrc): ?>
                                <p class="mt-2 text-[10px] text-gray-400 text-center" id="thumbSizeLabel">Full size &mdash; 1280&times;720</p>
                                <?php endif; ?>
                            </div>
                        </div>

                        
                        <?php if ($isEdit && $previewSrc): ?>
                        <div class="bg-white rounded-lg shadow-sm border border-gray-200">
                            <div class="px-4 py-3 border-b border-gray-100">
                                <h3 class="text-sm font-semibold text-gray-700 flex items-center gap-2">
                                    <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><polygon points="5 3 19 12 5 21 5 3"/></svg>
                                    Preview Clip
                                </h3>
                            </div>
                            <div class="p-4">
                                <video class="w-full rounded-lg" style="background:#0f172a" controls loop muted>
                                    <source src="<?= htmlspecialchars($previewSrc) ?>" type="video/mp4">
                                </video>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            
            <div class="vf-tab-panel" id="tabRelations">
                <div class="bg-white rounded-lg shadow-sm border border-gray-200">
                    <div class="px-4 py-3 border-b border-gray-100">
                        <h3 class="text-sm font-semibold text-gray-700 flex items-center gap-2">
                            <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>
                            Relations
                        </h3>
                    </div>
                    <div class="p-4">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Categories</label>
                                <div class="tok" id="tokCategories" data-name="categories[]" data-items='<?= $catJson ?>' data-selected='<?= $selCats ?>'>
                                    <div class="tok__wrap"><div class="tok__tags"></div><input type="text" class="tok__input" placeholder="Search categories..."></div>
                                    <div class="tok__drop"></div>
                                </div>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Tags</label>
                                <div class="tok" id="tokTags" data-name="tags[]" data-items='<?= $tagJson ?>' data-selected='<?= $selTags ?>'>
                                    <div class="tok__wrap"><div class="tok__tags"></div><input type="text" class="tok__input" placeholder="Search tags..."></div>
                                    <div class="tok__drop"></div>
                                </div>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Pornstars</label>
                                <div class="tok" id="tokPerformers" data-name="performers[]" data-items='<?= $perfJson ?>' data-selected='<?= $selPerfs ?>'>
                                    <div class="tok__wrap"><div class="tok__tags"></div><input type="text" class="tok__input" placeholder="Search pornstars..."></div>
                                    <div class="tok__drop"></div>
                                </div>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Channels</label>
                                <div class="tok" id="tokChannels" data-name="channels[]" data-items='<?= $channelJson ?>' data-selected='<?= $selChannels ?>'>
                                    <div class="tok__wrap"><div class="tok__tags"></div><input type="text" class="tok__input" placeholder="Search channels..."></div>
                                    <div class="tok__drop"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        
        <div class="space-y-6">

            
            <div class="bg-white rounded-lg shadow-sm border border-gray-200">
                <div class="px-4 py-3 border-b border-gray-100">
                    <h3 class="text-sm font-semibold text-gray-700 flex items-center gap-2">
                        <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>
                        Publishing
                    </h3>
                </div>
                <div class="p-4 space-y-4">
                    <div>
                        <label for="status" class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                        <select id="status" name="status" class="<?= $inputCls ?>">
                            <option value="draft" <?= $curStatus === 'draft' ? 'selected' : '' ?>>Draft</option>
                            <option value="published" <?= $curStatus === 'published' ? 'selected' : '' ?>>Published</option>
                            <option value="private" <?= $curStatus === 'private' ? 'selected' : '' ?>>Private</option>
                        </select>
                    </div>
                    <div>
                        <label for="video_type" class="block text-sm font-medium text-gray-700 mb-1">Type</label>
                        <select id="video_type" name="video_type" class="<?= $inputCls ?>">
                            <?php foreach (Video::typeLabels() as $vtCode => $vtLabel): ?>
                            <option value="<?= $vtCode ?>" <?= $vtype === $vtCode ? 'selected' : '' ?>><?= htmlspecialchars($vtLabel) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Duration</label>
                        <div class="flex items-center gap-1.5">
                            <div class="relative flex-1">
                                <input type="number" id="dur_min" min="0" max="999" value="<?= $durMin ?>"
                                       class="<?= $inputCls ?> font-mono text-center pr-8" style="appearance:textfield;-moz-appearance:textfield">
                                <span class="absolute right-2.5 top-1/2 -translate-y-1/2 text-[10px] font-medium text-gray-400 pointer-events-none">min</span>
                            </div>
                            <span class="text-gray-400 font-mono font-bold text-lg select-none">:</span>
                            <div class="relative flex-1">
                                <input type="number" id="dur_sec" min="0" max="59" value="<?= $durSec ?>"
                                       class="<?= $inputCls ?> font-mono text-center pr-8" style="appearance:textfield;-moz-appearance:textfield">
                                <span class="absolute right-2.5 top-1/2 -translate-y-1/2 text-[10px] font-medium text-gray-400 pointer-events-none">sec</span>
                            </div>
                        </div>
                        <input type="hidden" id="duration" name="duration" value="<?= $dur ?>">
                    </div>
                    <?php if ($isEdit && !empty($video['video_folder'])): ?>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Folder</label>
                        <div class="px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg text-xs font-mono text-gray-500 truncate" title="<?= htmlspecialchars($video['video_folder']) ?>">
                            <?= htmlspecialchars($video['video_folder']) ?>
                        </div>
                    </div>
                    <?php
                    $storageName = 'Local';
                    if (!empty($video['storage_id'])) {
                        $storageInfo = Database::fetchOne('SELECT name, driver FROM media_storages WHERE id = ?', [(int)$video['storage_id']]);
                        if ($storageInfo) $storageName = $storageInfo['name'];
                    }
                    ?>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Storage</label>
                        <div class="px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg text-xs text-gray-500 truncate">
                            <?= htmlspecialchars($storageName) ?>
                        </div>
                    </div>
                    <?php endif; ?>
                    <div class="pt-3 border-t border-gray-100 space-y-2">
                        <button type="submit" class="w-full inline-flex items-center justify-center gap-2 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
                            <?= $isEdit ? 'Save Changes' : 'Create Video' ?>
                        </button>
                        <a href="/admin/videos" class="w-full inline-flex items-center justify-center px-4 py-2 bg-white text-gray-700 text-sm font-medium rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors">Cancel</a>
                    </div>
                </div>
            </div>

            
            <div class="bg-white rounded-lg shadow-sm border border-gray-200">
                <div class="px-4 py-3 border-b border-gray-100">
                    <h3 class="text-sm font-semibold text-gray-700 flex items-center gap-2">
                        <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                        Engagement
                    </h3>
                </div>
                <div class="p-4 space-y-3">
                    <div>
                        <label for="views" class="block text-sm font-medium text-gray-700 mb-1">Views</label>
                        <input type="number" id="views" name="views" value="<?= (int)($video['views'] ?? 0) ?>" min="0"
                               class="<?= $inputCls ?> font-mono">
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label for="likes" class="block text-sm font-medium text-gray-700 mb-1">Likes</label>
                            <input type="number" id="likes" name="likes" value="<?= (int)($video['likes'] ?? 0) ?>" min="0"
                                   class="<?= $inputCls ?> font-mono">
                        </div>
                        <div>
                            <label for="dislikes" class="block text-sm font-medium text-gray-700 mb-1">Dislikes</label>
                            <input type="number" id="dislikes" name="dislikes" value="<?= (int)($video['dislikes'] ?? 0) ?>" min="0"
                                   class="<?= $inputCls ?> font-mono">
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
</form>

<?php if ($isEdit && count($videoLanguages ?? []) > 1):
    $_vtlLangs = [];
    $_vtlDefault = $defaultLang ?? 'en';
    foreach ($videoLanguages as $vl) {
        if ($vl['code'] === $_vtlDefault) continue;
        $_vtlLangs[] = [
            'code' => $vl['code'],
            'name' => $vl['name'],
            'flag' => Translator::flagCode($vl['code']),
            'title' => $videoTranslations[$vl['code']]['title'] ?? '',
            'description' => $videoTranslations[$vl['code']]['description'] ?? '',
        ];
    }
?>
<style>
.vtl-overlay{display:none;position:fixed;inset:0;z-index:10000;background:rgba(0,0,0,.5);backdrop-filter:blur(2px);align-items:center;justify-content:center}
.vtl-overlay.open{display:flex}
.vtl-modal{background:#fff;border-radius:14px;width:560px;max-width:95vw;max-height:85vh;display:flex;flex-direction:column;box-shadow:0 20px 60px rgba(0,0,0,.2);animation:vtlIn .2s ease}
@keyframes vtlIn{from{opacity:0;transform:scale(.96) translateY(8px)}to{opacity:1;transform:none}}
.vtl-modal__header{display:flex;align-items:center;justify-content:space-between;padding:14px 18px;border-bottom:1px solid #e5e7eb;flex-shrink:0}
.vtl-modal__title{display:flex;align-items:center;gap:8px;font-size:14px;font-weight:600;color:#111827}
.vtl-modal__close{width:28px;height:28px;display:flex;align-items:center;justify-content:center;border:none;background:#f3f4f6;border-radius:7px;cursor:pointer;color:#6b7280}
.vtl-modal__close:hover{background:#e5e7eb;color:#111}
.vtl-modal__body{padding:12px 18px;overflow-y:auto;flex:1}
.vtl-lang{padding:12px 0;border-bottom:1px solid #f3f4f6}
.vtl-lang:last-child{border-bottom:none}
.vtl-lang__head{display:flex;align-items:center;gap:8px;margin-bottom:8px}
.vtl-lang__flag{width:18px;height:13px;border-radius:2px;object-fit:cover}
.vtl-lang__name{font-size:13px;font-weight:600;color:#374151}
.vtl-lang__input{width:100%;padding:7px 10px;border:1px solid #d1d5db;border-radius:7px;font-size:13px;outline:none;transition:border-color .12s;box-sizing:border-box;margin-bottom:6px}
.vtl-lang__input:focus{border-color:#6366f1;box-shadow:0 0 0 3px rgba(99,102,241,.08)}
.vtl-lang__lbl{font-size:11px;color:#9ca3af;margin-bottom:3px}
.vtl-modal__footer{display:flex;justify-content:flex-end;gap:8px;padding:12px 18px;border-top:1px solid #e5e7eb;flex-shrink:0}
.vtl-btn{padding:7px 18px;border-radius:7px;font-size:13px;font-weight:600;cursor:pointer;border:none;transition:background .12s}
.vtl-btn--save{background:#4f46e5;color:#fff}
.vtl-btn--save:hover{background:#4338ca}
.vtl-btn--cancel{background:#f3f4f6;color:#374151}
.vtl-btn--cancel:hover{background:#e5e7eb}
.vtl-saving{opacity:.6;pointer-events:none}
</style>
<div class="vtl-overlay" id="vtlOverlay">
    <div class="vtl-modal">
        <div class="vtl-modal__header">
            <div class="vtl-modal__title">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0;color:#6366f1"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
                <span>Video Translations</span>
            </div>
            <button type="button" class="vtl-modal__close" onclick="vtlClose()">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 6L6 18M6 6l12 12"/></svg>
            </button>
        </div>
        <div class="vtl-modal__body" id="vtlBody">
            <?php foreach ($_vtlLangs as $vl): ?>
            <div class="vtl-lang">
                <div class="vtl-lang__head">
                    <img src="https://flagcdn.com/w40/<?= htmlspecialchars($vl['flag']) ?>.png" class="vtl-lang__flag" alt="">
                    <span class="vtl-lang__name"><?= htmlspecialchars($vl['name']) ?></span>
                </div>
                <div class="vtl-lang__lbl">Title</div>
                <input type="text" class="vtl-lang__input" data-lang="<?= htmlspecialchars($vl['code']) ?>" data-field="title" value="<?= htmlspecialchars($vl['title']) ?>" placeholder="Translated title...">
                <div class="vtl-lang__lbl">Description</div>
                <textarea class="vtl-lang__input" style="min-height:60px;resize:vertical" data-lang="<?= htmlspecialchars($vl['code']) ?>" data-field="description" placeholder="Translated description..."><?= htmlspecialchars($vl['description']) ?></textarea>
            </div>
            <?php endforeach; ?>
        </div>
        <div class="vtl-modal__footer">
            <button type="button" class="vtl-btn vtl-btn--cancel" onclick="vtlClose()">Cancel</button>
            <button type="button" class="vtl-btn vtl-btn--save" id="vtlSaveBtn" onclick="vtlSave()">Save Translations</button>
        </div>
    </div>
</div>
<script>
function vtlOpen(){document.getElementById('vtlOverlay').classList.add('open');}
function vtlClose(){document.getElementById('vtlOverlay').classList.remove('open');}
document.getElementById('vtlOverlay').addEventListener('click',function(e){if(e.target===this)vtlClose();});
function vtlSave(){
    var btn=document.getElementById('vtlSaveBtn');
    var modal=document.querySelector('.vtl-modal');
    modal.classList.add('vtl-saving');
    btn.textContent='Saving...';
    var data={};
    document.querySelectorAll('#vtlBody [data-lang]').forEach(function(el){
        var lang=el.dataset.lang, field=el.dataset.field;
        if(!data[lang])data[lang]={};
        data[lang][field]=el.value;
    });
    fetch('/admin/videos/<?= (int)$video['id'] ?>/translations',{
        method:'POST',
        headers:{'Content-Type':'application/json','X-CSRF-Token':document.querySelector('[name=csrf_token]').value},
        body:JSON.stringify({translations:data})
    }).then(function(r){return r.json();}).then(function(r){
        modal.classList.remove('vtl-saving');
        btn.textContent='Save Translations';
        if(r.success){vtlClose();}
    }).catch(function(){
        modal.classList.remove('vtl-saving');
        btn.textContent='Save Translations';
        alert('Failed to save translations');
    });
}
</script>
<?php endif; ?>

<script>

(function(){
    var nav=document.getElementById('vfTabNav');
    var panels=document.querySelectorAll('.vf-tab-panel');
    nav.addEventListener('click',function(e){
        var btn=e.target.closest('.vf-tab-btn');
        if(!btn)return;
        var tab=btn.dataset.tab;
        
        nav.querySelectorAll('.vf-tab-btn').forEach(function(b){
            if(b.dataset.tab===tab){
                b.className=b.className.replace('border-transparent text-gray-500 hover:text-gray-700','border-blue-600 text-blue-600');
            }else{
                b.className=b.className.replace('border-blue-600 text-blue-600','border-transparent text-gray-500 hover:text-gray-700');
            }
        });
        
        panels.forEach(function(p){
            p.classList.toggle('active',p.id==='tab'+tab.charAt(0).toUpperCase()+tab.slice(1));
        });
    });
})();


(function(){
    var toggle=document.getElementById('sourceToggle');
    if(!toggle)return;
    var embedPanel=document.getElementById('sourceEmbed');
    var uploadPanel=document.getElementById('sourceUpload');
    var embedTa=document.getElementById('embed_code');
    var fileIn=document.getElementById('video_file');
    toggle.querySelectorAll('button').forEach(function(btn){
        btn.addEventListener('click',function(){
            var src=btn.dataset.source;
            toggle.querySelectorAll('button').forEach(function(b){
                b.className=b.className.replace(/bg-blue-600 text-white|bg-white text-gray-600 hover:bg-gray-50/g,'');
                b.classList.add(...(b.dataset.source===src?['bg-blue-600','text-white']:['bg-white','text-gray-600','hover:bg-gray-50']));
            });
            if(src==='embed'){
                embedPanel.classList.remove('hidden');
                uploadPanel.classList.add('hidden');
                fileIn.value='';
            }else{
                uploadPanel.classList.remove('hidden');
                embedPanel.classList.add('hidden');
                embedTa.value='';
            }
        });
    });
})();


(function(){
    var mn=document.getElementById('dur_min'),sc=document.getElementById('dur_sec'),hid=document.getElementById('duration');
    function sync(){
        var m=parseInt(mn.value)||0, s=Math.min(59,Math.max(0,parseInt(sc.value)||0));
        hid.value=m*60+s;
    }
    mn.addEventListener('input',sync);
    sc.addEventListener('input',sync);
    sc.addEventListener('blur',function(){
        var v=parseInt(sc.value)||0;
        if(v>59) sc.value=59;
        if(v<0) sc.value=0;
        sync();
    });
})();


(function(){
    var inp=document.getElementById('thumbnail'),zone=document.getElementById('thumbZone'),
        prev=document.getElementById('thumbPreview'),ph=document.getElementById('thumbPlaceholder');
    inp.addEventListener('change',function(){
        if(inp.files&&inp.files[0]){
            var r=new FileReader();
            r.onload=function(e){
                prev.src=e.target.result;
                prev.classList.remove('hidden');
                if(ph)ph.style.display='none';
                zone.classList.add('has-preview');
            };
            r.readAsDataURL(inp.files[0]);
        }
    });
})();


(function(){
    var toggle=document.getElementById('thumbSizeToggle');
    if(!toggle)return;
    var prev=document.getElementById('thumbPreview');
    var label=document.getElementById('thumbSizeLabel');
    toggle.querySelectorAll('button').forEach(function(btn){
        btn.addEventListener('click',function(){
            var size=btn.dataset.size;
            toggle.querySelectorAll('button').forEach(function(b){
                b.className=b.className.replace(/bg-blue-600 text-white|bg-white text-gray-600 hover:bg-gray-50/g,'');
                b.classList.add(...(b.dataset.size===size?['bg-blue-600','text-white']:['bg-white','text-gray-600','hover:bg-gray-50']));
            });
            if(prev&&prev.dataset[size]){
                prev.src=prev.dataset[size];
            }
            if(label){
                label.textContent=size==='large'?'Full size \u2014 1280\u00d7720':'Small size \u2014 320\u00d7180';
            }
        });
    });
})();
</script>

<script>
(function () {
    var form = document.getElementById('videoForm');
    var panel = document.getElementById('vupPanel');
    if (!form || !panel || !window.FormData || !window.XMLHttpRequest) {
        return;
    }

    var videoInput = document.getElementById('video_file');
    var thumbInput = document.getElementById('thumbnail');
    var bar = document.getElementById('vupBar');
    var track = document.getElementById('vupTrack');
    var pctLabel = document.getElementById('vupPct');
    var phaseLabel = document.getElementById('vupPhase');
    var fileLabel = document.getElementById('vupFile');
    var statsLabel = document.getElementById('vupStats');
    var errorBox = document.getElementById('vupError');
    var cancelBtn = document.getElementById('vupCancel');
    var ping = document.getElementById('vupPing');
    var core = document.getElementById('vupCore');
    var steps = document.getElementById('vupSteps');
    var submitBtn = form.querySelector('button[type="submit"]');
    var submitHtml = submitBtn ? submitBtn.innerHTML : '';

    var request = null;
    var uploading = false;
    var lastTime = 0;
    var lastLoaded = 0;
    var speed = 0;

    function formatBytes(value) {
        var units = ['B', 'KB', 'MB', 'GB', 'TB'];
        var v = value;
        var i = 0;
        while (v >= 1024 && i < units.length - 1) {
            v = v / 1024;
            i++;
        }
        return (i === 0 || v >= 10 ? Math.round(v) : Math.round(v * 10) / 10) + ' ' + units[i];
    }

    function formatDuration(seconds) {
        if (!isFinite(seconds) || seconds < 0) {
            return 'calculating';
        }
        var s = Math.round(seconds);
        if (s < 60) {
            return s + ' sec';
        }
        var m = Math.floor(s / 60);
        if (m < 60) {
            var rest = s % 60;
            return m + ' min' + (rest > 0 ? ' ' + rest + ' sec' : '');
        }
        var h = Math.floor(m / 60);
        return h + ' h ' + (m % 60) + ' min';
    }

    function selectedFiles() {
        var files = [];
        [videoInput, thumbInput].forEach(function (input) {
            if (input && input.files && input.files.length > 0) {
                files.push(input.files[0]);
            }
        });
        return files;
    }

    function markStep(active) {
        if (!steps) {
            return;
        }
        var order = ['upload', 'process', 'done'];
        var reached = order.indexOf(active);
        order.forEach(function (name, index) {
            var node = steps.querySelector('[data-step="' + name + '"]');
            if (!node) {
                return;
            }
            node.classList.remove('text-blue-600', 'text-gray-700', 'text-gray-400', 'font-medium');
            if (index < reached) {
                node.classList.add('text-gray-700');
            } else if (index === reached) {
                node.classList.add('text-blue-600', 'font-medium');
            } else {
                node.classList.add('text-gray-400');
            }
        });
    }

    function setDot(tone) {
        if (!ping || !core) {
            return;
        }
        core.classList.remove('bg-blue-600', 'bg-green-600', 'bg-red-600');
        if (tone === 'ok') {
            core.classList.add('bg-green-600');
            ping.classList.add('hidden');
        } else if (tone === 'error') {
            core.classList.add('bg-red-600');
            ping.classList.add('hidden');
        } else {
            core.classList.add('bg-blue-600');
            ping.classList.remove('hidden');
        }
    }

    function setBar(percent, tone) {
        var value = Math.max(0, Math.min(100, percent));
        bar.style.width = value + '%';
        pctLabel.textContent = Math.round(value) + '%';
        track.setAttribute('aria-valuenow', String(Math.round(value)));
        bar.classList.remove('bg-blue-600', 'bg-green-600', 'bg-red-600');
        if (tone === 'ok') {
            bar.classList.add('bg-green-600');
        } else if (tone === 'error') {
            bar.classList.add('bg-red-600');
        } else {
            bar.classList.add('bg-blue-600');
        }
    }

    function lockForm(locked) {
        if (!submitBtn) {
            return;
        }
        submitBtn.disabled = locked;
        if (locked) {
            submitBtn.classList.add('opacity-60', 'cursor-not-allowed');
            submitBtn.textContent = 'Uploading…';
        } else {
            submitBtn.classList.remove('opacity-60', 'cursor-not-allowed');
            submitBtn.innerHTML = submitHtml;
        }
    }

    function guard(event) {
        event.preventDefault();
        event.returnValue = '';
        return '';
    }

    function setUploading(state) {
        uploading = state;
        if (state) {
            window.addEventListener('beforeunload', guard);
        } else {
            window.removeEventListener('beforeunload', guard);
        }
    }

    function fail(message) {
        setUploading(false);
        lockForm(false);
        setBar(0, 'error');
        setDot('error');
        markStep('upload');
        phaseLabel.textContent = 'Upload failed';
        statsLabel.textContent = '';
        cancelBtn.textContent = 'Dismiss';
        errorBox.textContent = message;
        errorBox.classList.remove('hidden');
    }

    cancelBtn.addEventListener('click', function () {
        if (uploading && request) {
            request.abort();
            return;
        }
        panel.classList.add('hidden');
    });

    form.addEventListener('submit', function (event) {
        if (uploading) {
            event.preventDefault();
            return;
        }
        var files = selectedFiles();
        if (files.length === 0) {
            return;
        }
        event.preventDefault();

        var limitBytes = parseInt(panel.getAttribute('data-limit'), 10) || 0;
        var total = 0;
        files.forEach(function (file) {
            total += file.size;
        });

        errorBox.classList.add('hidden');
        errorBox.textContent = '';
        cancelBtn.textContent = 'Cancel';
        cancelBtn.classList.remove('hidden');
        panel.classList.remove('hidden');
        setBar(0, 'busy');
        setDot('busy');
        markStep('upload');
        phaseLabel.textContent = 'Uploading';
        fileLabel.textContent = videoInput && videoInput.files && videoInput.files.length > 0 ? videoInput.files[0].name : '';

        if (limitBytes > 0 && total > limitBytes) {
            fail('This upload is ' + formatBytes(total) + ', but the server accepts at most ' + formatBytes(limitBytes) + '. Raise post_max_size and upload_max_filesize in PHP and the body size limit in your web server, or choose a smaller file.');
            return;
        }

        statsLabel.textContent = '0 B of ' + formatBytes(total);
        lockForm(true);
        setUploading(true);

        lastTime = Date.now();
        lastLoaded = 0;
        speed = 0;

        request = new XMLHttpRequest();
        request.open('POST', form.getAttribute('action'), true);
        request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        request.setRequestHeader('Accept', 'application/json');

        request.upload.addEventListener('progress', function (e) {
            if (!e.lengthComputable) {
                return;
            }
            var now = Date.now();
            var elapsed = (now - lastTime) / 1000;
            if (elapsed >= 0.25) {
                var instant = (e.loaded - lastLoaded) / elapsed;
                speed = speed > 0 ? (speed * 0.7 + instant * 0.3) : instant;
                lastTime = now;
                lastLoaded = e.loaded;
            }
            setBar(e.total > 0 ? (e.loaded / e.total) * 100 : 0, 'busy');
            var parts = [formatBytes(e.loaded) + ' of ' + formatBytes(e.total)];
            if (speed > 0) {
                parts.push(formatBytes(speed) + '/s');
                parts.push(formatDuration((e.total - e.loaded) / speed) + ' left');
            }
            statsLabel.textContent = parts.join(' · ');
        });

        request.upload.addEventListener('load', function () {
            setBar(100, 'busy');
            markStep('process');
            phaseLabel.textContent = 'Processing on the server';
            statsLabel.textContent = formatBytes(total) + ' sent · saving the video, keep this page open';
        });

        request.addEventListener('load', function () {
            var payload = null;
            try {
                payload = JSON.parse(request.responseText);
            } catch (parseError) {
                payload = null;
            }
            if (request.status === 413) {
                fail('The web server refused the upload because it exceeds its configured body size limit. Raise that limit and try again.');
                return;
            }
            if (payload && payload.success) {
                setUploading(false);
                setBar(100, 'ok');
                setDot('ok');
                markStep('done');
                phaseLabel.textContent = 'Completed';
                statsLabel.textContent = payload.message || 'Saved.';
                cancelBtn.classList.add('hidden');
                window.setTimeout(function () {
                    window.location.href = payload.redirect || '/admin/videos';
                }, 700);
                return;
            }
            if (payload && payload.message) {
                fail(payload.message);
                return;
            }
            fail('The server returned an unexpected response (HTTP ' + request.status + '). Reload the video list to check whether it was saved.');
        });

        request.addEventListener('error', function () {
            fail('The connection was lost during the upload. Nothing was saved — you can try again.');
        });

        request.addEventListener('abort', function () {
            setUploading(false);
            lockForm(false);
            setBar(0, 'busy');
            setDot('busy');
            markStep('upload');
            phaseLabel.textContent = 'Upload cancelled';
            statsLabel.textContent = 'Nothing was saved.';
            cancelBtn.textContent = 'Dismiss';
        });

        request.send(new FormData(form));
    });
})();
</script>
