{% extends "base.html" %}
{% from "components/ui.html" import page_header %}

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

{{ page_header(
    icon_class='fas fa-car',
    title_text='Mileage Tracking',
    subtitle_text='Track and manage vehicle mileage expenses',
    breadcrumbs=breadcrumbs,
    actions_html='<div class="flex gap-2"><a href="' + url_for("mileage.gps_tracking_page") + '" class="bg-background-light dark:bg-background-dark text-text-light dark:text-text-dark px-4 py-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"><i class="fas fa-location-dot mr-2"></i>GPS Tracking</a><a href="' + url_for("mileage.create_mileage") + '" class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90 transition-colors"><i class="fas fa-plus mr-2"></i>New Mileage Entry</a></div>'
) }}

<!-- Summary Stats -->
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4 mb-6">
    <div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-sm text-gray-600 dark:text-gray-400">Total Distance</p>
                <p class="text-2xl font-bold">{{ '%.2f'|format(total_distance) }} km</p>
            </div>
            <div class="text-primary text-3xl">
                <i class="fas fa-route"></i>
            </div>
        </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">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-sm text-gray-600 dark:text-gray-400">Total Amount</p>
                <p class="text-2xl font-bold">{{ total_amount|format_currency(currency) }}</p>
            </div>
            <div class="text-green-500 text-3xl">
                <i class="fas {{ currency|currency_icon }}"></i>
            </div>
        </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">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-sm text-gray-600 dark:text-gray-400">Total Entries</p>
                <p class="text-2xl font-bold">{{ pagination.total if pagination else (mileage_entries|length) }}</p>
            </div>
            <div class="text-blue-500 text-3xl">
                <i class="fas fa-list"></i>
            </div>
        </div>
    </div>
</div>

<!-- Filter Form -->
<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 flex-wrap gap-2">
        <h2 class="text-lg font-semibold">{{ _('Filter Mileage') }}</h2>
        <div class="flex items-center gap-2 flex-wrap">
            <span class="text-xs text-gray-500 dark:text-gray-400 self-center">{{ _('Exports use current filters') }}</span>
            <a id="mileageExportCsvBtn" data-export-base="{{ url_for('mileage.export_mileage_csv') }}" href="{{ url_for('mileage.export_mileage_csv') }}" class="px-3 py-1.5 text-sm bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
                <i class="fas fa-file-csv mr-2"></i>{{ _('Export CSV') }}
            </a>
            <a id="mileageExportPdfBtn" data-export-base="{{ url_for('mileage.export_mileage_pdf') }}" href="{{ url_for('mileage.export_mileage_pdf') }}" class="px-3 py-1.5 text-sm bg-gray-800 text-white rounded-lg hover:bg-gray-900 transition-colors">
                <i class="fas fa-file-pdf mr-2"></i>{{ _('Export PDF') }}
            </a>
            <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>
    <div id="filterBody">
    <form method="GET" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4" data-filter-form>
        <div>
            <label for="mileage-filter-search" class="form-label">Search</label>
            <input type="text" name="search" id="mileage-filter-search" value="{{ search or '' }}" 
                   placeholder="{{ _('Purpose, location...') }}" 
                   class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-primary focus:border-primary dark:bg-gray-700">
        </div>
        
        <div>
            <label for="status" class="form-label">Status</label>
            <select name="status" id="status" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-primary focus:border-primary dark:bg-gray-700">
                <option value="">All Statuses</option>
                <option value="pending" {% if status == 'pending' %}selected{% endif %}>Pending</option>
                <option value="approved" {% if status == 'approved' %}selected{% endif %}>Approved</option>
                <option value="rejected" {% if status == 'rejected' %}selected{% endif %}>Rejected</option>
                <option value="reimbursed" {% if status == 'reimbursed' %}selected{% endif %}>Reimbursed</option>
            </select>
        </div>
        
        <div>
            <label for="project_id" class="form-label">Project</label>
            <select name="project_id" id="project_id" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-primary focus:border-primary dark:bg-gray-700">
                <option value="">All Projects</option>
                {% for project in projects %}
                <option value="{{ project.id }}" {% if project_id == project.id %}selected{% endif %}>{{ project.name }}</option>
                {% endfor %}
            </select>
        </div>
        
        <div>
            <label for="client_id" class="form-label">Client</label>
            {% set locked_client = get_locked_client() %}
            {% if locked_client %}
                <input type="hidden" name="client_id" id="client_id" value="{{ locked_client.id }}">
                <input type="text" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-100 dark:bg-gray-700 cursor-not-allowed opacity-75"
                       value="{{ locked_client.name }}" disabled readonly>
            {% elif only_one_client|default(false) and single_client %}
                <input type="hidden" name="client_id" id="client_id" value="{{ single_client.id }}">
                <input type="text" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-100 dark:bg-gray-700 cursor-not-allowed opacity-75"
                       value="{{ single_client.name }}" disabled readonly>
            {% else %}
                <select name="client_id" id="client_id" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-primary focus:border-primary dark:bg-gray-700">
                    <option value="">All Clients</option>
                    {% for client in clients %}
                    <option value="{{ client.id }}" {% if client_id == client.id %}selected{% endif %}>{{ client.name }}</option>
                    {% endfor %}
                </select>
            {% endif %}
        </div>
        
        <div>
            <label for="start_date" class="form-label">Start Date</label>
            <input type="date" name="start_date" id="start_date" value="{{ start_date or '' }}" 
                   class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-primary focus:border-primary dark:bg-gray-700 user-date-input">
        </div>
        
        <div>
            <label for="end_date" class="form-label">End Date</label>
            <input type="date" name="end_date" id="end_date" value="{{ end_date or '' }}" 
                   class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-primary focus:border-primary dark:bg-gray-700 user-date-input">
        </div>
        
        <div class="flex items-end gap-2 col-span-full md:col-span-2">
            <button type="submit" class="flex-1 bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90 transition-colors">
                <i class="fas fa-filter mr-2"></i>Filter
            </button>
            <a href="{{ url_for('mileage.list_mileage') }}" class="px-4 py-2 bg-gray-200 dark:bg-gray-700 rounded-lg hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors">
                <i class="fas fa-times"></i>
            </a>
        </div>
    </form>
    </div>
