<?php
$formAction = !empty($album) ? '/admin/albums/' . (int)$album['id'] . '/update' : '/admin/albums/store';
$isEdit = !empty($album);

$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 ?? []));

$curStatus = $album['status'] ?? 'draft';
$vtype     = $album['video_type'] ?? 'hetero';
$cover     = $album['cover_file'] ?? '';
$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';

 
$formImages = [];
if ($isEdit) {
    $sid = isset($album['storage_id']) ? (int)$album['storage_id'] : null;
    $folder = $album['album_folder'] ?? '';
    foreach (Album::images($album) as $im) {
        $f = $im['f'] ?? '';
        if ($f === '') continue;
        $formImages[] = ['f' => $f, 'url' => AlbumAsset::resolveUrl($folder, $f, $sid), 'w' => $im['w'] ?? null, 'h' => $im['h'] ?? null];
    }
}
?>

<style>
.tok{position:relative}
.tok__wrap{display:flex;flex-wrap:wrap;gap:6px;padding:8px 10px;border:1px solid #d1d5db;border-radius:8px;min-height:42px;cursor:text;transition:border-color .15s,box-shadow .15s;background:#fff;align-items:center}
.tok__tags{display:flex;flex-wrap:wrap;gap:6px}
.tok__wrap:focus-within{border-color:#3b82f6;box-shadow:0 0 0 3px rgba(59,130,246,.15)}
.tok__tag{display:inline-flex;align-items:center;gap:4px;padding:3px 8px 3px 10px;background:#eff6ff;color:#1d4ed8;font-size:12px;font-weight:600;border-radius:6px;white-space:nowrap;line-height:1.4}
.tok__tag button{display:flex;align-items:center;justify-content:center;width:16px;height:16px;border:none;background:none;color:#3b82f6;font-size:16px;cursor:pointer;padding:0;border-radius:50%;line-height:1}
.tok__tag button:hover{background:#dbeafe;color:#1e40af}
.tok__input{flex:1;min-width:100px;border:none;outline:none;font-size:13px;padding:2px 0;background:transparent;color:#1f2937}
.tok__input::placeholder{color:#9ca3af}
.tok__drop{display:none;position:absolute;top:100%;left:0;right:0;margin-top:4px;background:#fff;border:1px solid #e5e7eb;border-radius:8px;box-shadow:0 8px 24px rgba(0,0,0,.12);max-height:200px;overflow-y:auto;z-index:60}
.tok__drop.open{display:block}
.tok__opt{padding:8px 12px;font-size:13px;cursor:pointer;color:#374151;transition:background .1s}
.tok__opt:hover,.tok__opt.hl{background:#eff6ff;color:#1d4ed8}
.tok__empty{padding:8px 12px;font-size:12px;color:#9ca3af;font-style:italic}
.vf-tab-panel{display:none}.vf-tab-panel.active{display:block}
.img-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(110px,1fr));gap:10px}
.img-card{position:relative;border-radius:8px;overflow:hidden;border:2px solid #e5e7eb;background:#f8fafc;aspect-ratio:3/4}
.img-card img{width:100%;height:100%;object-fit:cover;display:block}
.img-card.removed{opacity:.35;filter:grayscale(1)}
.img-card.is-cover{border-color:#3b82f6}
.img-card__bar{position:absolute;top:4px;right:4px;display:flex;gap:4px}
.img-card__bar button{width:22px;height:22px;border:none;border-radius:6px;background:rgba(15,23,42,.7);color:#fff;font-size:13px;cursor:pointer;display:flex;align-items:center;justify-content:center;line-height:1}
.img-card__bar button:hover{background:rgba(15,23,42,.95)}
.img-card__bar .on{background:#3b82f6}
.img-card__cover{position:absolute;bottom:0;left:0;right:0;background:#3b82f6;color:#fff;font-size:9px;font-weight:700;text-align:center;padding:2px;letter-spacing:.04em;display:none}
.img-card.is-cover .img-card__cover{display:block}
</style>

<form method="POST" action="<?= htmlspecialchars($formAction) ?>" enctype="multipart/form-data" id="albumForm">
    <?= Router::csrfField() ?>
    <input type="hidden" name="existing_images" id="existing_images" value="">
    <input type="hidden" name="cover_file" id="cover_file" value="<?= htmlspecialchars($cover) ?>">

    <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="images">
                <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="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>Images <?php if ($isEdit): ?><span class="text-gray-400">(<?= count($formImages) ?>)</span><?php endif; ?></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">Information</h3>
                        <div class="flex items-center gap-1">
                            <?php if ($isEdit && count($albumLanguages ?? []) > 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($album['slug'])): ?>
                            <a href="/album/<?= htmlspecialchars($album['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($album['title'] ?? '') ?>" required class="<?= $inputCls ?>" placeholder="Enter album title...">
                        </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">/album/</span>
                                <input type="text" id="slug" name="slug" value="<?= htmlspecialchars($album['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 album..."><?= htmlspecialchars($album['description'] ?? '') ?></textarea>
                        </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($album['published_at'])): ?><span>Published <strong class="text-gray-500"><?= date('M j, Y H:i', strtotime($album['published_at'])) ?></strong></span><?php endif; ?>
                            <span>Created <strong class="text-gray-500"><?= date('M j, Y H:i', strtotime($album['created_at'])) ?></strong></span>
                            <span>Updated <strong class="text-gray-500"><?= date('M j, Y H:i', strtotime($album['updated_at'])) ?></strong></span>
                            <?php if (!empty($album['external_id'])): ?><span>Ext ID <strong class="text-gray-500 font-mono"><?= htmlspecialchars($album['external_id']) ?></strong></span><?php endif; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            
            <div class="vf-tab-panel" id="tabImages">
                <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">Images</h3></div>
                    <div class="p-4 space-y-5">
                        <div id="imgGrid" class="img-grid"></div>
                        <p id="imgEmpty" class="text-sm text-gray-400 hidden">No images yet — upload some below.</p>
                        <div>
                            <label for="images" class="block text-sm font-medium text-gray-700 mb-1">Upload images</label>
                            <input type="file" id="images" name="images[]" accept="image/*" multiple 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">
                            <p class="mt-1 text-xs text-gray-500">Select multiple files. They are added to the album in order.</p>
                        </div>
                        <div>
                            <label for="image_urls" class="block text-sm font-medium text-gray-700 mb-1">…or add image URLs</label>
                            <textarea id="image_urls" name="image_urls" rows="3" class="<?= $inputCls ?> font-mono text-xs resize-y" placeholder="https://cdn.example.com/img1.jpg&#10;https://cdn.example.com/img2.jpg"></textarea>
                            <p class="mt-1 text-xs text-gray-500">One URL per line. Useful for referencing externally-hosted images.</p>
                        </div>
                    </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">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">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 (Album::typeLabels() as $vtCode => $vtLabel): ?>
                            <option value="<?= $vtCode ?>" <?= $vtype === $vtCode ? 'selected' : '' ?>><?= htmlspecialchars($vtLabel) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <label class="flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
                        <input type="checkbox" name="is_featured" value="1" <?= !empty($album['is_featured']) ? 'checked' : '' ?> class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                        Featured album
                    </label>
                    <?php if ($isEdit && !empty($album['album_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($album['album_folder']) ?>"><?= htmlspecialchars($album['album_folder']) ?></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 Album' ?>
                        </button>
                        <a href="/admin/albums" 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">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)($album['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)($album['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)($album['dislikes'] ?? 0) ?>" min="0" class="<?= $inputCls ?> font-mono"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

<?php if ($isEdit && count($albumLanguages ?? []) > 1):
    $_vtlLangs = [];
    $_vtlDefault = $defaultLang ?? 'en';
    foreach ($albumLanguages as $vl) {
        if ($vl['code'] === $_vtlDefault) continue;
        $_vtlLangs[] = ['code' => $vl['code'], 'name' => $vl['name'], 'flag' => Translator::flagCode($vl['code']), 'title' => $albumTranslations[$vl['code']]['title'] ?? '', 'description' => $albumTranslations[$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)}
.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__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;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}
.vtl-btn--save{background:#4f46e5;color:#fff}.vtl-btn--cancel{background:#f3f4f6;color:#374151}
.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="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>Album 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');}
function vtlSave(){
    var btn=document.getElementById('vtlSaveBtn'),modal=document.querySelector('.vtl-modal');
    modal.classList.add('vtl-saving');btn.textContent='Saving...';
    var data={};
    document.querySelectorAll('#vtlBody [data-lang]').forEach(function(el){var l=el.dataset.lang,f=el.dataset.field;if(!data[l])data[l]={};data[l][f]=el.value;});
    fetch('/admin/albums/<?= (int)$album['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 imgs=<?= json_encode($formImages, JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
    var grid=document.getElementById('imgGrid');
    var empty=document.getElementById('imgEmpty');
    var coverInput=document.getElementById('cover_file');
    var existingInput=document.getElementById('existing_images');
    var form=document.getElementById('albumForm');
    var coverF=coverInput.value;

    function esc(s){var d=document.createElement('div');d.textContent=s==null?'':s;return d.innerHTML;}
    function render(){
        grid.innerHTML='';
        if(!imgs.length){empty.classList.remove('hidden');return;}
        empty.classList.add('hidden');
        if((!coverF||!imgs.some(function(i){return i.f===coverF&&!i._removed;}))){
            var first=imgs.find(function(i){return !i._removed;});coverF=first?first.f:'';
        }
        imgs.forEach(function(im,idx){
            var card=document.createElement('div');
            card.className='img-card'+(im._removed?' removed':'')+(im.f===coverF&&!im._removed?' is-cover':'');
            card.innerHTML='<img src="'+esc(im.url)+'" alt="" loading="lazy">'
                +'<div class="img-card__bar"><button type="button" class="cover-btn'+(im.f===coverF?' on':'')+'" title="Set as cover">&#9733;</button>'
                +'<button type="button" class="rm-btn" title="'+(im._removed?'Restore':'Remove')+'">'+(im._removed?'&#8635;':'&times;')+'</button></div>'
                +'<div class="img-card__cover">COVER</div>';
            card.querySelector('.cover-btn').addEventListener('click',function(){if(im._removed)return;coverF=im.f;render();});
            card.querySelector('.rm-btn').addEventListener('click',function(){im._removed=!im._removed;render();});
            grid.appendChild(card);
        });
    }
    form.addEventListener('submit',function(){
        var kept=imgs.filter(function(i){return !i._removed;}).map(function(i){return {f:i.f,w:i.w,h:i.h};});
        existingInput.value=JSON.stringify(kept);
        coverInput.value=(coverF&&kept.some(function(i){return i.f===coverF;}))?coverF:(kept[0]?kept[0].f:'');
    });
    render();
})();
</script>

<script>

(function(){
    document.querySelectorAll('.tok').forEach(function(el){
        var name=el.dataset.name;var items=JSON.parse(el.dataset.items);var selected=new Set(JSON.parse(el.dataset.selected).map(String));
        var wrap=el.querySelector('.tok__wrap');var tagsDiv=el.querySelector('.tok__tags');var input=el.querySelector('.tok__input');var drop=el.querySelector('.tok__drop');var hlIdx=-1;
        function render(){
            tagsDiv.innerHTML='';el.querySelectorAll('input[type=hidden]').forEach(function(h){h.remove();});
            items.forEach(function(item){
                if(!selected.has(String(item.id)))return;
                var span=document.createElement('span');span.className='tok__tag';span.innerHTML=esc(item.n)+'<button type="button">&times;</button>';
                span.querySelector('button').addEventListener('click',function(e){e.stopPropagation();selected.delete(String(item.id));render();input.focus();});
                tagsDiv.appendChild(span);
                var h=document.createElement('input');h.type='hidden';h.name=name;h.value=item.id;el.appendChild(h);
            });
        }
        function showDrop(filter){
            var f=filter.toLowerCase();var filtered=items.filter(function(i){return !selected.has(String(i.id))&&i.n.toLowerCase().indexOf(f)!==-1;});
            drop.innerHTML='';hlIdx=-1;
            if(!f||filtered.length===0){if(f&&filtered.length===0){drop.innerHTML='<div class="tok__empty">No results</div>';drop.classList.add('open');}else{drop.classList.remove('open');}return;}
            filtered.slice(0,12).forEach(function(item){
                var d=document.createElement('div');d.className='tok__opt';d.textContent=item.n;
                d.addEventListener('mousedown',function(e){e.preventDefault();selected.add(String(item.id));input.value='';drop.classList.remove('open');render();input.focus();});
                drop.appendChild(d);
            });
            drop.classList.add('open');
        }
        input.addEventListener('input',function(){showDrop(input.value);});
        input.addEventListener('focus',function(){if(input.value)showDrop(input.value);});
        input.addEventListener('blur',function(){setTimeout(function(){drop.classList.remove('open');},150);});
        input.addEventListener('keydown',function(e){
            var opts=drop.querySelectorAll('.tok__opt');
            if(e.key==='ArrowDown'){e.preventDefault();hlIdx=Math.min(hlIdx+1,opts.length-1);updHl(opts);}
            else if(e.key==='ArrowUp'){e.preventDefault();hlIdx=Math.max(hlIdx-1,0);updHl(opts);}
            else if(e.key==='Enter'&&hlIdx>=0&&opts[hlIdx]){e.preventDefault();opts[hlIdx].dispatchEvent(new MouseEvent('mousedown'));}
            else if(e.key==='Backspace'&&input.value===''&&selected.size>0){var last=Array.from(selected).pop();selected.delete(last);render();}
        });
        wrap.addEventListener('click',function(){input.focus();});
        function updHl(opts){opts.forEach(function(o,i){o.classList.toggle('hl',i===hlIdx);});}
        function esc(s){var d=document.createElement('div');d.textContent=s;return d.innerHTML;}
        render();
    });
})();
</script>
