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

{% block content %}
<div class="page-header page-header--with-action">
    <div class="page-header__content">
        <h2>📁 {{ t('files.title') }}</h2>
        <p>{{ t('files.subtitle') }}</p>
    </div>
    <a href="{{ url_for('admin_files_upload') }}" class="btn-upload">{{ t('files.upload_file_btn') }}</a>
</div>

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

    <div id="files-content">
    {% if files.items %}
    <div class="media-grid">
        {% for file in files.items %}
        <div class="media-card">
            <div class="file-type-icon" data-type="{{ file.get_extension() }}">
                <span class="file-emoji">{{ file.get_icon() }}</span>
                <span class="file-ext-badge">{{ file.get_type_label() }}</span>
            </div>
            <div class="media-card-body">
                <div class="media-alt" title="{{ file.title }}">{{ file.title or file.original_filename }}</div>
                <div class="media-info">
                    {{ file.original_filename or file.filename }}
                    {% if file.file_size %}· {{ file.human_size() }}{% endif %}
                </div>
                <div class="media-url-row">
                    <input type="text" class="media-url-input" value="/{{ file.download_slug }}" readonly id="url-{{ file.id }}">
                    <button class="copy-btn" onclick="copyUrl('url-{{ file.id }}', this)" title="{{ t('files.copy_url') }}">📋 {{ t('files.copy_url') }}</button>
                </div>
                <div class="media-actions">
                    <a href="{{ url_for('admin_files_edit', file_id=file.id) }}" class="action-link action-edit">✏️ {{ t('table.edit') }}</a>
                    <form method="POST" action="{{ url_for('admin_files_delete', file_id=file.id) }}" class="d-inline">
                        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                        <button type="button" class="action-link action-delete" onclick="checkUsageThenDelete('file', {{ file.id }}, this.closest('form'))">🗑️ {{ t('table.delete') }}</button>
                    </form>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>

    {% else %}
    <div class="empty-state">
        {% if search_query %}
        <h3>🔍 {{ t('files.no_results') }}</h3>
        <p>{{ t('files.clear_search') }}</p>
        <a href="{{ url_for('admin_files_list') }}" class="btn btn-primary">{{ t('files.clear_search') }}</a>
        {% else %}
        <h3>📁 {{ t('files.no_files') }}</h3>
        <p>{{ t('files.no_files_text') }}</p>
        <a href="{{ url_for('admin_files_upload') }}" class="btn-upload">{{ t('files.upload_first') }}</a>
        {% endif %}
    </div>
    {% endif %}
    </div>
</div>

<div class="pagination-footer">
{% if files.items and files.pages > 1 %}
<div class="pagination">
    {% if files.has_prev %}
        <a href="{{ url_for('admin_files_list', page=files.prev_num, q=search_query, per_page=per_page) }}">{{ t('pagination.prev') }}</a>
    {% endif %}
    {% for p in files.iter_pages(left_edge=1, right_edge=1, left_current=2, right_current=2) %}
        {% if p %}
            {% if p == files.page %}
                <span class="current">{{ p }}</span>
            {% else %}
                <a href="{{ url_for('admin_files_list', page=p, q=search_query, per_page=per_page) }}">{{ p }}</a>
            {% endif %}
        {% else %}
            <span>…</span>
        {% endif %}
    {% endfor %}
    {% if files.has_next %}
        <a href="{{ url_for('admin_files_list', page=files.next_num, q=search_query, per_page=per_page) }}">{{ t('pagination.next') }}</a>
    {% endif %}
</div>
{% endif %}
{% if files.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) {
    var input = document.getElementById(inputId);
    input.select();
    document.execCommand('copy');
    var originalText = btn.textContent;
    btn.textContent = '✅ {{ t("files.copied") }}';
    setTimeout(function() { 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("files.delete_confirm") }}';
        
        if (data.count > 0) {
            msg = '{{ t("files.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("files.usage_confirm_delete") }}';
        }
        
        if (confirm(msg)) {
            formEl.submit();
        }
    } catch (err) {
        if (confirm('{{ t("files.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_files_list") }}';
    var _uploadUrl = '{{ url_for("admin_files_upload") }}';
    var _perPage = {{ per_page }};
    var _debounceTimer;

    var _i18n = {
        copy_url: '{{ t("files.copy_url") }}',
        copied: '{{ t("files.copied") }}',
        edit: '{{ t("table.edit") }}',
        delete_action: '{{ t("table.delete") }}',
        delete_confirm: '{{ t("files.delete_confirm") }}',
        no_results: '{{ t("files.no_results") }}',
        clear_search: '{{ t("files.clear_search") }}',
        no_files: '{{ t("files.no_files") }}',
        no_files_text: '{{ t("files.no_files_text") }}',
        upload_first: '{{ t("files.upload_first") }}',
        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('files-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>' +
                      '<p>' + escapeHtml(_i18n.clear_search) + '</p>' +
                      '<a href="' + _baseUrl + '" class="btn btn-primary">' + escapeHtml(_i18n.clear_search) + '</a>'
                    : '<h3>📁 ' + escapeHtml(_i18n.no_files) + '</h3>' +
                      '<p>' + escapeHtml(_i18n.no_files_text) + '</p>' +
                      '<a href="' + _uploadUrl + '" class="btn-upload">' + escapeHtml(_i18n.upload_first) + '</a>'
                ) + '</div>';
            return;
        }

        var cards = data.items.map(function(f) {
            var urlId = 'url-' + f.id;
            return '<div class="media-card">' +
                '<div class="file-type-icon" data-type="' + escapeHtml(f.extension) + '">' +
                    '<span class="file-emoji">' + f.icon + '</span>' +
                    '<span class="file-ext-badge">' + escapeHtml(f.type_label) + '</span>' +
                '</div>' +
                '<div class="media-card-body">' +
                    '<div class="media-alt" title="' + escapeHtml(f.title) + '">' + escapeHtml(f.title) + '</div>' +
                    '<div class="media-info">' + escapeHtml(f.original_filename) +
                        (f.size ? ' · ' + escapeHtml(f.size) : '') + '</div>' +
                    '<div class="media-url-row">' +
                        '<input type="text" class="media-url-input" value="/' + escapeHtml(f.download_slug) + '" 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/files/' + f.id + '/edit" class="action-link action-edit">✏️ ' + _i18n.edit + '</a>' +
                        '<form method="POST" action="/admin/files/' + f.id + '/delete" class="d-inline">' +
                            '<input type="hidden" name="csrf_token" value="' + _csrfToken + '">' +
                            '<button type="button" class="action-link action-delete" onclick="checkUsageThenDelete(\'file\',' + f.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 %}
