{% extends 'admin/base.html' %}
{% block title %}{{ t('media.edit_title') }}{% endblock %}

{% block extra_css %}
{% endblock %}

{% block content %}
<div class="page-header">
    <h2>✏️ {{ t('media.edit_title') }}</h2>
    <p>{{ t('media.edit_subtitle') }}</p>
</div>

<div class="settings-section">
    <div class="edit-container">
        <!-- Image Preview -->
        <div class="image-preview-panel">
            <img src="{{ image.public_url }}" alt="{{ image.alt_text }}">
            
            <div class="form-group">
                <label>{{ t('media.image_url') }}</label>
                <div class="url-row">
                    <input type="text" class="url-input" value="{{ image.public_url }}" readonly id="imageUrl">
                    <button class="copy-btn" onclick="copyUrl()" title="{{ t('media.copy_url') }}">📋 {{ t('media.copy_url') }}</button>
                </div>
                <div class="help-text">{{ t('media.image_url_help') }}</div>
            </div>

            <div class="image-info">
                <strong>{{ t('media.filename') }}</strong> {{ image.original_filename or image.filename }}<br>
                {% if image.file_size %}<strong>{{ t('media.size') }}</strong> {{ (image.file_size / 1024)|round(0)|int }} {{ t('common.unit_kb') }}<br>{% endif %}
                {% if image.width and image.height %}<strong>{{ t('media.dimensions') }}</strong> {{ image.width }} × {{ image.height }}px<br>{% endif %}
                {% if image.mime_type %}<strong>{{ t('media.type') }}</strong> {{ image.mime_type }}<br>{% endif %}
                {% if image.dominant_color %}
                <strong>{{ t('media.dominant_color') }}</strong> 
                <span class="dominant-color-swatch" style="background:{{ image.dominant_color }};"></span> 
                {{ image.dominant_color }}<br>
                {% endif %}
                <strong>{{ t('media.uploaded') }}</strong> {{ image.uploaded_at|format_datetime }}
            </div>

            {% set variants = image.get_variants() %}
            {% if variants and (variants.get('webp') or variants.get('avif')) %}
            <div class="variants-info">
                <strong class="d-block mb-2">⚡ {{ t('media.generated_variants') }}</strong>
                {% for fmt in ['webp', 'avif'] %}
                {% if variants.get(fmt) %}
                <div class="mb-2">
                    <strong class="text-uppercase">{{ fmt }}:</strong>
                    {% for width_key, v in variants[fmt].items() %}
                    <span class="variant-badge">{{ width_key }}w · {{ (v.size / 1024)|round(0)|int }} {{ t('common.unit_kb') }}</span>
                    {% endfor %}
                </div>
                {% endif %}
                {% endfor %}
                {% if variants.get('og') %}
                <div class="variants-separator">
                    <strong>📱 {{ t('media.og_social') }}</strong>
                    {% for fmt_key, v in variants['og'].items() %}
                    <span class="variant-badge">{{ fmt_key|upper }} · {{ (v.size / 1024)|round(0)|int }} {{ t('common.unit_kb') }}</span>
                    {% endfor %}
                </div>
                {% endif %}
            </div>
            {% endif %}
        </div>

        <!-- Edit Form -->
        <form method="POST" class="edit-form-panel" data-inline-save>
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <input type="hidden" name="return_to" value="{{ admin_back_value() }}">
            <div class="form-group">
                <label for="alt_text" class="required">{{ t('media.alt_text') }}</label>
                <input type="text" id="alt_text" name="alt_text" value="{{ image.alt_text }}" required>
                <div class="help-text">{{ t('media.alt_text_help') }}</div>
            </div>
            
            <div class="form-group">
                <label for="title">{{ t('media.title_label') }}</label>
                <input type="text" id="title" name="title" value="{{ image.title or '' }}">
            </div>
            
            <div class="form-group">
                <label for="download_slug">{{ t('media.public_slug') }}</label>
                <div class="slug-row">
                    <span class="slug-prefix">/</span>
                    <input type="text" id="download_slug" name="download_slug" value="{{ image.download_slug or '' }}" autocomplete="off" spellcheck="false">
                    <span class="slug-suffix">.{{ image.original_extension }}</span>
                </div>
                <div class="help-text">{{ t('media.public_slug_help') }}</div>
            </div>
            
            <div class="form-group">
                <label for="caption">{{ t('media.caption') }}</label>
                <textarea id="caption" name="caption" rows="2">{{ image.caption or '' }}</textarea>
            </div>
            
            <div class="form-group">
                <label for="description">{{ t('media.description') }}</label>
                <textarea id="description" name="description" rows="3">{{ image.description or '' }}</textarea>
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">💾 {{ t('media.save_changes') }}</button>
                <a href="{{ admin_back_url('admin_media_library') }}" class="btn btn-secondary">{{ t('common.cancel') }}</a>
                <button type="button" class="btn btn-danger" onclick="checkUsageThenDelete('image', {{ image.id }}, document.getElementById('deleteForm'))">🗑️ {{ t('media.delete') }}</button>
            </div>
        </form>
        <form id="deleteForm" method="POST" action="{{ url_for('admin_media_delete', image_id=image.id) }}">
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        </form>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
function copyUrl() {
    const input = document.getElementById('imageUrl');
    input.select();
    document.execCommand('copy');
    const btn = input.nextElementSibling;
    const originalText = btn.textContent;
    btn.textContent = '✅ {{ t("media.copied") }}';
    setTimeout(() => { btn.textContent = originalText; }, 1500);
}

async function checkUsageThenDelete(assetType, assetId, formEl) {
    try {
        const res = await fetch('/admin/api/check-usage', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ type: assetType, id: assetId })
        });
        const data = await res.json();
        
        var msg = '{{ t("media.delete_confirm") }}';
        
        if (data.count > 0) {
            msg = '{{ t("media.usage_warning") }}\n\n';
            data.usage.forEach(function(u) {
                var typeLabel = u.type.charAt(0).toUpperCase() + u.type.slice(1);
                msg += '• ' + typeLabel + ': ' + u.title + ' (' + u.fields.join(', ') + ')\n';
            });
            msg += '\n{{ t("media.usage_confirm_delete") }}';
        }
        
        AdminDialog.confirm(msg, { danger: true }).then(function(ok) {
            if (ok) formEl.submit();
        });
    } catch (err) {
        AdminDialog.confirm('{{ t("media.delete_confirm") }}', { danger: true }).then(function(ok) {
            if (ok) formEl.submit();
        });
    }
}
</script>
{% endblock %}
