<?php
$formAction = !empty($category) ? '/admin/albums/categories/' . (int)$category['id'] . '/update' : '/admin/albums/categories/store';
$isEdit = !empty($category);
?>
<div class="bg-white rounded-lg shadow-sm border border-gray-200">
    <div class="p-6">
        <form method="POST" action="<?= htmlspecialchars($formAction) ?>" enctype="multipart/form-data">
            <?= Router::csrfField() ?>

            <div class="mb-4 flex items-center justify-between">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Type</label>
                    <?php $vtype = $category['video_type'] ?? Video::defaultType(); ?>
                    <div class="flex gap-4">
                        <?php foreach (Video::typeLabels() as $val => $label): ?>
                        <label class="inline-flex items-center gap-1.5 text-sm text-gray-700 cursor-pointer">
                            <input type="radio" name="video_type" value="<?= $val ?>" <?= $vtype === $val ? 'checked' : '' ?>
                                   class="text-blue-600 focus:ring-blue-500">
                            <?= $label ?>
                        </label>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php if ($isEdit && count($entityLanguages ?? []) > 1): ?>
                <button type="button" onclick="etlOpen()" 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; ?>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label for="name" class="block text-sm font-medium text-gray-700 mb-1">Name</label>
                    <input type="text" id="name" name="name" value="<?= htmlspecialchars($category['name'] ?? '') ?>" required
                           class="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">
                </div>

                <div>
                    <label for="slug" class="block text-sm font-medium text-gray-700 mb-1">Slug</label>
                    <input type="text" id="slug" name="slug" value="<?= htmlspecialchars($category['slug'] ?? '') ?>"
                           class="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">
                    <p class="mt-1 text-xs text-gray-500">Leave empty to auto-generate.</p>
                </div>
            </div>

            <div class="mt-4">
                <label for="description" class="block text-sm font-medium text-gray-700 mb-1">Description</label>
                <textarea id="description" name="description" rows="4"
                          class="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 min-h-[120px] resize-y"><?= htmlspecialchars($category['description'] ?? '') ?></textarea>
            </div>

            <div class="mt-4">
                <label for="thumbnail" class="block text-sm font-medium text-gray-700 mb-1">Thumbnail</label>
                <?php if (!empty($category['thumbnail'])): ?>
                    <div class="mb-2">
                        <?php $thumbUrl = str_starts_with($category['thumbnail'], 'http') ? $category['thumbnail'] : '/uploads/thumbnails/' . $category['thumbnail']; ?>
                        <img src="<?= htmlspecialchars($thumbUrl) ?>" alt="" class="w-20 h-20 object-cover rounded-lg">
                    </div>
                <?php endif; ?>
                <input type="file" id="thumbnail" name="thumbnail" accept="image/*"
                       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">
            </div>

            <div class="flex flex-col sm:flex-row gap-2 sm:gap-3 mt-6 pt-4 border-t border-gray-200">
                <button type="submit" class="w-full sm:w-auto inline-flex items-center justify-center px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700"><?= $isEdit ? 'Update' : 'Create Album Category' ?></button>
                <a href="/admin/albums/categories" class="w-full sm:w-auto 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">Cancel</a>
            </div>
        </form>
    </div>
</div>

<?php if ($isEdit && count($entityLanguages ?? []) > 1):
    $_etlLangs = [];
    $_etlDefault = $defaultLang ?? 'en';
    foreach ($entityLanguages as $el) {
        if ($el['code'] === $_etlDefault) continue;
        $_etlLangs[] = [
            'code' => $el['code'],
            'name' => $el['name'],
            'flag' => Translator::flagCode($el['code']),
            'tname' => $entityTranslations[$el['code']]['name'] ?? '',
            'tdescription' => $entityTranslations[$el['code']]['description'] ?? '',
        ];
    }
