{% extends "base.html" %}
{% from "components/ui.html" import page_header, stat_card, badge, confirm_dialog %}
{% from "components/multi_select.html" import multi_select %}

{% block content %}
{% set breadcrumbs = [
    {'text': 'Tasks'}
] %}

{{ page_header(
    icon_class='fas fa-tasks',
    title_text='Tasks',
    subtitle_text='Manage your tasks here',
    breadcrumbs=breadcrumbs,
    actions_html='<a href="' + url_for("tasks.create_task") + '" class="btn btn-primary btn-press shadow-md"><i class="fas fa-plus mr-2"></i>Create Task</a>'
) }}

<!-- Task Summary Cards -->
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6 stagger-animation">
    {% set todo_count = task_counts.get('todo', 0) if task_counts else (tasks|selectattr('status', 'equalto', 'todo')|list|length) %}
    {% set in_progress_count = task_counts.get('in_progress', 0) if task_counts else (tasks|selectattr('status', 'equalto', 'in_progress')|list|length) %}
    {% set review_count = task_counts.get('review', 0) if task_counts else (tasks|selectattr('status', 'equalto', 'review')|list|length) %}
    {% set done_count = task_counts.get('done', 0) if task_counts else (tasks|selectattr('status', 'equalto', 'done')|list|length) %}
    
    {{ stat_card('To Do', todo_count, 'fas fa-list', 'slate-500') }}
    {{ stat_card('In Progress', in_progress_count, 'fas fa-spinner', 'blue-500') }}
    {{ stat_card('In Review', review_count, 'fas fa-eye', 'amber-500') }}
    {{ stat_card('Completed', done_count, 'fas fa-check-circle', 'green-500') }}
</div>

<div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm mb-6">
    <div class="flex justify-between items-center mb-4">
        <h2 class="text-lg font-semibold">{{ _('Filter Tasks') }}</h2>
        <button type="button" class="px-3 py-1.5 text-sm bg-background-light dark:bg-background-dark rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors" id="toggleFilters" onclick="toggleFilterVisibility()" title="{{ _('Toggle Filters') }}">
            <i class="fas fa-chevron-up" id="filterToggleIcon"></i>
        </button>
    </div>
    <div id="filterBody">
    <form method="GET" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4" id="tasksFilterForm" data-filter-form>
        <div class="lg:col-span-1">
            <label for="tasks-filter-search" class="form-label">Search</label>
            <input type="text" name="search" id="tasks-filter-search" value="{{ search or '' }}" class="form-input">
        </div>
        <div class="lg:col-span-1">
            <label for="tags" class="form-label">{{ _('Tags') }}</label>
            <input type="text" name="tags" id="tags" value="{{ tags or '' }}" class="form-input" placeholder="{{ _('e.g. bug, frontend') }}">
        </div>
        <div>
            <label for="status" class="form-label">Status</label>
            <select name="status" id="status" class="form-input">
                <option value="">All</option>
                <option value="todo" {% if status == 'todo' %}selected{% endif %}>To Do</option>
                <option value="in_progress" {% if status == 'in_progress' %}selected{% endif %}>In Progress</option>
                <option value="review" {% if status == 'review' %}selected{% endif %}>Review</option>
                <option value="done" {% if status == 'done' %}selected{% endif %}>Done</option>
                <option value="cancelled" {% if status == 'cancelled' %}selected{% endif %}>Cancelled</option>
            </select>
        </div>
        <div>
            <label for="priority" class="form-label">Priority</label>
            <select name="priority" id="priority" class="form-input">
                <option value="">All</option>
                <option value="low" {% if priority == 'low' %}selected{% endif %}>Low</option>
                <option value="medium" {% if priority == 'medium' %}selected{% endif %}>Medium</option>
                <option value="high" {% if priority == 'high' %}selected{% endif %}>High</option>
                <option value="urgent" {% if priority == 'urgent' %}selected{% endif %}>Urgent</option>
            </select>
        </div>
        <div>
            {{ multi_select(
                field_name='project_ids',
                label='Project',
                items=projects,
                selected_ids=project_ids,
                item_id_attr='id',
                item_label_attr='name',
                placeholder='All Projects',
                show_search=True,
                form_id='tasksFilterForm'
            ) }}
        </div>
        <div>
            {{ multi_select(
                field_name='assigned_to_ids',
                label='Assigned To',
                items=users,
                selected_ids=assigned_to_ids,
                item_id_attr='id',
                item_label_attr='display_name',
                placeholder='All Users',
                show_search=True,
                form_id='tasksFilterForm'
            ) }}
        </div>
        <div class="flex items-center pt-5">
            <input type="checkbox" name="overdue" id="overdue" value="1" {% if overdue %}checked{% endif %} class="h-4 w-4 rounded border-gray-300 text-indigo-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
            <label for="overdue" class="ml-2 block text-sm text-gray-900 dark:text-gray-300">Overdue only</label>
        </div>
    </form>
    </div>
