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

{% block extra_css %}
{% endblock %}

{% block content %}
<div class="page-header page-header--with-action">
    <div class="page-header__content">
        <h2>🖼️ {{ t('media.library_title') }}</h2>
        <p>{{ t('media.library_subtitle') }}</p>
    </div>
    <a href="{{ url_for('admin_media_upload') }}" class="btn-upload">{{ t('media.upload_image_btn') }}</a>
</div>

<div class="settings-section">
<div class="filter-bar">
    <input type="text" id="searchInput" value="{{ search_query or '' }}" placeholder="🔍 {{ t('media.search_placeholder') }}" autocomplete="off">
</div>

<div id="media-content">
{% if images.items %}
<div class="media-grid">
    {% for image in images.items %}
    <div class="media-card">
        <img src="{{ image.public_url }}" alt="{{ image.alt_text }}">
        <div class="media-card-body">
            <div class="media-alt" title="{{ image.alt_text }}">{{ image.alt_text }}</div>
            <div class="media-info">
                {{ image.original_filename or image.filename }}
                {% if image.file_size %}· {{ (image.file_size / 1024)|round(0)|int }} {{ t('media.unit_kb') }}{% endif %}
            </div>
            <div class="media-url-row">
                <input type="text" class="media-url-input" value="{{ image.public_url }}" readonly id="url-{{ image.id }}">
                <button class="copy-btn" onclick="copyUrl('url-{{ image.id }}', this)" title="{{ t('media.copy_url') }}">📋 {{ t('media.copy_url') }}</button>
            </div>
            <div class="media-actions">
                <a href="{{ url_for('admin_media_edit', image_id=image.id) }}" class="action-link action-edit">✏️ {{ t('table.edit') }}</a>
                <form method="POST" action="{{ url_for('admin_media_delete', image_id=image.id) }}" class="d-inline">
                    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                    <button type="button" class="action-link action-delete" onclick="checkUsageThenDelete('image', {{ image.id }}, this.closest('form'))">🗑️ {{ t('table.delete') }}</button>
                </form>
            </div>
        </div>
    </div>
    {% endfor %}
</div>

{% else %}
<div class="empty-state">
    <h3>🖼️ {{ t('media.no_images') }}</h3>
    <p>{{ t('media.no_images_text') }}</p>
    <a href="{{ url_for('admin_media_upload') }}" class="btn-upload">{{ t('media.upload_first') }}</a>
</div>
{% endif %}
</div>
</div>

<div class="pagination-footer">
{% if images.items and images.pages > 1 %}
<div class="pagination">
    {% if images.has_prev %}
        <a href="{{ url_for('admin_media_library', page=images.prev_num, per_page=per_page) }}">{{ t('pagination.prev') }}</a>
    {% endif %}
    {% for p in images.iter_pages(left_edge=1, right_edge=1, left_current=2, right_current=2) %}
        {% if p %}
            {% if p == images.page %}
                <span class="current">{{ p }}</span>
            {% else %}
                <a href="{{ url_for('admin_media_library', page=p, per_page=per_page) }}">{{ p }}</a>
            {% endif %}
        {% else %}
            <span>…</span>
        {% endif %}
    {% endfor %}
    {% if images.has_next %}
        <a href="{{ url_for('admin_media_library', page=images.next_num, per_page=per_page) }}">{{ t('pagination.next') }}</a>
    {% endif %}
</div>
{% endif %}
{% if images.items %}
    <div class="per-page-selector">
        <span>{{ t('pagination.per_page') }}</span>
        <select onchange="var u=new URLSearchParams(location.search);u.set('per_page',this.value);u.delete('page');location.search=u">
            {% for pp in [20, 50, 100] %}
            <option value="{{ pp }}" {% if per_page == pp %}selected{% endif %}>{{ pp }}</option>
            {% endfor %}
        </select>
        <span>{{ t('pagination.per_page_suffix') }}</span>
    </div>
{% endif %}
</div>
{% endblock %}

{% block extra_js %}
<script>
function copyUrl(inputId, btn) {
    const input = document.getElementById(inputId);
    input.select();
    document.execCommand('copy');
    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") }}';
        }
        
        if (confirm(msg)) {
            formEl.submit();
        }
    } catch (err) {
        if (confirm('{{ t("media.delete_confirm") }}')) {
            formEl.submit();
        }
    }
}