</div>

<!-- Mileage Table -->
<div class="bg-card-light dark:bg-card-dark rounded-xl border border-border-light dark:border-border-dark shadow-sm overflow-visible">
    <div class="flex justify-between items-center mb-4 p-6 pb-0">
        <h3 class="text-sm font-medium text-text-muted-light dark:text-text-muted-dark">
            {{ mileage_entries|length }} entr{{ 'ies' if mileage_entries|length != 1 else 'y' }} found
        </h3>
        <div class="flex items-center gap-2">
            {% if current_user.is_admin %}
            <div class="relative">
                <button type="button" id="bulkActionsBtn" class="px-3 py-1.5 text-sm border rounded-lg text-gray-700 dark:text-gray-200 border-gray-300 dark:border-gray-600 disabled:opacity-60" onclick="openMenu(this, 'mileageBulkMenu')" disabled>
                    <i class="fas fa-tasks mr-1"></i> Bulk Actions (<span id="selectedCount">0</span>)
                </button>
                <ul id="mileageBulkMenu" class="bulk-menu hidden absolute right-0 mt-2 w-56 bg-card-light dark:bg-card-dark border border-border-light dark:border-border-dark rounded-md shadow-lg z-50">
                    <li><a class="block px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-700" href="#" onclick="return showBulkStatusDialog()"><i class="fas fa-tasks mr-2"></i>Change Status</a></li>
                    <li><hr class="my-1 border-border-light dark:border-border-dark"></li>
                    <li><a class="block px-4 py-2 text-sm text-rose-600 hover:bg-gray-100 dark:hover:bg-gray-700" href="#" onclick="return showBulkDeleteConfirm()"><i class="fas fa-trash mr-2"></i>Delete</a></li>
                </ul>
            </div>
            {% endif %}
        </div>
    </div>
    <div class="overflow-x-auto p-6 pt-4">
        <table class="table table-zebra w-full text-left enhanced-table responsive-cards" data-table-enhanced data-page-size="25" data-sticky-header="true" data-column-visibility="true">
            <thead class="bg-background-light dark:bg-background-dark border-b border-border-light dark:border-border-dark">
                <tr>
                    {% if current_user.is_admin %}
                    <th class="px-4 py-3 w-12">
                        <input type="checkbox" id="selectAll" class="h-4 w-4 rounded border-gray-300 text-primary focus:ring-primary" onchange="toggleAllMileage()">
                    </th>
                    {% endif %}
                    <th class="px-4 py-3" data-sortable>Date</th>
                    <th class="px-4 py-3" data-sortable>Purpose</th>
                    <th class="px-4 py-3" data-sortable>Route</th>
                    <th class="px-4 py-3 table-number" data-sortable>Distance</th>
                    <th class="px-4 py-3 table-number" data-sortable>Amount</th>
                    <th class="px-4 py-3" data-sortable>Status</th>
                    <th class="px-4 py-3">Actions</th>
                </tr>
            </thead>
            <tbody>
                {% if mileage_entries %}
                    {% for entry in mileage_entries %}
                    <tr class="border-b border-border-light dark:border-border-dark hover:bg-gray-50 dark:hover:bg-gray-800">
                        {% if current_user.is_admin %}
                        <td class="p-4">
                            <input type="checkbox" class="mileage-entry-checkbox h-4 w-4 rounded border-gray-300 text-primary focus:ring-primary" value="{{ entry.id }}" onchange="updateBulkDeleteButton()">
                        </td>
                        {% endif %}
                        <td class="p-4 whitespace-nowrap" data-label="Date">{{ entry.date|format_date if entry.date else (entry.trip_date|format_date if entry.trip_date else '—') }}</td>
                        <td class="p-4" data-label="Purpose">
                            <a href="{{ url_for('mileage.view_mileage', mileage_id=entry.id) }}" class="text-primary hover:underline font-medium">
                                {{ entry.purpose }}
                            </a>
                            {% if entry.project %}
                            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ entry.project.name }}</div>
                            {% endif %}
                        </td>
                        <td class="p-4" data-label="Route">
                            <div class="flex flex-col">
                                <span class="text-gray-600 dark:text-gray-400">{{ entry.start_location }}</span>
                                <i class="fas fa-arrow-down text-xs text-gray-400 dark:text-gray-500 my-1"></i>
                                <span class="text-gray-600 dark:text-gray-400">{{ entry.end_location }}</span>
                            </div>
                        </td>
                        <td class="p-4 table-number font-medium" data-label="Distance">{{ '%.2f'|format(entry.distance_km) }} km</td>
                        <td class="p-4 table-number font-medium" data-label="Amount">{{ (entry.total_amount or entry.calculated_amount or 0)|format_currency(entry.currency_code) }}</td>
                        <td class="p-4" data-label="Status">
                            {% if entry.status == 'pending' %}
                            <span class="px-2 py-1 rounded-full text-xs font-medium whitespace-nowrap bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200">Pending</span>
                            {% elif entry.status == 'approved' %}
                            <span class="px-2 py-1 rounded-full text-xs font-medium whitespace-nowrap bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200">Approved</span>
                            {% elif entry.status == 'rejected' %}
                            <span class="px-2 py-1 rounded-full text-xs font-medium whitespace-nowrap bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200">Rejected</span>
                            {% elif entry.status == 'reimbursed' %}
                            <span class="px-2 py-1 rounded-full text-xs font-medium whitespace-nowrap bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200">Reimbursed</span>
                            {% else %}
                            <span class="px-2 py-1 rounded-full text-xs font-medium whitespace-nowrap bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200">{{ entry.status|title }}</span>
                            {% endif %}
                        </td>
                        <td class="p-4" data-label="Actions">
                            <a href="{{ url_for('mileage.view_mileage', mileage_id=entry.id) }}" class="text-primary hover:underline">View</a>
                        </td>
                    </tr>
                    {% endfor %}
                {% endif %}
            </tbody>
        </table>
        {% if not mileage_entries %}
        {% from "components/ui.html" import empty_state %}
        {% set actions %}
            <a href="{{ url_for('mileage.create_mileage') }}" class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90 transition-colors">
                <i class="fas fa-plus mr-2"></i>Create Your First Mileage Entry
            </a>
            <a href="{{ url_for('main.help') }}" class="bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 px-4 py-2 rounded-lg hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors">
                <i class="fas fa-question-circle mr-2"></i>Learn More
            </a>
        {% endset %}
        {% if request.args.get('search') or request.args.get('status') %}
            {{ empty_state('fas fa-search', 'No Mileage Entries Match Your Filters', 'Try adjusting your filters to see more results. You can clear filters or create a new mileage entry that matches your criteria.', actions, type='no-results') }}
        {% else %}
            {{ empty_state('fas fa-car', 'No Mileage Entries Yet', 'Track your business travel mileage for reimbursement. Create your first mileage entry to get started!', actions, type='no-data') }}
        {% endif %}
        {% endif %}
    </div>