</div>

<div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm overflow-visible" id="tasksContainer">
    {% include 'tasks/_tasks_list.html' %}
</div>

<!-- Bulk Operations Forms (hidden) -->
<form id="confirmBulkDelete-form" method="POST" action="{{ url_for('tasks.bulk_delete_tasks') }}" class="hidden">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
</form>

<form id="bulkStatusForm" method="POST" action="{{ url_for('tasks.bulk_update_status') }}" class="hidden">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <input type="hidden" name="status" id="bulkStatusValue">
</form>

<form id="bulkAssignForm" method="POST" action="{{ url_for('tasks.bulk_assign_tasks') }}" class="hidden">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <input type="hidden" name="assigned_to" id="bulkAssignValue">
</form>

<form id="bulkProjectForm" method="POST" action="{{ url_for('tasks.bulk_move_project') }}" class="hidden">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <input type="hidden" name="project_id" id="bulkProjectValue">
</form>

<!-- Bulk Delete Confirmation Dialog -->
<div id="confirmBulkDelete" class="fixed inset-0 z-50 hidden overflow-y-auto" role="dialog" aria-modal="true">
    <div class="flex items-center justify-center min-h-screen px-4">
        <div class="fixed inset-0 transition-opacity bg-black/50 dark:bg-gray-900 dark:bg-opacity-75" onclick="closeBulkDeleteDialog()"></div>
        <div class="relative bg-card-light dark:bg-card-dark rounded-xl shadow-xl border border-border-light dark:border-border-dark max-w-md w-full p-6 zoom-in">
            <div class="flex items-start mb-4">
                <div class="flex-shrink-0">
                    <div class="w-12 h-12 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center">
                        <i class="fas fa-exclamation-triangle text-red-600 dark:text-red-400 text-xl"></i>
                    </div>
                </div>
                <div class="ml-4 flex-1">
                    <h3 class="text-lg font-semibold text-text-light dark:text-text-dark mb-2">{{ _('Delete Selected Tasks') }}</h3>
                    <p class="text-sm text-text-muted-light dark:text-text-muted-dark">Are you sure you want to delete the selected tasks? This action cannot be undone. Tasks with existing time entries will be skipped.</p>
                </div>
            </div>
            <div class="flex justify-end gap-3 mt-6">
                <button type="button" class="btn btn-secondary" onclick="closeBulkDeleteDialog()">
                    Cancel
                </button>
                <button type="button" class="btn btn-danger" onclick="submitBulkDelete()">
                    Delete
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Bulk Status Change Dialog -->
<div id="bulkStatusDialog" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black/50">
    <div class="bg-card-light dark:bg-card-dark rounded-xl shadow-xl border border-border-light dark:border-border-dark max-w-md w-full mx-4">
        <div class="p-6">
            <h3 class="text-lg font-semibold mb-4">{{ _('Change Status for Selected Tasks') }}</h3>
            <label for="bulkStatusSelect" class="form-label">Select Status</label>
            <select id="bulkStatusSelect" class="form-input w-full mb-4">
                <option value="">-- Select Status --</option>
                {% if kanban_columns %}
                    {% for column in kanban_columns %}
                    <option value="{{ column.status_key }}">{{ column.name }}</option>
                    {% endfor %}
                {% else %}
                    <option value="todo">To Do</option>
                    <option value="in_progress">In Progress</option>
                    <option value="review">Review</option>
                    <option value="done">Done</option>
                    <option value="cancelled">Cancelled</option>
                {% endif %}
            </select>
            <div class="flex justify-end gap-2">
                <button type="button" onclick="closeBulkStatusDialog()" class="btn btn-secondary">Cancel</button>
                <button type="button" onclick="submitBulkStatus()" class="btn btn-primary">{{ _('Update Status') }}</button>
            </div>
        </div>
    </div>
