$(function () {

    /* ── Delete modal: inject video id & name ── */
    $('#deleteModal').on('show.bs.modal', function (e) {
        const btn = $(e.relatedTarget);
        const videoId = btn.data('video-id');
        const name = btn.data('video-name');
        const url = '/delete-video/' + videoId;   // Adapt to your route
        $('#deleteModalFileName').text(name);
        $('#deleteForm').attr('action', url);
    });

    /* ── Live search ── */
    $('#searchInput').on('input', function () {
        const query = $(this).val().toLowerCase().trim();
        let visible = 0;
        $('#historyTbody tr').each(function () {
            const name = $(this).data('name') || '';
            const match = name.includes(query);
            $(this).toggle(match);
            if (match) visible++;
        });
        updatePaginationInfo(visible);
    });

    /* ── Sort ── */
    $('#sortSelect').on('change', function () {
        const val = $(this).val();
        const tbody = $('#historyTbody');
        const rows = tbody.find('tr').get();

        rows.sort(function (a, b) {
            switch (val) {
                case 'date_desc': return $(b).data('date') - $(a).data('date');
                case 'date_asc': return $(a).data('date') - $(b).data('date');
                case 'name_asc': return ($(a).data('name') > $(b).data('name')) ? 1 : -1;
                case 'size_desc': return $(b).data('size') - $(a).data('size');
                default: return 0;
            }
        });

        tbody.empty();
        $.each(rows, function (i, row) { tbody.append(row); });
    });

    function updatePaginationInfo(count) {
        const total = $('#historyTbody tr').length;
        // Simple update — replace the number shown; adapt translation if needed
        $('#paginationInfo').text(count + ' / ' + total);
    }
});