</div>

{% endblock %}

{% block scripts_extra %}
<style>
.filter-collapsed { display: none !important; }
.filter-toggle-transition { transition: all 0.3s ease-in-out; }
</style>
<script>
(function() {
    function getMileageFilterParams() {
        const form = document.querySelector('[data-filter-form]');
        if (!form) return {};
        const params = {};
        ['search', 'status', 'project_id', 'client_id', 'start_date', 'end_date'].forEach(function(name) {
            const el = form.querySelector('[name="' + name + '"]');
            if (el && (el.tagName === 'SELECT' || el.type === 'hidden' || el.type === 'date' || el.type === 'text')) {
                const val = (el.value || '').trim();
                if (val) params[name] = val;
            }
        });
        return params;
    }
    function buildMileageExportUrl(base) {
        const params = getMileageFilterParams();
        const qs = new URLSearchParams(params).toString();
        return qs ? base + '?' + qs : base;
    }
    function updateMileageExportLinks() {
        const csvBtn = document.getElementById('mileageExportCsvBtn');
        const pdfBtn = document.getElementById('mileageExportPdfBtn');
        const csvBase = csvBtn ? csvBtn.getAttribute('data-export-base') : '';
        const pdfBase = pdfBtn ? pdfBtn.getAttribute('data-export-base') : '';
        if (csvBtn && csvBase) csvBtn.href = buildMileageExportUrl(csvBase);
        if (pdfBtn && pdfBase) pdfBtn.href = buildMileageExportUrl(pdfBase);
    }
    document.addEventListener('DOMContentLoaded', function() {
        updateMileageExportLinks();
        const form = document.querySelector('[data-filter-form]');
        if (form) {
            form.addEventListener('change', updateMileageExportLinks);
            form.addEventListener('input', updateMileageExportLinks);
        }
        const csvBtn = document.getElementById('mileageExportCsvBtn');
        const pdfBtn = document.getElementById('mileageExportPdfBtn');
        if (csvBtn) {
            csvBtn.addEventListener('click', function(e) {
                e.preventDefault();
                window.location.href = buildMileageExportUrl(this.getAttribute('data-export-base') || '');
            });
        }
        if (pdfBtn) {
            pdfBtn.addEventListener('click', function(e) {
                e.preventDefault();
                window.location.href = buildMileageExportUrl(this.getAttribute('data-export-base') || '');
            });
        }
    });
})();

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

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

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

