{% extends "base.html" %}
{% from "components/cards.html" import info_card %}
{% from "components/ui.html" import page_header, breadcrumb_nav, button, filter_badge %}

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

{{ page_header(
    icon_class='fas fa-file-invoice',
    title_text='Invoices',
    subtitle_text='Create and manage invoices for your clients',
    breadcrumbs=breadcrumbs,
    actions_html=''
        + '<div class="flex gap-2">'
        +   '<a href="' + url_for("recurring_invoices.list_recurring_invoices") + '" class="btn bg-purple-600 text-white hover:bg-purple-700"><i class="fas fa-sync-alt mr-2"></i>Recurring Invoices</a>'
        +   '<a href="' + url_for("invoices.export_invoices_excel") + '" class="btn bg-green-600 text-white hover:bg-green-700"><i class="fas fa-file-excel mr-2"></i>Export to Excel</a>'
        +   '<a href="' + url_for("invoices.create_invoice") + '" class="btn btn-primary"><i class="fas fa-plus mr-2"></i>Create Invoice</a>'
        + '</div>'
) }}

<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
    {{ info_card("Total Invoiced", "%.2f"|format(summary.total_amount), "All time") }}
    {{ info_card("Total Paid", "%.2f"|format(summary.paid_amount), "All time") }}
    {{ info_card("Outstanding", "%.2f"|format(summary.outstanding_amount), "All time") }}
    {{ info_card("Overdue", "%.2f"|format(summary.overdue_amount), "All time") }}
</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 Invoices') }}</h2>
        <button type="button" class="btn btn-sm bg-background-light dark:bg-background-dark hover:bg-gray-100 dark:hover:bg-gray-700" 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-4 gap-4" id="invoicesFilterForm" data-filter-form>
        <div>
            <label for="status" class="form-label">Status</label>
            <div class="flex flex-wrap gap-2">
                <button type="button" onclick="filterByStatus('')" class="status-filter-btn px-3 py-1.5 rounded-lg text-sm transition-colors {% if not request.args.get('status') %}bg-primary text-white{% else %}bg-background-light dark:bg-background-dark text-text-light dark:text-text-dark hover:bg-gray-100 dark:hover:bg-gray-700{% endif %}" data-status="">
                    <i class="fas fa-list mr-1"></i>All
                </button>
                <button type="button" onclick="filterByStatus('draft')" class="status-filter-btn px-3 py-1.5 rounded-lg text-sm transition-colors {% if request.args.get('status') == 'draft' %}bg-slate-500 text-white{% else %}bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700{% endif %}" data-status="draft">
                    <i class="fas fa-file-alt mr-1"></i>Draft
                </button>
                <button type="button" onclick="filterByStatus('sent')" class="status-filter-btn px-3 py-1.5 rounded-lg text-sm transition-colors {% if request.args.get('status') == 'sent' %}bg-indigo-500 text-white{% else %}bg-indigo-100 dark:bg-indigo-900/30 text-indigo-700 dark:text-indigo-300 hover:bg-indigo-200 dark:hover:bg-indigo-800{% endif %}" data-status="sent">
                    <i class="fas fa-paper-plane mr-1"></i>Sent
                </button>
                <button type="button" onclick="filterByStatus('paid')" class="status-filter-btn px-3 py-1.5 rounded-lg text-sm transition-colors {% if request.args.get('status') == 'paid' %}bg-emerald-500 text-white{% else %}bg-emerald-100 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300 hover:bg-emerald-200 dark:hover:bg-emerald-800{% endif %}" data-status="paid">
                    <i class="fas fa-check-circle mr-1"></i>Paid
                </button>
                <button type="button" onclick="filterByStatus('overdue')" class="status-filter-btn px-3 py-1.5 rounded-lg text-sm transition-colors {% if request.args.get('status') == 'overdue' %}bg-red-500 text-white{% else %}bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300 hover:bg-red-200 dark:hover:bg-red-800{% endif %}" data-status="overdue">
                    <i class="fas fa-exclamation-triangle mr-1"></i>Overdue
                </button>
            </div>
            <input type="hidden" name="status" id="statusFilter" value="{{ request.args.get('status', '') }}">
        </div>
        <div>
            <label for="payment_status" class="form-label">Payment Status</label>
            <select name="payment_status" id="payment_status" class="form-input">
                <option value="">All</option>
                <option value="unpaid" {% if request.args.get('payment_status') == 'unpaid' %}selected{% endif %}>Unpaid</option>
                <option value="partially_paid" {% if request.args.get('payment_status') == 'partially_paid' %}selected{% endif %}>Partially Paid</option>
                <option value="fully_paid" {% if request.args.get('payment_status') == 'fully_paid' %}selected{% endif %}>Fully Paid</option>
                <option value="overpaid" {% if request.args.get('payment_status') == 'overpaid' %}selected{% endif %}>Overpaid</option>
            </select>
        </div>
        <div>
            <label for="invoices-filter-search" class="form-label">Search</label>
            <input type="text" name="search" id="invoices-filter-search" value="{{ request.args.get('search', '') }}" class="form-input" placeholder="{{ _('Invoice number or client') }}">
        </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="invoicesContainer">
    {% include 'invoices/_invoices_list.html' %}