?>
<style>
.etl-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}
.etl-overlay.open{display:flex}
.etl-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:etlIn .2s ease}
@keyframes etlIn{from{opacity:0;transform:scale(.96) translateY(8px)}to{opacity:1;transform:none}}
.etl-modal__header{display:flex;align-items:center;justify-content:space-between;padding:14px 18px;border-bottom:1px solid #e5e7eb;flex-shrink:0}
.etl-modal__title{display:flex;align-items:center;gap:8px;font-size:14px;font-weight:600;color:#111827}
.etl-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}
.etl-modal__close:hover{background:#e5e7eb;color:#111}
.etl-modal__body{padding:12px 18px;overflow-y:auto;flex:1}
.etl-lang{padding:12px 0;border-bottom:1px solid #f3f4f6}
.etl-lang:last-child{border-bottom:none}
.etl-lang__head{display:flex;align-items:center;gap:8px;margin-bottom:8px}
.etl-lang__flag{width:18px;height:13px;border-radius:2px;object-fit:cover}
.etl-lang__name{font-size:13px;font-weight:600;color:#374151}
.etl-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}
.etl-lang__input:focus{border-color:#6366f1;box-shadow:0 0 0 3px rgba(99,102,241,.08)}
.etl-lang__lbl{font-size:11px;color:#9ca3af;margin-bottom:3px}
.etl-lang__textarea{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;min-height:60px;resize:vertical}
.etl-lang__textarea:focus{border-color:#6366f1;box-shadow:0 0 0 3px rgba(99,102,241,.08)}
.etl-modal__footer{display:flex;justify-content:flex-end;gap:8px;padding:12px 18px;border-top:1px solid #e5e7eb;flex-shrink:0}
.etl-btn{padding:7px 18px;border-radius:7px;font-size:13px;font-weight:600;cursor:pointer;border:none;transition:background .12s}
.etl-btn--save{background:#4f46e5;color:#fff}.etl-btn--save:hover{background:#4338ca}
.etl-btn--cancel{background:#f3f4f6;color:#374151}.etl-btn--cancel:hover{background:#e5e7eb}
.etl-saving{opacity:.6;pointer-events:none}
</style>
<div class="etl-overlay" id="etlOverlay">
    <div class="etl-modal">
        <div class="etl-modal__header">
            <div class="etl-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>Album Category Translations</span>
            </div>
            <button type="button" class="etl-modal__close" onclick="etlClose()">
                <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="etl-modal__body" id="etlBody">
            <?php foreach ($_etlLangs as $el): ?>
            <div class="etl-lang">
                <div class="etl-lang__head">
                    <img src="https://flagcdn.com/w40/<?= htmlspecialchars($el['flag']) ?>.png" class="etl-lang__flag" alt="">
                    <span class="etl-lang__name"><?= htmlspecialchars($el['name']) ?></span>
                </div>
                <div class="etl-lang__lbl">Name</div>
                <input type="text" class="etl-lang__input" data-lang="<?= htmlspecialchars($el['code']) ?>" data-field="name" value="<?= htmlspecialchars($el['tname']) ?>" placeholder="Translated name...">
                <div class="etl-lang__lbl">Description</div>
                <textarea class="etl-lang__textarea" data-lang="<?= htmlspecialchars($el['code']) ?>" data-field="description" placeholder="Translated description..."><?= htmlspecialchars($el['tdescription']) ?></textarea>
            </div>
            <?php endforeach; ?>
        </div>
        <div class="etl-modal__footer">
            <button type="button" class="etl-btn etl-btn--cancel" onclick="etlClose()">Cancel</button>
            <button type="button" class="etl-btn etl-btn--save" id="etlSaveBtn" onclick="etlSave()">Save Translations</button>
        </div>
    </div>
</div>
<script>
function etlOpen(){document.getElementById('etlOverlay').classList.add('open');}
function etlClose(){document.getElementById('etlOverlay').classList.remove('open');}
document.getElementById('etlOverlay').addEventListener('click',function(e){if(e.target===this)etlClose();});
function etlSave(){
    var btn=document.getElementById('etlSaveBtn');
    var modal=document.querySelector('.etl-modal');
    modal.classList.add('etl-saving');
    btn.textContent='Saving...';
    var data={};
    document.querySelectorAll('#etlBody [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/albums/categories/<?= (int)$category['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('etl-saving');
        btn.textContent='Save Translations';
        if(r.success){etlClose();}
    }).catch(function(){
        modal.classList.remove('etl-saving');
        btn.textContent='Save Translations';
        alert('Failed to save translations');
    });
}
</script>
<?php endif; ?>
