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

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

{{ page_header(
    icon_class='fas fa-receipt',
    title_text='Expenses',
    subtitle_text='Track and manage business expenses',
    breadcrumbs=breadcrumbs,
    actions_html=''
        + '<div class="flex gap-2">'
        +   '<a href="' + url_for("expenses.create_expense") + '" class="btn btn-primary"><i class="fas fa-plus mr-2"></i>New Expense</a>'
        +   '<a href="' + url_for("mileage.create_mileage") + '" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors"><i class="fas fa-car mr-2"></i>New Mileage</a>'
        +   '<a href="' + url_for("per_diem.create_per_diem") + '" class="bg-emerald-600 text-white px-4 py-2 rounded-lg hover:bg-emerald-700 transition-colors"><i class="fas fa-money-bill-alt mr-2"></i>New Per Diem</a>'
        + '</div>'
) }}

<!-- Summary Stats -->
<div class="grid grid-cols-1 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 Expenses</p>
                <p class="text-2xl font-bold">{{ total_count }}</p>
            </div>
            <div class="text-primary text-3xl">
                <i class="fas fa-file-invoice-dollar"></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>
                <a href="{{ url_for('expenses.dashboard') }}" class="text-sm text-primary hover:underline">
                    View Dashboard <i class="fas fa-arrow-right ml-1"></i>
                </a>
            </div>
            <div class="text-blue-500 text-3xl">
                <i class="fas fa-chart-line"></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">
        <h2 class="text-lg font-semibold">{{ _('Filter Expenses') }}</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-4 gap-4" data-filter-form>
        <div>
            <label for="expenses-filter-search" class="form-label">Search</label>
            <input type="text" name="search" id="expenses-filter-search" value="{{ search or '' }}" 
                   placeholder="Title, vendor, notes..." 
                   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="category" class="form-label">Category</label>
            <select name="category" id="category" 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 Categories</option>
                {% for cat in categories %}
                <option value="{{ cat }}" {% if category == cat %}selected{% endif %}>{{ cat|title }}</option>
                {% endfor %}
            </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>
        
        {% if current_user.is_admin and users %}
        <div>
            <label for="user_id" class="form-label">User</label>
            <select name="user_id" id="user_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 Users</option>
                {% for user in users %}
                <option value="{{ user.id }}" {% if user_id == user.id %}selected{% endif %}>{{ user.username }}</option>
                {% endfor %}
            </select>
        </div>
        {% endif %}
        
        <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="form-input 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="form-input user-date-input">
        </div>
        
        <div>
            <label for="billable" class="form-label">Billable</label>
            <select name="billable" id="billable" 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</option>
                <option value="true" {% if billable == 'true' %}selected{% endif %}>Billable Only</option>
                <option value="false" {% if billable == 'false' %}selected{% endif %}>Non-Billable</option>
            </select>
        </div>
        
        <div class="flex items-end gap-2 col-span-full">
            <button type="submit" class="btn btn-primary flex-1">
                <i class="fas fa-filter mr-2"></i>Filter
            </button>
            <a href="{{ url_for('expenses.list_expenses') }}" class="btn btn-secondary">
                <i class="fas fa-times"></i>
            </a>
            <a href="{{ url_for('expenses.export_expenses', **request.args) }}" class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors" title="{{ _('Export to CSV') }}">
                <i class="fas fa-download"></i>
            </a>
        </div>
    </form>
    </div>
</div>

{% if current_user.is_admin %}
<!-- Bulk Operations Forms (hidden) -->
<!-- Note: Bulk operations routes need to be implemented in the backend -->
<form id="confirmBulkDelete-form" method="POST" action="{{ url_for('expenses.bulk_delete_expenses') }}" class="hidden">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
</form>

<form id="bulkStatusForm" method="POST" action="{{ url_for('expenses.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-lg shadow-xl 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 Expenses') }}</h3>
                    <p class="text-sm text-text-muted-light dark:text-text-muted-dark">Are you sure you want to delete the selected expenses? 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 Expenses') }}</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>
                <option value="pending">Pending</option>
                <option value="approved">Approved</option>
                <option value="rejected">Rejected</option>
                <option value="reimbursed">Reimbursed</option>
            </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>
{% endif %}