</div>

<!-- Bulk Operations Forms (hidden) -->
{% if current_user.is_admin %}
<form id="confirmBulkDelete-form" method="POST" action="{{ url_for('invoices.bulk_delete_invoices') }}" class="hidden">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
</form>

<form id="bulkStatusForm" method="POST" action="{{ url_for('invoices.bulk_update_status') }}" class="hidden">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <input type="hidden" name="status" id="bulkStatusValue">
</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 Invoices') }}</h3>
                    <p class="text-sm text-text-muted-light dark:text-text-muted-dark">Are you sure you want to delete the selected invoices? This action cannot be undone.</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-lg shadow-xl max-w-md w-full mx-4">
        <div class="p-6">
            <h3 class="text-lg font-semibold mb-4">{{ _('Change Status for Selected Invoices') }}</h3>
            <label for="bulkStatusSelect" class="form-label">{{ _('Select Status') }}</label>
            <select id="bulkStatusSelect" class="form-input w-full mb-4" onchange="toggleInvoiceReferenceField()">
                <option value="">-- {{ _('Select Status') }} --</option>
                <option value="draft">{{ _('Draft') }}</option>
                <option value="sent">{{ _('Sent') }}</option>
                <option value="paid">{{ _('Paid') }}</option>
                <option value="overdue">{{ _('Overdue') }}</option>
            </select>
            <div id="invoiceReferenceField" class="hidden mb-4">
                <label for="bulkInvoiceReference" class="form-label">{{ _('Invoice Reference') }} <span class="text-text-muted-light dark:text-text-muted-dark text-xs">({{ _('Optional') }})</span></label>
                <input type="text" id="bulkInvoiceReference" class="form-input w-full" placeholder="{{ _('e.g., Payment confirmation number') }}">
            </div>
            <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>
{% endif %}

<!-- Delete Invoice Modal (Single) -->
<div id="deleteInvoiceModal" class="hidden fixed inset-0 z-50" role="dialog" aria-modal="true" aria-labelledby="deleteModalTitle">
  <div class="absolute inset-0 bg-black/50" onclick="hideDeleteModal()"></div>
  <div class="relative max-w-lg mx-auto mt-24 bg-card-light dark:bg-card-dark text-text-light dark:text-text-dark rounded-xl shadow-xl border border-border-light dark:border-border-dark">
    <div class="p-4 border-b border-border-light dark:border-border-dark flex items-center justify-between">
      <h5 id="deleteModalTitle" class="text-lg font-semibold flex items-center gap-2">
        <i class="fas fa-trash text-red-500"></i> {{ _('Delete Invoice') }}
      </h5>
      <button type="button" class="px-2 py-1 hover:bg-background-light dark:hover:bg-background-dark rounded text-2xl leading-none" aria-label="{{ _('Close') }}" onclick="hideDeleteModal()">&times;</button>
    </div>
    <div class="p-4">
      <div class="bg-yellow-50 dark:bg-yellow-900/30 text-yellow-900 dark:text-yellow-100 rounded-lg p-3 ring-1 ring-yellow-200/60 dark:ring-yellow-700/50 flex items-start gap-2">
        <i class="fas fa-exclamation-triangle mt-1"></i>
        <div>
          <strong>{{ _('Warning:') }}</strong> {{ _('This action cannot be undone.') }}
        </div>
      </div>
      <p class="mt-4">{{ _('Are you sure you want to delete invoice') }} <strong id="deleteInvoiceNumber"></strong>?</p>
      <p class="text-text-muted-light dark:text-text-muted-dark mt-2">
        <small>{{ _('All invoice items, extra goods, and payment records associated with this invoice will be permanently deleted.') }}</small>
      </p>
    </div>
    <div class="p-4 border-t border-border-light dark:border-border-dark flex items-center justify-between">
      <button type="button" class="btn btn-secondary" onclick="hideDeleteModal()">
        <i class="fas fa-times"></i> {{ _('Cancel') }}
      </button>
      <form method="POST" id="deleteInvoiceForm" class="inline">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        <button type="submit" class="btn btn-danger">
          <i class="fas fa-trash"></i> {{ _('Delete Invoice') }}
        </button>
      </form>
    </div>
  </div>