</div>

<!-- Bulk Assign Dialog -->
<div id="bulkAssignDialog" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black/50">
    <div class="bg-card-light dark:bg-card-dark rounded-xl shadow-xl border border-border-light dark:border-border-dark max-w-md w-full mx-4">
        <div class="p-6">
            <h3 class="text-lg font-semibold mb-4">{{ _('Assign Selected Tasks') }}</h3>
            <label for="bulkAssignSelect" class="form-label">Select User</label>
            <select id="bulkAssignSelect" class="form-input w-full mb-4">
                <option value="">-- Select User --</option>
                {% for user in users %}
                <option value="{{ user.id }}">{{ user.display_name }}</option>
                {% endfor %}
            </select>
            <div class="flex justify-end gap-2">
                <button type="button" onclick="closeBulkAssignDialog()" class="btn btn-secondary">Cancel</button>
                <button type="button" onclick="submitBulkAssign()" class="btn btn-primary">{{ _('Assign Tasks') }}</button>
            </div>
        </div>
    </div>
</div>

<!-- Bulk Move to Project Dialog -->
<div id="bulkProjectDialog" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black/50">
    <div class="bg-card-light dark:bg-card-dark rounded-xl shadow-xl border border-border-light dark:border-border-dark max-w-md w-full mx-4">
        <div class="p-6">
            <h3 class="text-lg font-semibold mb-4">{{ _('Move Selected Tasks to Project') }}</h3>
            <label for="bulkProjectSelect" class="form-label">{{ _('Select Project') }}</label>
            <select id="bulkProjectSelect" class="form-input w-full mb-4">
                <option value="">-- {{ _('Select Project') }} --</option>
                {% for project in projects %}
                <option value="{{ project.id }}">{{ project.name }}</option>
                {% endfor %}
            </select>
            <div class="flex justify-end gap-2">
                <button type="button" onclick="closeBulkProjectDialog()" class="btn btn-secondary">{{ _('Cancel') }}</button>
                <button type="button" onclick="submitBulkProject()" class="btn btn-primary">{{ _('Move Tasks') }}</button>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block scripts_extra %}
<style>
.filter-collapsed { display: none !important; }
.filter-toggle-transition { transition: all 0.3s ease-in-out; }
@media (max-width: 640px) {
    .stagger-animation [data-count-up] {
        font-size: 1.5rem;
    }
}
</style>
<script type="application/json" id="i18n-json-tasks-list">
{
  "confirm_delete": {{ _('Are you sure you want to delete the task "{name}"?')|tojson }},
  "confirm_delete_with_entries": {{ _('Cannot delete task "{name}" because it has time entries. Please delete the time entries first.')|tojson }}
}
</script>
<script>
var i18nTasksList = (function(){ try{ var el=document.getElementById('i18n-json-tasks-list'); return el?JSON.parse(el.textContent):{}; }catch(e){ return {}; } })();

// Bulk delete functions
function toggleAllTasks() {
    const selectAll = document.getElementById('selectAll');
    const checkboxes = document.querySelectorAll('.task-checkbox');
    checkboxes.forEach(cb => cb.checked = selectAll.checked);
    updateBulkDeleteButton();
}

function updateBulkDeleteButton() {
    const checkboxes = document.querySelectorAll('.task-checkbox:checked');
    const count = checkboxes.length;
    const btn = document.getElementById('bulkActionsBtn');
    const countSpan = document.getElementById('selectedCount');
    
    if (countSpan) countSpan.textContent = count;
    if (btn) btn.disabled = count === 0;
    
    // Update select all checkbox state
    const allCheckboxes = document.querySelectorAll('.task-checkbox');
    const selectAll = document.getElementById('selectAll');
    if (selectAll && allCheckboxes.length > 0) {
        selectAll.checked = count === allCheckboxes.length;
        selectAll.indeterminate = count > 0 && count < allCheckboxes.length;
    }
}