/* Live search — updates grid without page reload */
(function() {
    var input = document.getElementById('searchInput');
    if (!input) return;

    var _csrfToken = '{{ csrf_token() }}';
    var _baseUrl = '{{ url_for("admin_media_library") }}';
    var _uploadUrl = '{{ url_for("admin_media_upload") }}';
    var _perPage = {{ per_page }};
    var _debounceTimer;

    var _i18n = {
        copy_url: '{{ t("media.copy_url") }}',
        copied: '{{ t("media.copied") }}',
        edit: '{{ t("table.edit") }}',
        delete_action: '{{ t("table.delete") }}',
        delete_confirm: '{{ t("media.delete_confirm") }}',
        unit_kb: '{{ t("media.unit_kb") }}',
        no_images: '{{ t("media.no_images") }}',
        no_images_text: '{{ t("media.no_images_text") }}',
        upload_first: '{{ t("media.upload_first") }}',
        no_results: '{{ t("media.no_results") }}',
        clear_search: '{{ t("media.clear_search") }}',
        per_page_label: '{{ t("pagination.per_page") }}',
        per_page_suffix: '{{ t("pagination.per_page_suffix") }}',
        prev: '{{ t("pagination.prev") }}',
        next: '{{ t("pagination.next") }}'
    };

    function escapeHtml(str) {
        var div = document.createElement('div');
        div.appendChild(document.createTextNode(str || ''));
        return div.innerHTML;
    }

    function renderContent(data) {
        var container = document.getElementById('media-content');
        if (!data.items || data.items.length === 0) {
            var hasSearch = input.value.trim();
            container.innerHTML = '<div class="empty-state">' +
                (hasSearch
                    ? '<h3>🔍 ' + escapeHtml(_i18n.no_results) + '</h3>' +
                      '<a href="' + _baseUrl + '" class="btn btn-primary">' + escapeHtml(_i18n.clear_search) + '</a>'
                    : '<h3>🖼️ ' + escapeHtml(_i18n.no_images) + '</h3>' +
                      '<p>' + escapeHtml(_i18n.no_images_text) + '</p>' +
                      '<a href="' + _uploadUrl + '" class="btn-upload">' + escapeHtml(_i18n.upload_first) + '</a>'
                ) + '</div>';
            return;
        }

        var cards = data.items.map(function(img) {
            var urlId = 'url-' + img.id;
            var sizeStr = img.file_size
                ? ' · ' + Math.round(img.file_size / 1024) + ' ' + _i18n.unit_kb
                : '';

            return '<div class="media-card">' +
                '<img src="' + escapeHtml(img.url) + '" alt="' + escapeHtml(img.alt_text) + '">' +
                '<div class="media-card-body">' +
                    '<div class="media-alt" title="' + escapeHtml(img.alt_text) + '">' + escapeHtml(img.alt_text) + '</div>' +
                    '<div class="media-info">' + escapeHtml(img.original_filename) + sizeStr + '</div>' +
                    '<div class="media-url-row">' +
                        '<input type="text" class="media-url-input" value="' + escapeHtml(img.url) + '" readonly id="' + urlId + '">' +
                        '<button class="copy-btn" onclick="copyUrl(\'' + urlId + '\', this)" title="' + escapeHtml(_i18n.copy_url) + '">📋 ' + escapeHtml(_i18n.copy_url) + '</button>' +
                    '</div>' +
                    '<div class="media-actions">' +
                        '<a href="/admin/media/' + img.id + '/edit" class="action-link action-edit">✏️ ' + _i18n.edit + '</a>' +
                        '<form method="POST" action="/admin/media/' + img.id + '/delete" class="d-inline">' +
                            '<input type="hidden" name="csrf_token" value="' + _csrfToken + '">' +
                            '<button type="button" class="action-link action-delete" onclick="checkUsageThenDelete(\'image\', ' + img.id + ', this.closest(\'form\'))">🗑️ ' + _i18n.delete_action + '</button>' +
                        '</form>' +
                    '</div>' +
                '</div></div>';
        }).join('');

        var html = '<div class="media-grid">' + cards + '</div>';

        html += '<div class="pagination-footer">';
        if (data.pages > 1) {
            html += '<div class="pagination">';
            if (data.has_prev) {
                html += '<a href="#" onclick="window._liveSearch(' + data.prev_num + ');return false">' + _i18n.prev + '</a>';
            }
            var pageNums = [], i;
            for (i = 1; i <= data.pages; i++) {
                if (i === 1 || i === data.pages || (i >= data.page - 2 && i <= data.page + 2)) {
                    pageNums.push(i);
                } else if (pageNums[pageNums.length - 1] !== null) {
                    pageNums.push(null);
                }
            }
            pageNums.forEach(function(p) {
                if (p === null) { html += '<span>…</span>'; }
                else if (p === data.page) { html += '<span class="current">' + p + '</span>'; }
                else { html += '<a href="#" onclick="window._liveSearch(' + p + ');return false">' + p + '</a>'; }
            });
            if (data.has_next) {
                html += '<a href="#" onclick="window._liveSearch(' + data.next_num + ');return false">' + _i18n.next + '</a>';
            }
            html += '</div>';
        }
        html += '<div class="per-page-selector">' +
            '<span>' + _i18n.per_page_label + '</span>' +
            '<select onchange="var u=new URLSearchParams(location.search);u.set(\'per_page\',this.value);u.delete(\'page\');location.search=u">' +
            [20,50,100].map(function(pp) { return '<option value="' + pp + '"' + (pp === _perPage ? ' selected' : '') + '>' + pp + '</option>'; }).join('') +
            '</select>' +
            '<span>' + _i18n.per_page_suffix + '</span></div>';
        html += '</div>';  /* close pagination-footer */

        container.innerHTML = html;
    }

    window._liveSearch = function(page) {
        var q = input.value.trim();
        var params = new URLSearchParams();
        params.set('format', 'json');
        if (_perPage && _perPage !== 20) params.set('per_page', _perPage);
        if (q) params.set('q', q);
        if (page && page > 1) params.set('page', page);

        fetch(_baseUrl + '?' + params.toString())
            .then(function(r) { return r.json(); })
            .then(function(data) {
                renderContent(data);
                var urlParams = new URLSearchParams(window.location.search);
                if (q) { urlParams.set('q', q); } else { urlParams.delete('q'); }
                if (page && page > 1) { urlParams.set('page', page); } else { urlParams.delete('page'); }
                urlParams.delete('format');
                history.replaceState(null, '', window.location.pathname +
                    (urlParams.toString() ? '?' + urlParams.toString() : ''));
            })
            .catch(function(err) { console.error('Search error:', err); });
    };

    input.addEventListener('input', function() {
        clearTimeout(_debounceTimer);
        _debounceTimer = setTimeout(function() { window._liveSearch(1); }, 300);
    });
})();
</script>
{% endblock %}