</div>

{% endblock %}

{% block scripts_extra %}
<style>
.filter-collapsed { display: none !important; }
.filter-toggle-transition { transition: all 0.3s ease-in-out; }
.status-filter-btn {
    border: 1px solid transparent;
}
.status-filter-btn.active {
    border-color: currentColor;
}
</style>
<script>
// Status filter function
function filterByStatus(status) {
    document.getElementById('statusFilter').value = status;
    document.querySelectorAll('.status-filter-btn').forEach(btn => {
        btn.classList.remove('active');
        if (btn.dataset.status === status) {
            btn.classList.add('active');
        }
    });
    // Trigger AJAX filter
    if (window.applyInvoiceFilters) {
        window.applyInvoiceFilters();
    }
}

function resetInvoiceActionsMenu(menu) {
    if (!menu) return;
    menu.classList.add('hidden');
    menu.style.position = '';
    menu.style.left = '';
    menu.style.top = '';
    menu.style.bottom = '';
    menu.style.right = '';
    menu.style.zIndex = '';
    delete menu.dataset.visible;
}

function closeInvoiceActionMenus() {
    document.querySelectorAll('.invoice-actions-dropdown').forEach(resetInvoiceActionsMenu);
}

// Toggle invoice actions dropdown
function toggleInvoiceActions(evt, invoiceId) {
    if (evt) {
        evt.preventDefault();
        evt.stopPropagation();
    }

    const menu = document.getElementById('invoiceActions' + invoiceId);
    if (!menu) return;

    const willOpen = menu.classList.contains('hidden');

    closeInvoiceActionMenus();

    if (!willOpen) {
        return;
    }

    const trigger = (evt && evt.currentTarget) || document.querySelector(`[data-invoice-actions-trigger="${invoiceId}"]`);
    if (!trigger) return;

    menu.classList.remove('hidden');
    menu.style.position = 'fixed';
    menu.style.zIndex = '1300';

    // Measure after making visible
    const rect = trigger.getBoundingClientRect();
    const menuWidth = menu.offsetWidth;
    const menuHeight = menu.offsetHeight;

    let left = rect.right - menuWidth;
    if (left < 16) {
        left = rect.left;
    }
    if (left + menuWidth > window.innerWidth - 16) {
        left = window.innerWidth - menuWidth - 16;
    }
    if (left < 16) {
        left = 16;
    }

    let top = rect.bottom + 8;
    if (top + menuHeight > window.innerHeight - 16) {
        top = rect.top - menuHeight - 8;
    }
    if (top < 16) {
        top = Math.max(16, rect.bottom + 8);
    }

    menu.style.left = `${left}px`;
    menu.style.top = `${top}px`;
    menu.dataset.visible = 'true';
}

// Close dropdowns when clicking outside
document.addEventListener('click', function(e) {
    if (!e.target.closest('[onclick*="toggleInvoiceActions"]') && !e.target.closest('.invoice-actions-dropdown')) {
        closeInvoiceActionMenus();
    }
});

window.addEventListener('scroll', closeInvoiceActionMenus, true);

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('invoiceListFiltersVisible', '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('invoiceListFiltersVisible', '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('invoiceListFiltersVisible');
    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);
});