// Bulk actions for mileage
function toggleAllMileage() {
    const selectAll = document.getElementById('selectAll');
    const checkboxes = document.querySelectorAll('.mileage-entry-checkbox');
    checkboxes.forEach(cb => cb.checked = selectAll.checked);
    updateBulkDeleteButton();
}

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

document.addEventListener('click', function(e) {
    const insideTrigger = e.target.closest('#bulkActionsBtn');
    const insideMenu = e.target.closest('#mileageBulkMenu');
    if (!insideTrigger && !insideMenu) {
        closeAllMenus();
    }
});

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

function showBulkDeleteConfirm() {
    const count = document.querySelectorAll('.mileage-entry-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="mileage_ids[]"]').forEach(input => input.remove());
    
    const checkboxes = document.querySelectorAll('.mileage-entry-checkbox:checked');
    if (checkboxes.length === 0) {
        alert('Please select at least one mileage entry to delete.');
        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 = 'mileage_ids[]';
        input.value = cb.value;
        form.appendChild(input);
    });
    
    // Submit the form - routes are already implemented
    form.submit();
}

function showBulkStatusDialog() {
    document.getElementById('bulkStatusDialog').classList.remove('hidden');
    return false;
}

function closeBulkStatusDialog() {
    document.getElementById('bulkStatusDialog').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;
    }
    
    form.querySelectorAll('input[name="mileage_ids[]"]').forEach(input => input.remove());
    
    const checkboxes = document.querySelectorAll('.mileage-entry-checkbox:checked');
    if (checkboxes.length === 0) {
        alert('Please select at least one mileage entry 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 = 'mileage_ids[]';
        input.value = cb.value;
        form.appendChild(input);
    });
    
    // Submit the form - routes are already implemented
    form.submit();
}
{% endif %}

</script>
{% endblock %}