function showBulkDeleteConfirm() {
    document.getElementById('confirmBulkDelete').classList.remove('hidden');
    return false;
}

function closeBulkDeleteDialog() {
    document.getElementById('confirmBulkDelete').classList.add('hidden');
}

function submitBulkDelete() {
    const form = document.getElementById('confirmBulkDelete-form');
    
    // Clear existing hidden inputs
    form.querySelectorAll('input[name="task_ids[]"]').forEach(input => input.remove());
    
    // Add selected task IDs to form
    const checkboxes = document.querySelectorAll('.task-checkbox:checked');
    checkboxes.forEach(cb => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'task_ids[]';
        input.value = cb.value;
        form.appendChild(input);
    });
    
    // Submit the form
    form.submit();
}

// Bulk status change functions
function showBulkStatusDialog() {
    document.getElementById('bulkStatusDialog').classList.remove('hidden');
    return false;
}

function closeBulkStatusDialog() {
    document.getElementById('bulkStatusDialog').classList.add('hidden');
}

function submitBulkStatus() {
    const status = document.getElementById('bulkStatusSelect').value;
    if (!status) {
        alert('Please select a status');
        return;
    }
    
    const form = document.getElementById('bulkStatusForm');
    document.getElementById('bulkStatusValue').value = status;
    
    // Clear existing hidden inputs
    form.querySelectorAll('input[name="task_ids[]"]').forEach(input => input.remove());
    
    // Add selected task IDs to form
    const checkboxes = document.querySelectorAll('.task-checkbox:checked');
    checkboxes.forEach(cb => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'task_ids[]';
        input.value = cb.value;
        form.appendChild(input);
    });
    
    form.submit();
}

// Bulk assign functions
function showBulkAssignDialog() {
    document.getElementById('bulkAssignDialog').classList.remove('hidden');
    return false;
}

function closeBulkAssignDialog() {
    document.getElementById('bulkAssignDialog').classList.add('hidden');
}

function submitBulkAssign() {
    const assignedTo = document.getElementById('bulkAssignSelect').value;
    if (!assignedTo) {
        alert('Please select a user');
        return;
    }
    
    const form = document.getElementById('bulkAssignForm');
    document.getElementById('bulkAssignValue').value = assignedTo;
    
    // Clear existing hidden inputs
    form.querySelectorAll('input[name="task_ids[]"]').forEach(input => input.remove());
    
    // Add selected task IDs to form
    const checkboxes = document.querySelectorAll('.task-checkbox:checked');
    checkboxes.forEach(cb => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'task_ids[]';
        input.value = cb.value;
        form.appendChild(input);
    });
    
    form.submit();
}

// Bulk move to project functions
function showBulkProjectDialog() {
    document.getElementById('bulkProjectDialog').classList.remove('hidden');
    return false;
}

function closeBulkProjectDialog() {
    document.getElementById('bulkProjectDialog').classList.add('hidden');
}

function submitBulkProject() {
    const projectId = document.getElementById('bulkProjectSelect').value;
    if (!projectId) {
        alert('Please select a project');
        return;
    }
    
    const form = document.getElementById('bulkProjectForm');
    document.getElementById('bulkProjectValue').value = projectId;
    
    // Clear existing hidden inputs
    form.querySelectorAll('input[name="task_ids[]"]').forEach(input => input.remove());
    
    // Add selected task IDs to form
    const checkboxes = document.querySelectorAll('.task-checkbox:checked');
    checkboxes.forEach(cb => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'task_ids[]';
        input.value = cb.value;
        form.appendChild(input);
    });
    
    form.submit();
}