// Invoices Filter Handler - AJAX filtering
(function() {
    'use strict';
    
    let filterTimeout = null;
    let searchTimeout = null;
    
    function getFilterParams() {
        const form = document.getElementById('invoicesFilterForm');
        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 status from hidden input
        const statusInput = form.querySelector('#statusFilter');
        if (statusInput && statusInput.value) {
            params.status = statusInput.value;
        }
        
        // Get payment status
        const paymentStatusSelect = form.querySelector('[name="payment_status"]');
        if (paymentStatusSelect && paymentStatusSelect.value) {
            params.payment_status = paymentStatusSelect.value;
        }
        
        return params;
    }
    
    function buildFilterUrl() {
        const params = getFilterParams();
        const queryString = new URLSearchParams(params).toString();
        return `/invoices?${queryString}`;
    }
    
    function applyFilters() {
        const url = buildFilterUrl();
        const container = document.getElementById('invoicesListContainer');
        
        if (!container) {
            console.error('invoicesListContainer 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('#invoicesListContainer');
            
            if (newContainer) {
                container.innerHTML = newContainer.innerHTML;
            } else {
                const match = html.trim().match(/<div[^>]*id=["']invoicesListContainer["'][^>]*>([\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 invoices. Please refresh the page.', 'error');
            } else if (window.showToast) {
                window.showToast('Failed to filter invoices. Please refresh the page.', 'error');
            }
        })
        .finally(() => {
            container.style.opacity = '';
            container.style.pointerEvents = '';
        });
    }
    
    // Export function for status filter buttons
    window.applyInvoiceFilters = applyFilters;
    
    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('invoicesFilterForm');
        if (!form) {
            console.error('Invoices filter form not found');
            return;
        }
        
        // Auto-submit on dropdown changes
        form.querySelectorAll('select').forEach(select => {
            select.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();
                }
            });
        }
        
        // Prevent form submission (use AJAX instead)
        form.addEventListener('submit', (e) => {
            e.preventDefault();
            e.stopPropagation();
            if (searchTimeout) {
                clearTimeout(searchTimeout);
            }
            if (filterTimeout) {
                clearTimeout(filterTimeout);
            }
            applyFilters();
        });
    });
})();

{% if current_user.is_admin %}
// Bulk actions for invoices
function toggleAllInvoices() {
    const selectAll = document.getElementById('selectAll');
    const checkboxes = document.querySelectorAll('.invoice-checkbox');
    checkboxes.forEach(cb => cb.checked = selectAll.checked);
    updateBulkDeleteButton();
}

function updateBulkDeleteButton() {
    const checkboxes = document.querySelectorAll('.invoice-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;
}

function closeAllMenus() {
    document.querySelectorAll('.bulk-menu').forEach(m => m.classList.add('hidden'));
}

function openMenu(triggerEl, menuId) {
    const menu = document.getElementById(menuId);
    if (!menu) return;
    const willOpen = menu.classList.contains('hidden');
    closeAllMenus();
    if (!willOpen) return;
    
    // Position menu (dropup if not enough space below)
    menu.style.top = '';
    menu.style.bottom = '';
    const rect = triggerEl.getBoundingClientRect();
    const menuHeight = menu.offsetHeight || 200;
    const spaceBelow = window.innerHeight - rect.bottom;
    const spaceAbove = rect.top;
    if (spaceBelow < menuHeight + 16 && spaceAbove > menuHeight + 16) {
        menu.style.bottom = 'calc(100% + 8px)';
    } else {
        menu.style.top = 'calc(100% + 8px)';
    }
    menu.classList.remove('hidden');
}

// Click outside to close
document.addEventListener('click', function(e) {
    const insideTrigger = e.target.closest('#bulkActionsBtn');
    const insideMenu = e.target.closest('#invoicesBulkMenu');
    if (!insideTrigger && !insideMenu) {
        closeAllMenus();
    }
});

// Close on Escape
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') closeAllMenus();
});

function showBulkDeleteConfirm() {
    const count = document.querySelectorAll('.invoice-checkbox:checked').length;
    if (count === 0) return false;
    document.getElementById('confirmBulkDelete').classList.remove('hidden');
    return false;
}

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

function submitBulkDelete() {
    const form = document.getElementById('confirmBulkDelete-form');
    if (!form) return;
    
    form.querySelectorAll('input[name="invoice_ids[]"]').forEach(input => input.remove());
    
    const checkboxes = document.querySelectorAll('.invoice-checkbox:checked');
    if (checkboxes.length === 0) {
        alert('Please select at least one invoice to delete.');
        return;
    }
    
    checkboxes.forEach(cb => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'invoice_ids[]';
        input.value = cb.value;
        form.appendChild(input);
    });
    
    // Show loading state
    const btn = document.getElementById('bulkActionsBtn');
    let originalHTML = '';
    if (btn) {
        originalHTML = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i> Processing...';
        
        // Re-enable after timeout (safety fallback)
        setTimeout(() => {
            btn.innerHTML = originalHTML;
            btn.disabled = false;
        }, 10000);
    }
    
    // Submit the form - routes are already implemented
    form.submit();
}