<!-- Expenses 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">
            {{ expenses|length }} expense{{ 's' if expenses|length != 1 else '' }} found
        </h3>
        <div class="flex items-center gap-2">
            <a href="{{ url_for('expenses.export_expenses', **request.args) }}" 
               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 inline-flex items-center export-btn" 
               title="{{ _('Export to CSV') }}"
               onclick="showExportLoading(this); return true;">
                <i class="fas fa-download mr-1"></i> <span class="export-text">Export</span>
            </a>
            {% 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, 'expensesBulkMenu')" disabled>
                    <i class="fas fa-tasks mr-1"></i> Bulk Actions (<span id="selectedCount">0</span>)
                </button>
                <ul id="expensesBulkMenu" 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="toggleAllExpenses()">
                    </th>
                    {% endif %}
                    <th class="px-4 py-3" data-sortable>Date</th>
                    <th class="px-4 py-3" data-sortable>Title</th>
                    <th class="px-4 py-3" data-sortable>Category</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" data-sortable>User</th>
                    <th class="px-4 py-3" data-sortable>Project</th>
                    <th class="px-4 py-3">Actions</th>
                </tr>
            </thead>
            <tbody>
                {% if expenses %}
                    {% for expense in expenses %}
                    <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="expense-checkbox h-4 w-4 rounded border-gray-300 text-primary focus:ring-primary" value="{{ expense.id }}" onchange="updateBulkDeleteButton()">
                        </td>
                        {% endif %}
                        <td class="p-4 whitespace-nowrap" data-label="{{ _('Date') }}">{{ expense.expense_date|format_date }}</td>
                        <td class="p-4" data-label="{{ _('Title') }}">
                            <a href="{{ url_for('expenses.view_expense', expense_id=expense.id) }}" class="text-primary hover:underline font-medium">
                                {{ expense.title }}
                            </a>
                            {% if expense.vendor %}
                            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ expense.vendor }}</div>
                            {% endif %}
                        </td>
                        <td class="p-4" data-label="{{ _('Category') }}">
                            <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">
                                {{ expense.category|title }}
                            </span>
                        </td>
                        <td class="p-4 table-number font-medium" data-label="{{ _('Amount') }}">
                            {{ expense.total_amount|format_currency(expense.currency_code) }}
                            {% if expense.billable %}
                            <span class="ml-1 text-xs text-green-600 dark:text-green-400" title="Billable"><i class="fas fa-check-circle"></i></span>
                            {% endif %}
                        </td>
                        <td class="p-4" data-label="{{ _('Status') }}">
                            {% if expense.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 expense.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 expense.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 expense.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">{{ expense.status|title }}</span>
                            {% endif %}
                        </td>
                        <td class="p-4" data-label="{{ _('User') }}">{{ expense.user.username if expense.user else '—' }}</td>
                        <td class="p-4" data-label="{{ _('Project') }}">
                            {% if expense.project %}
                            <a href="{{ url_for('projects.view_project', project_id=expense.project.id) }}" class="text-primary hover:underline">{{ expense.project.name }}</a>
                            {% else %}
                            <span class="text-text-muted-light dark:text-text-muted-dark">—</span>
                            {% endif %}
                        </td>
                        <td class="p-4" data-label="{{ _('Actions') }}">
                            <a href="{{ url_for('expenses.view_expense', expense_id=expense.id) }}" class="text-primary hover:underline">View</a>
                        </td>
                    </tr>
                    {% endfor %}
                {% endif %}
            </tbody>
        </table>
        {% if not expenses %}
        {% from "components/ui.html" import empty_state %}
        {% set actions %}
            <a href="{{ url_for('expenses.create_expense') }}" class="btn btn-primary">
                <i class="fas fa-plus mr-2"></i>Create Your First Expense
            </a>
            <a href="{{ url_for('main.help') }}" class="btn btn-secondary">
                <i class="fas fa-question-circle mr-2"></i>Learn More
            </a>
        {% endset %}
        {% if request.args.get('search') or request.args.get('category') or request.args.get('status') %}
            {{ empty_state('fas fa-search', 'No Expenses Match Your Filters', 'Try adjusting your filters to see more results. You can clear filters or create a new expense that matches your criteria.', actions, type='no-results') }}
        {% else %}
            {{ empty_state('fas fa-receipt', 'No Expenses Yet', 'Track your business expenses to keep accurate financial records. Create your first expense entry to get started!', actions, type='no-data') }}
        {% endif %}
        {% endif %}
    </div>
    
    <!-- Pagination -->
    {% if pagination and pagination.pages > 1 %}
    <div class="bg-gray-50 dark:bg-gray-800 px-4 py-3 flex items-center justify-between border-t border-gray-200 dark:border-gray-700 sm:px-6">
        <div class="flex-1 flex justify-between sm:hidden">
            {% if pagination.has_prev %}
            <a href="{{ url_for('expenses.list_expenses', page=pagination.prev_num, **request.args) }}" class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                Previous
            </a>
            {% endif %}
            {% if pagination.has_next %}
            <a href="{{ url_for('expenses.list_expenses', page=pagination.next_num, **request.args) }}" class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                Next
            </a>
            {% endif %}
        </div>
        <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
            <div>
                <p class="text-sm text-gray-700 dark:text-gray-300">
                    Showing <span class="font-medium">{{ ((pagination.page - 1) * pagination.per_page) + 1 }}</span>
                    to <span class="font-medium">{{ min(pagination.page * pagination.per_page, pagination.total) }}</span>
                    of <span class="font-medium">{{ pagination.total }}</span> results
                </p>
            </div>
            <div>
                <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                    {% if pagination.has_prev %}
                    <a href="{{ url_for('expenses.list_expenses', page=pagination.prev_num, **request.args) }}" class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-sm font-medium text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-600">
                        <i class="fas fa-chevron-left"></i>
                    </a>
                    {% endif %}
                    
                    {% for page_num in pagination.iter_pages(left_edge=1, right_edge=1, left_current=1, right_current=2) %}
                        {% if page_num %}
                            {% if page_num == pagination.page %}
                            <span class="relative inline-flex items-center px-4 py-2 border border-primary bg-primary text-white text-sm font-medium">
                                {{ page_num }}
                            </span>
                            {% else %}
                            <a href="{{ url_for('expenses.list_expenses', page=page_num, **request.args) }}" class="relative inline-flex items-center px-4 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600">
                                {{ page_num }}
                            </a>
                            {% endif %}
                        {% else %}
                            <span class="relative inline-flex items-center px-4 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-sm font-medium text-gray-700 dark:text-gray-300">
                                ...
                            </span>
                        {% endif %}
                    {% endfor %}
                    
                    {% if pagination.has_next %}
                    <a href="{{ url_for('expenses.list_expenses', page=pagination.next_num, **request.args) }}" class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-sm font-medium text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-600">
                        <i class="fas fa-chevron-right"></i>
                    </a>
                    {% endif %}
                </nav>
            </div>
        </div>
    </div>
    {% endif %}
</div>

{% endblock %}

{% block scripts_extra %}
<style>
.filter-collapsed { display: none !important; }
.filter-toggle-transition { transition: all 0.3s ease-in-out; }
</style>
<script>
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('expenseListFiltersVisible', '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('expenseListFiltersVisible', '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('expenseListFiltersVisible');
    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 actions for expenses
function toggleAllExpenses() {
    const selectAll = document.getElementById('selectAll');
    const checkboxes = document.querySelectorAll('.expense-checkbox');
    checkboxes.forEach(cb => cb.checked = selectAll.checked);
    updateBulkDeleteButton();
}

function updateBulkDeleteButton() {
    const checkboxes = document.querySelectorAll('.expense-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('#expensesBulkMenu');
    if (!insideTrigger && !insideMenu) {
        closeAllMenus();
    }
});

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

function showBulkDeleteConfirm() {
    const count = document.querySelectorAll('.expense-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="expense_ids[]"]').forEach(input => input.remove());
    
    const checkboxes = document.querySelectorAll('.expense-checkbox:checked');
    if (checkboxes.length === 0) {
        alert('Please select at least one expense to delete.');
        return;
    }
    
    checkboxes.forEach(cb => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'expense_ids[]';
        input.value = cb.value;
        form.appendChild(input);
    });
    
    // Show loading state
    const btn = document.getElementById('bulkActionsBtn');
    if (btn) {
        const 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() {
    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;
    }
    
    // Clear existing hidden inputs
    form.querySelectorAll('input[name="expense_ids[]"]').forEach(input => input.remove());
    
    // Add selected expense IDs to form
    const checkboxes = document.querySelectorAll('.expense-checkbox:checked');
    if (checkboxes.length === 0) {
        alert('Please select at least one expense 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 = 'expense_ids[]';
        input.value = cb.value;
        form.appendChild(input);
    });
    
    // Submit the form - routes are already implemented
    form.submit();
}

// 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);
}
{% endif %}
</script>
{% endblock %}