// Delete task confirmation (single)
function confirmDeleteTask(taskId, taskName, hasTimeEntries) {
    if (hasTimeEntries) {
        const msg = (i18nTasksList.confirm_delete_with_entries || 'Cannot delete task "{name}" because it has time entries. Please delete the time entries first.').replace('{name}', taskName);
        if (window.showAlert) {
            window.showAlert(msg);
        } else {
            alert(msg);
        }
        return;
    }
    
    const msg = (i18nTasksList.confirm_delete || 'Are you sure you want to delete the task "{name}"?').replace('{name}', taskName);
    window.showConfirm(msg, {
        title: '{{ _("Delete Task") }}',
        confirmText: '{{ _("Delete") }}',
        cancelText: '{{ _("Cancel") }}',
        variant: 'danger'
    }).then(function(ok){
        if (!ok) return;
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = `/tasks/${taskId}/delete`;
        
        // Add CSRF token
        const csrfInput = document.createElement('input');
        csrfInput.type = 'hidden';
        csrfInput.name = 'csrf_token';
        csrfInput.value = document.querySelector('meta[name="csrf-token"]').getAttribute('content') || '';
        form.appendChild(csrfInput);
        
        document.body.appendChild(form);
        form.submit();
    });
}

function toggleFilterVisibility() {
    const filterBody = document.getElementById('filterBody');
    const toggleIcon = document.getElementById('filterToggleIcon');
    const toggleButton = document.getElementById('toggleFilters');
    if (!filterBody || !toggleIcon || !toggleButton) return;
    
    const isCollapsed = filterBody.classList.contains('filter-collapsed');
    
    if (isCollapsed) {
        // Show filters
        filterBody.classList.remove('filter-collapsed');
        toggleIcon.classList.remove('fa-chevron-down');
        toggleIcon.classList.add('fa-chevron-up');
        toggleButton.title = '{{ _('Hide Filters') }}';
        localStorage.setItem('taskListFiltersVisible', 'true');
    } else {
        // Hide filters
        filterBody.classList.add('filter-collapsed');
        toggleIcon.classList.remove('fa-chevron-up');
        toggleIcon.classList.add('fa-chevron-down');
        toggleButton.title = '{{ _('Show Filters') }}';
        localStorage.setItem('taskListFiltersVisible', 'false');
    }
}

document.addEventListener('DOMContentLoaded', function() {
    const filterBody = document.getElementById('filterBody');
    const toggleIcon = document.getElementById('filterToggleIcon');
    const toggleButton = document.getElementById('toggleFilters');
    if (!filterBody || !toggleIcon || !toggleButton) return;
    
    const filtersVisible = localStorage.getItem('taskListFiltersVisible');
    if (filtersVisible === 'false') {
        filterBody.classList.add('filter-collapsed');
        toggleIcon.classList.remove('fa-chevron-up');
        toggleIcon.classList.add('fa-chevron-down');
        toggleButton.title = '{{ _('Show Filters') }}';
    } else {
        // Explicitly set the icon to chevron-up when filter is visible
        filterBody.classList.remove('filter-collapsed');
        toggleIcon.classList.remove('fa-chevron-down');
        toggleIcon.classList.add('fa-chevron-up');
        toggleButton.title = '{{ _('Hide Filters') }}';
    }
    setTimeout(() => { filterBody.classList.add('filter-toggle-transition'); }, 100);
});