function showBulkStatusDialog() {
    const dialog = document.getElementById('bulkStatusDialog');
    if (dialog) {
        dialog.classList.remove('hidden');
        // Reset form fields
        const statusSelect = document.getElementById('bulkStatusSelect');
        const referenceField = document.getElementById('invoiceReferenceField');
        const referenceInput = document.getElementById('bulkInvoiceReference');
        if (statusSelect) statusSelect.value = '';
        if (referenceField) referenceField.classList.add('hidden');
        if (referenceInput) referenceInput.value = '';
    }
    return false;
}

function closeBulkStatusDialog() {
    document.getElementById('bulkStatusDialog').classList.add('hidden');
    // Reset form fields
    const statusSelect = document.getElementById('bulkStatusSelect');
    const referenceField = document.getElementById('invoiceReferenceField');
    const referenceInput = document.getElementById('bulkInvoiceReference');
    if (statusSelect) statusSelect.value = '';
    if (referenceField) referenceField.classList.add('hidden');
    if (referenceInput) referenceInput.value = '';
}

function toggleInvoiceReferenceField() {
    const statusSelect = document.getElementById('bulkStatusSelect');
    const referenceField = document.getElementById('invoiceReferenceField');
    if (!statusSelect || !referenceField) return;
    
    if (statusSelect.value === 'paid') {
        referenceField.classList.remove('hidden');
    } else {
        referenceField.classList.add('hidden');
    }
}

function submitBulkStatus() {
    const statusSelect = document.getElementById('bulkStatusSelect');
    if (!statusSelect) return;
    
    const status = statusSelect.value;
    if (!status) {
        alert('Please select a status');
        return;
    }
    
    const form = document.getElementById('bulkStatusForm');
    if (!form) return;
    
    const statusValueInput = document.getElementById('bulkStatusValue');
    if (statusValueInput) {
        statusValueInput.value = status;
    }
    
    // Clear existing invoice_reference input if any
    const existingRefInput = form.querySelector('input[name="invoice_reference"]');
    if (existingRefInput) {
        existingRefInput.remove();
    }
    
    // Add invoice reference if provided and status is paid
    const referenceInput = document.getElementById('bulkInvoiceReference');
    if (status === 'paid' && referenceInput && referenceInput.value.trim()) {
        const refInput = document.createElement('input');
        refInput.type = 'hidden';
        refInput.name = 'invoice_reference';
        refInput.value = referenceInput.value.trim();
        form.appendChild(refInput);
    }
    
    // Clear existing hidden inputs
    form.querySelectorAll('input[name="invoice_ids[]"]').forEach(input => input.remove());
    
    // Add selected invoice IDs to form
    const checkboxes = document.querySelectorAll('.invoice-checkbox:checked');
    if (checkboxes.length === 0) {
        alert('Please select at least one invoice to update.');
        return;
    }
    
    // Show loading state
    const btn = document.getElementById('bulkActionsBtn');
    let originalHTML = '';
    if (btn) {
        originalHTML = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i> Processing...';
        
        // Re-enable after timeout (safety fallback)
        setTimeout(() => {
            btn.innerHTML = originalHTML;
            btn.disabled = false;
        }, 10000);
    }
    
    checkboxes.forEach(cb => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'invoice_ids[]';
        input.value = cb.value;
        form.appendChild(input);
    });
    
    // Submit the form - routes are already implemented
    form.submit();
}
{% endif %}

function showDeleteModal(invoiceId, invoiceNumber) {
  const numberEl = document.getElementById('deleteInvoiceNumber');
  const formEl = document.getElementById('deleteInvoiceForm');
  if (numberEl) numberEl.textContent = invoiceNumber || '';
  if (formEl) formEl.action = "{{ url_for('invoices.delete_invoice', invoice_id=0) }}".replace('0', invoiceId);
  const modal = document.getElementById('deleteInvoiceModal');
  if (modal) modal.classList.remove('hidden');
}

function hideDeleteModal() {
  const modal = document.getElementById('deleteInvoiceModal');
  if (modal) modal.classList.add('hidden');
}

// Export loading state
function showExportLoading(link) {
    const originalHTML = link.innerHTML;
    link.classList.add('pointer-events-none', 'opacity-60');
    link.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i> <span class="export-text">Exporting...</span>';
    
    // Reset after 5 seconds (fallback)
    setTimeout(() => {
        link.innerHTML = originalHTML;
        link.classList.remove('pointer-events-none', 'opacity-60');
    }, 5000);
}
</script>
{% endblock %}