// Tasks Filter Handler - AJAX filtering
(function() {
    'use strict';
    
    let filterTimeout = null;
    let searchTimeout = null;
    
    function getFilterParams() {
        const form = document.getElementById('tasksFilterForm');
        if (!form) return {};
        
        const params = {};
        
        // Get search input value directly
        const searchInput = form.querySelector('input[name="search"]');
        if (searchInput) {
            const searchValue = searchInput.value.trim();
            if (searchValue) {
                params.search = searchValue;
            }
        }
        
        // Get other form fields from FormData
        const formData = new FormData(form);
        for (const [key, value] of formData.entries()) {
            if (key === 'search') continue;
            const trimmed = String(value || '').trim();
            if (trimmed && trimmed !== '') {
                params[key] = trimmed;
            }
        }
        
        // Preserve pagination parameters from current URL
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.has('per_page')) {
            params.per_page = urlParams.get('per_page');
        }
        if (urlParams.has('page')) {
            params.page = urlParams.get('page');
        }
        
        return params;
    }
    
    function buildFilterUrl() {
        const params = getFilterParams();
        const queryString = new URLSearchParams(params).toString();
        return `/tasks?${queryString}`;
    }
    
    function applyFilters() {
        const url = buildFilterUrl();
        const container = document.getElementById('tasksListContainer');
        
        if (!container) {
            console.error('tasksListContainer not found');
            return;
        }
        
        // Show loading state
        container.style.opacity = '0.5';
        container.style.pointerEvents = 'none';
        
        // Update URL
        if (window.history && window.history.pushState) {
            window.history.pushState({}, '', url);
        }
        
        // Fetch filtered results
        fetch(url, {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'text/html'
            },
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            return response.text();
        })
        .then(html => {
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = html.trim();
            
            const newContainer = tempDiv.querySelector('#tasksListContainer');
            
            if (newContainer) {
                container.innerHTML = newContainer.innerHTML;
            } else {
                const match = html.trim().match(/<div[^>]*id=["']tasksListContainer["'][^>]*>([\s\S]*?)<\/div>\s*$/);
                if (match && match[1]) {
                    container.innerHTML = match[1];
                } else {
                    container.innerHTML = html;
                }
            }
        })
        .catch(error => {
            console.error('Filter error:', error);
            container.style.opacity = '';
            container.style.pointerEvents = '';
            if (window.toastManager) {
                window.toastManager.show('Failed to filter tasks. Please refresh the page.', 'error');
            } else if (window.showToast) {
                window.showToast('Failed to filter tasks. Please refresh the page.', 'error');
            }
        })
        .finally(() => {
            container.style.opacity = '';
            container.style.pointerEvents = '';
        });
    }
    
    function debouncedApplyFilters(delay = 100) {
        if (filterTimeout) {
            clearTimeout(filterTimeout);
        }
        filterTimeout = setTimeout(applyFilters, delay);
    }
    
    function debouncedSearch(delay = 500) {
        if (searchTimeout) {
            clearTimeout(searchTimeout);
        }
        searchTimeout = setTimeout(applyFilters, delay);
    }
    
    // Initialize when DOM is ready
    document.addEventListener('DOMContentLoaded', function() {
        const form = document.getElementById('tasksFilterForm');
        if (!form) {
            console.error('Tasks filter form not found');
            return;
        }
        
        // Auto-submit on dropdown changes
        form.querySelectorAll('select').forEach(select => {
            select.addEventListener('change', () => {
                debouncedApplyFilters(100);
            });
        });
        
        // Auto-submit on checkbox changes (including overdue filter)
        form.querySelectorAll('input[type="checkbox"]:not(.multi-select-checkbox):not(.multi-select-all)').forEach(checkbox => {
            checkbox.addEventListener('change', () => {
                debouncedApplyFilters(100);
            });
        });
        
        // Auto-submit on multi-select hidden input changes (triggered by Apply button)
        form.querySelectorAll('input[name="project_ids"], input[name="assigned_to_ids"]').forEach(input => {
            input.addEventListener('change', () => {
                debouncedApplyFilters(100);
            });
        });
        
        // Auto-submit on search input (debounced)
        const searchInput = form.querySelector('input[name="search"]');
        if (searchInput) {
            searchInput.addEventListener('input', () => {
                debouncedSearch(500);
            });
            
            // Submit on Enter
            searchInput.addEventListener('keydown', (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    if (searchTimeout) {
                        clearTimeout(searchTimeout);
                    }
                    applyFilters();
                }
            });
        }
        
        // Auto-submit on tags input (debounced)
        const tagsInput = form.querySelector('input[name="tags"], input#tags');
        if (tagsInput) {
            tagsInput.addEventListener('input', () => {
                debouncedSearch(500);
            });
            tagsInput.addEventListener('keydown', (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    if (searchTimeout) {
                        clearTimeout(searchTimeout);
                    }
                    applyFilters();
                }
            });
        }
        
        // Prevent form submission (use AJAX instead)
        form.addEventListener('submit', (e) => {
            e.preventDefault();
            e.stopPropagation();
            if (searchTimeout) {
                clearTimeout(searchTimeout);
            }
            if (filterTimeout) {
                clearTimeout(filterTimeout);
            }
            applyFilters();
        });
    });
})();
</script>
{% endblock %}