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

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

{{ page_header(
    icon_class='fas fa-folder',
    title_text='Projects',
    subtitle_text='Manage your projects here',
    breadcrumbs=breadcrumbs,
    actions_html='<a href="' + url_for("projects.create_project") + '" class="btn btn-primary"><i class="fas fa-plus"></i>Create Project</a>' if (current_user.is_admin or has_permission('create_projects')) else None
) }}

<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 Projects') }}</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-4 gap-4" id="projectsFilterForm" data-filter-form>
        <div>
            <label for="projects-filter-search" class="form-label">Search</label>
            <input type="text" name="search" id="projects-filter-search" value="{{ search or '' }}" class="form-input">
        </div>
        <div>
            <label for="status" class="form-label">Status</label>
            <select name="status" id="status" class="form-input">
                <option value="all" {% if not status or status == 'all' %}selected{% endif %}>All</option>
                <option value="active" {% if status == 'active' %}selected{% endif %}>Active</option>
                <option value="inactive" {% if status == 'inactive' %}selected{% endif %}>Inactive</option>
                <option value="archived" {% if status == 'archived' %}selected{% endif %}>Archived</option>
            </select>
        </div>
        <div>
            <label for="client" class="form-label">Client</label>
            {% set locked_client = get_locked_client() %}
            {% if locked_client %}
                <input type="hidden" name="client" id="client" value="{{ locked_client.name }}">
                <input type="text" class="form-input 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="client" value="{{ single_client.name }}">
                <input type="text" class="form-input bg-gray-100 dark:bg-gray-700 cursor-not-allowed opacity-75"
                       value="{{ single_client.name }}" disabled readonly>
            {% else %}
                <select name="client" id="client" class="form-input">
                    <option value="">All</option>
                    {% for client_name in clients %}
                    <option value="{{ client_name }}" {% if request.args.get('client') == client_name %}selected{% endif %}>{{ client_name }}</option>
                    {% endfor %}
                </select>
            {% endif %}
        </div>
        <div>
            <label for="favorites" class="form-label">Show</label>
            <select name="favorites" id="favorites" class="form-input">
                <option value="">All Projects</option>
                <option value="true" {% if favorites_only %}selected{% endif %}>⭐ Favorites Only</option>
            </select>
        </div>
        {% if custom_field_definitions %}
        {% for definition in custom_field_definitions %}
        <div>
            <label for="custom_field_{{ definition.field_key }}" class="form-label">{{ definition.label }}</label>
            <input type="text" name="custom_field_{{ definition.field_key }}" id="custom_field_{{ definition.field_key }}" 
                   value="{{ request.args.get('custom_field_' + definition.field_key, '') }}" 
                   class="form-input" 
                   placeholder="{{ definition.description or '' }}">
        </div>
        {% endfor %}
        {% endif %}
    </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="projectsContainer">
    <div id="projectsListContainer">
    <div class="flex justify-between items-center mb-4">
        <h3 class="text-sm font-medium">
            <span class="table-count-badge">{{ projects|length }} project{{ 's' if projects|length != 1 else '' }} found</span>
        </h3>
        <div class="flex items-center gap-2">
            <!-- View Toggle -->
            <div class="flex items-center gap-1 bg-background-light dark:bg-background-dark rounded-lg p-1">
                <button type="button" id="listViewBtn" onclick="setViewMode('list')" class="px-3 py-1.5 text-sm rounded transition-colors view-mode-btn active" data-view="list" title="{{ _('List View') }}">
                    <i class="fas fa-list"></i>
                </button>
                <button type="button" id="gridViewBtn" onclick="setViewMode('grid')" class="px-3 py-1.5 text-sm rounded transition-colors view-mode-btn" data-view="grid" title="{{ _('Grid View') }}">
                    <i class="fas fa-th"></i>
                </button>
            </div>
            <a href="{{ url_for('projects.export_projects', status=status, client=request.args.get('client', ''), search=request.args.get('search', ''), favorites=request.args.get('favorites', '')) }}" 
               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, 'projectsBulkMenu')" disabled>
                    <i class="fas fa-tasks mr-1"></i> Bulk Actions (<span id="selectedCount">0</span>)
                </button>
                <ul id="projectsBulkMenu" 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 text-text-light dark:text-text-dark hover:bg-gray-100 dark:hover:bg-gray-700" href="#" onclick="return showBulkStatusChange('active')"><i class="fas fa-check-circle mr-2 text-green-600"></i>Mark as Active</a></li>
                    <li><a class="block px-4 py-2 text-sm text-text-light dark:text-text-dark hover:bg-gray-100 dark:hover:bg-gray-700" href="#" onclick="return showBulkStatusChange('inactive')"><i class="fas fa-pause-circle mr-2 text-amber-500"></i>Mark as Inactive</a></li>
                    <li><a class="block px-4 py-2 text-sm text-text-light dark:text-text-dark hover:bg-gray-100 dark:hover:bg-gray-700" href="#" onclick="return showBulkArchiveDialog()"><i class="fas fa-archive mr-2 text-gray-600"></i>Archive</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>
    
    <!-- List View -->
    <div id="listView" class="view-container">
    <table class="table table-zebra w-full text-left responsive-cards" data-table-enhanced data-page-size="25" data-sticky-header="true" data-column-visibility="true">
        <thead class="border-b border-border-light dark:border-border-dark">
            <tr>
                {% if current_user.is_admin %}
                <th class="p-4 w-12">
                    <input type="checkbox" id="selectAll" class="h-4 w-4 rounded border-gray-300 text-primary focus:ring-primary" onchange="toggleAllProjects()">
                </th>
                {% endif %}
                <th class="p-4 w-10"></th>
                <th class="p-4" data-sortable>Name</th>
                <th class="p-4" data-sortable>Client</th>
                <th class="p-4" data-sortable>Status</th>
                <th class="p-4" data-sortable>Billable</th>
                <th class="p-4" data-sortable>Rate</th>
                <th class="p-4" data-sortable>Budget</th>
                <th class="p-4">Actions</th>
            </tr>
        </thead>
        <tbody>
            {% for project in projects %}
            <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="project-checkbox h-4 w-4 rounded border-gray-300 text-primary focus:ring-primary" value="{{ project.id }}" onchange="updateBulkDeleteButton()">
                </td>
                {% endif %}
                <td class="p-4 text-center">
                    {% set is_fav = favorite_project_ids and project.id in favorite_project_ids %}
                    <button type="button" 
                            class="favorite-btn text-xl hover:scale-110 transition-transform" 
                            data-project-id="{{ project.id }}"
                            data-is-favorited="{{ 'true' if is_fav else 'false' }}"
                            onclick="toggleFavorite({{ project.id }}, this)"
                            title="{{ 'Remove from favorites' if is_fav else 'Add to favorites' }}">
                        <i class="{{ 'fas fa-star text-yellow-500' if is_fav else 'far fa-star text-gray-400' }}"></i>
                    </button>
                </td>
                <td class="p-4 font-medium mobile-card-header" data-label="{{ _('Name') }}"><a href="{{ url_for('projects.view_project', project_id=project.id) }}" class="text-primary hover:underline">{{ project.name }}</a></td>
                <td class="p-4" data-label="{{ _('Client') }}">
                    {% if project.client_id %}
                        <a href="{{ url_for('clients.view_client', client_id=project.client_id) }}" class="text-primary hover:underline">{{ project.client }}</a>
                    {% else %}
                        {{ project.client }}
                    {% endif %}
                </td>
                <td class="p-4" data-label="{{ _('Status') }}">
                    {% if project.status == 'active' %}
                        <span class="px-2 py-1 rounded-full text-xs font-medium whitespace-nowrap bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300">Active</span>
                    {% elif project.status == 'inactive' %}
                        <span class="px-2 py-1 rounded-full text-xs font-medium whitespace-nowrap bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300">Inactive</span>
                    {% else %}
                        <span class="px-2 py-1 rounded-full text-xs font-medium whitespace-nowrap bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-200">Archived</span>
                    {% endif %}
                </td>
                <td class="p-4" data-label="{{ _('Billable') }}">
                    {% if project.billable %}
                        <span class="px-2 py-1 rounded-full text-xs font-medium whitespace-nowrap bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300">Billable</span>
                    {% else %}
                        <span class="px-2 py-1 rounded-full text-xs font-medium whitespace-nowrap bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300">Non-billable</span>
                    {% endif %}
                </td>
                <td class="p-4" data-label="{{ _('Rate') }}">
                    {% if project.hourly_rate %}
                        <span class="px-2 py-1 rounded-md text-xs font-medium bg-primary/10 text-primary">{{ '%.2f'|format(project.hourly_rate|float) }}/h</span>
                    {% else %}
                        <span class="text-text-muted-light dark:text-text-muted-dark">—</span>
                    {% endif %}
                </td>
                <td class="p-4" data-label="{{ _('Budget') }}">
                    {% if project.budget_amount %}
                        {% set consumed = (project.budget_consumed_amount or 0.0) %}
                        {% set total = project.budget_amount|float %}
                        {% set pct = (consumed / total * 100) if total > 0 else 0 %}
                        {% if pct >= 90 %}
                            {% set badge_classes = 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300' %}
                        {% elif pct >= 70 %}
                            {% set badge_classes = 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300' %}
                        {% else %}
                            {% set badge_classes = 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300' %}
                        {% endif %}
                        <span class="px-2 py-1 rounded-full text-xs font-medium whitespace-nowrap {{ badge_classes }}">{{ pct|round(0) }}%</span>
                    {% else %}
                        <span class="text-text-muted-light dark:text-text-muted-dark">—</span>
                    {% endif %}
                </td>
                <td class="p-4 mobile-actions" data-label="{{ _('Actions') }}">
                    <a href="{{ url_for('projects.view_project', project_id=project.id) }}" class="text-primary hover:underline">View</a>
                </td>
            </tr>
            {% else %}
            {% endfor %}
        </tbody>
    </table>
    </div>

    <!-- Grid View -->
    <div id="gridView" class="view-container hidden">
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {% for project in projects %}
            <div class="project-card bg-card-light dark:bg-card-dark rounded-lg shadow-md hover:shadow-lg transition-all duration-200 relative overflow-hidden group">
                <!-- Quick Actions on Hover -->
                <div class="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity z-10">
                    <div class="flex gap-1">
                        <a href="{{ url_for('projects.view_project', project_id=project.id) }}" 
                           class="p-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors" 
                           title="{{ _('View Project') }}">
                            <i class="fas fa-eye text-xs"></i>
                        </a>
                        {% if current_user.is_admin or has_permission('edit_projects') %}
                        <a href="{{ url_for('projects.edit_project', project_id=project.id) }}" 
                           class="p-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors" 
                           title="{{ _('Edit Project') }}">
                            <i class="fas fa-edit text-xs"></i>
                        </a>
                        {% endif %}
                        <button type="button" 
                                class="favorite-btn p-2 bg-yellow-500 text-white rounded-lg hover:bg-yellow-600 transition-colors" 
                                data-project-id="{{ project.id }}"
                                data-is-favorited="{{ 'true' if (favorite_project_ids and project.id in favorite_project_ids) else 'false' }}"
                                onclick="toggleFavorite({{ project.id }}, this)"
                                title="{{ 'Remove from favorites' if (favorite_project_ids and project.id in favorite_project_ids) else 'Add to favorites' }}">
                            <i class="{{ 'fas' if (favorite_project_ids and project.id in favorite_project_ids) else 'far' }} fa-star text-xs"></i>
                        </button>
                    </div>
                </div>
                
                <!-- Project Header -->
                <div class="p-6 pb-4">
                    <div class="flex items-start justify-between mb-2">
                        <h3 class="text-lg font-semibold text-text-light dark:text-text-dark flex-1 pr-2">
                            {{ project.name }}
                        </h3>
                        <!-- Status Badge -->
                        <span class="px-2 py-1 rounded-full text-xs font-medium whitespace-nowrap
                            {% if project.status == 'active' %}
                                bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300
                            {% elif project.status == 'inactive' %}
                                bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300
                            {% else %}
                                bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-200
                            {% endif %}">
                            {{ project.status|title }}
                        </span>
                    </div>
                    
                    {% if project.client %}
                    <p class="text-sm text-text-muted-light dark:text-text-muted-dark mb-3">
                        <i class="fas fa-building mr-1"></i>{{ project.client }}
                    </p>
                    {% endif %}
                    
                    {% if project.description %}
                    <div class="text-sm text-text-muted-light dark:text-text-muted-dark mb-4 line-clamp-2 prose prose-sm dark:prose-invert max-w-none">
                        {{ project.description | markdown | safe }}
                    </div>
                    {% endif %}
                </div>
                
                <!-- Progress Indicators -->
                <div class="px-6 pb-4 space-y-3">
                    {% if project.budget_amount %}
                        {% set consumed = (project.budget_consumed_amount or 0.0) %}
                        {% set total = project.budget_amount|float %}
                        {% set pct = (consumed / total * 100) if total > 0 else 0 %}
                        <div>
                            <div class="flex justify-between items-center mb-1">
                                <span class="text-xs font-medium text-text-muted-light dark:text-text-muted-dark">Budget</span>
                                <span class="text-xs font-semibold 
                                    {% if pct >= 90 %}text-red-600
                                    {% elif pct >= 70 %}text-amber-600
                                    {% else %}text-green-600{% endif %}">
                                    {{ pct|round(0) }}%
                                </span>
                            </div>
                            <div class="w-full h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
                                <div class="h-full rounded-full transition-all duration-300
                                    {% if pct >= 90 %}bg-red-500
                                    {% elif pct >= 70 %}bg-amber-500
                                    {% else %}bg-green-500{% endif %}" 
                                    style="width: {{ [pct,100]|min }}%">
                                </div>
                            </div>
                            <div class="text-xs text-text-muted-light dark:text-text-muted-dark mt-1">
                                {{ "%.2f"|format(consumed) }} / {{ "%.2f"|format(total) }}
                            </div>
                        </div>
                    {% endif %}
                    
                    <!-- Hours Progress -->
                    <div>
                        <div class="flex justify-between items-center mb-1">
                            <span class="text-xs font-medium text-text-muted-light dark:text-text-muted-dark">Hours</span>
                            <span class="text-xs font-semibold text-text-light dark:text-text-dark">
                                {{ "%.1f"|format(project.total_hours) }}h
                            </span>
                        </div>
                        {% if project.estimated_hours %}
                            {% set hours_pct = (project.total_hours / project.estimated_hours * 100) if project.estimated_hours > 0 else 0 %}
                            <div class="w-full h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
                                <div class="h-full bg-primary rounded-full transition-all duration-300" 
                                    style="width: {{ [hours_pct,100]|min }}%">
                                </div>
                            </div>
                            <div class="text-xs text-text-muted-light dark:text-text-muted-dark mt-1">
                                {{ "%.1f"|format(project.total_hours) }} / {{ "%.1f"|format(project.estimated_hours) }}h
                            </div>
                        {% endif %}
                    </div>
                </div>
                
                <!-- Project Footer -->
                <div class="px-6 py-4 border-t border-border-light dark:border-border-dark bg-background-light dark:bg-background-dark">
                    <div class="flex items-center justify-between">
                        <div class="flex items-center gap-3 text-sm">
                            {% if project.billable %}
                            <span class="px-2 py-1 rounded-full text-xs font-medium bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300">
                                <i class="fas fa-dollar-sign mr-1"></i>Billable
                            </span>
                            {% endif %}
                            {% if project.hourly_rate %}
                            <span class="text-xs text-text-muted-light dark:text-text-muted-dark">
                                {{ '%.2f'|format(project.hourly_rate|float) }}/h
                            </span>
                            {% endif %}
                        </div>
                        <a href="{{ url_for('projects.view_project', project_id=project.id) }}" 
                           class="text-primary hover:text-primary/80 text-sm font-medium">
                            View <i class="fas fa-arrow-right ml-1"></i>
                        </a>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
    </div>
    
    {% if not projects %}
    {% from "components/ui.html" import empty_state %}
    {% set actions %}
        {% if current_user.is_admin %}
        <a href="{{ url_for('projects.create_project') }}" 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 Project
        </a>
        {% endif %}
        <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 search or request.args.get('client') or request.args.get('status') != 'all' %}
        {{ empty_state('fas fa-search', 'No Projects Match Your Filters', 'Try adjusting your filters to see more results. You can clear filters or create a new project that matches your criteria.', actions, type='no-results') }}
    {% else %}
        {{ empty_state('fas fa-folder-open', 'No Projects Yet', 'Projects help you organize your work and track time efficiently. Create your first project 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; }
.view-container { display: block; }
.view-container.hidden { display: none; }
.view-mode-btn.active {
    background-color: rgb(59 130 246);
    color: white;
}
.view-mode-btn:not(.active) {
    background-color: transparent;
    color: inherit;
}
.view-mode-btn:hover:not(.active) {
    background-color: rgba(0, 0, 0, 0.05);
}
.dark .view-mode-btn:hover:not(.active) {
    background-color: rgba(255, 255, 255, 0.05);
}
.project-card {
    transition: transform 0.2s ease-in-out;
}
.project-card:hover {
    transform: translateY(-2px);
}
</style>
<script>
// View mode toggle
function setViewMode(mode) {
    const listView = document.getElementById('listView');
    const gridView = document.getElementById('gridView');
    const listBtn = document.getElementById('listViewBtn');
    const gridBtn = document.getElementById('gridViewBtn');
    
    if (mode === 'list') {
        listView.classList.remove('hidden');
        gridView.classList.add('hidden');
        listBtn.classList.add('active');
        gridBtn.classList.remove('active');
        localStorage.setItem('projectsViewMode', 'list');
    } else {
        listView.classList.add('hidden');
        gridView.classList.remove('hidden');
        listBtn.classList.remove('active');
        gridBtn.classList.add('active');
        localStorage.setItem('projectsViewMode', 'grid');
    }
}

// Load saved view mode
document.addEventListener('DOMContentLoaded', function() {
    const savedMode = localStorage.getItem('projectsViewMode') || 'list';
    setViewMode(savedMode);
});
</script>
<form id="bulkStatusChange-form" method="POST" action="{{ url_for('projects.bulk_status_change') }}" class="hidden">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <input type="hidden" name="new_status" id="bulkNewStatus" value="">
    <input type="hidden" name="archive_reason" id="bulkArchiveReason" value="">
</form>
<form id="confirmBulkDelete-form" method="POST" action="{{ url_for('projects.bulk_delete_projects') }}" class="hidden">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
</form>
<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('projectListFiltersVisible', '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('projectListFiltersVisible', '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('projectListFiltersVisible');
    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);
});

function toggleAllProjects(){
    const selectAll = document.getElementById('selectAll');
    document.querySelectorAll('.project-checkbox').forEach(cb => cb.checked = !!(selectAll && selectAll.checked));
    updateBulkDeleteButton();
}
function updateBulkDeleteButton(){
    const selected = document.querySelectorAll('.project-checkbox:checked').length;
    const btn = document.getElementById('bulkActionsBtn');
    const cnt = document.getElementById('selectedCount');
    if (cnt) cnt.textContent = selected;
    if (btn) btn.disabled = selected === 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('#projectsBulkMenu');
    if (!insideTrigger && !insideMenu){ closeAllMenus(); }
});
// Close on Escape
document.addEventListener('keydown', function(e){ if (e.key === 'Escape') closeAllMenus(); });

function showBulkDeleteConfirm(){
    const count = document.querySelectorAll('.project-checkbox:checked').length;
    if (count === 0) return false;
    const msg = `Are you sure you want to delete ${count} project(s)? Projects with time entries will be skipped.`;
    if (window.showConfirm){ window.showConfirm(msg, { title: 'Delete Projects', confirmText: 'Delete', variant: 'danger' }).then(function(ok){ if (ok) submitBulkDelete(); }); }
    return false;
}
function submitBulkDelete(){
    const form = document.getElementById('confirmBulkDelete-form');
    form.querySelectorAll('input[name="project_ids[]"]').forEach(n => n.remove());
    document.querySelectorAll('.project-checkbox:checked').forEach(cb => {
        const i = document.createElement('input'); i.type='hidden'; i.name='project_ids[]'; i.value=cb.value; form.appendChild(i);
    });
    form.submit();
}
function showBulkArchiveDialog(){
    const count = document.querySelectorAll('.project-checkbox:checked').length;
    if (count === 0) return false;
    
    // Create a custom modal for archive reason
    const modalHtml = `
        <div id="bulkArchiveModal" class="fixed inset-0 z-50 flex items-center justify-center">
            <div class="absolute inset-0 bg-black/50" onclick="closeBulkArchiveModal()"></div>
            <div class="relative bg-card-light dark:bg-card-dark rounded-lg shadow-lg max-w-md w-full mx-4 p-6">
                <h3 class="text-lg font-semibold mb-4">Archive ${count} Project${count !== 1 ? 's' : ''}?</h3>
                <div class="mb-4">
                    <label class="form-label">
                        Reason for Archiving <span class="text-text-muted-light dark:text-text-muted-dark">(Optional)</span>
                    </label>
                    <textarea id="bulkArchiveReasonInput" rows="3" class="form-input" placeholder="e.g., Projects completed, Contracts ended, etc."></textarea>
                </div>
                <div class="flex gap-2 mb-3">
                    <button type="button" onclick="setBulkArchiveReason('Projects completed successfully')" class="px-2 py-1 text-xs bg-gray-100 dark:bg-gray-700 rounded hover:bg-gray-200 dark:hover:bg-gray-600">Completed</button>
                    <button type="button" onclick="setBulkArchiveReason('Contracts ended')" class="px-2 py-1 text-xs bg-gray-100 dark:bg-gray-700 rounded hover:bg-gray-200 dark:hover:bg-gray-600">{{ _('Contract Ended') }}</button>
                    <button type="button" onclick="setBulkArchiveReason('Projects cancelled')" class="px-2 py-1 text-xs bg-gray-100 dark:bg-gray-700 rounded hover:bg-gray-200 dark:hover:bg-gray-600">Cancelled</button>
                </div>
                <div class="flex justify-end gap-3">
                    <button type="button" onclick="closeBulkArchiveModal()" class="px-4 py-2 rounded-lg bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 hover:bg-gray-300 dark:hover:bg-gray-600">Cancel</button>
                    <button type="button" onclick="confirmBulkArchive()" class="px-4 py-2 rounded-lg bg-amber-600 text-white hover:bg-amber-700">Archive</button>
                </div>
            </div>
        </div>
    `;
    
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    return false;
}

function closeBulkArchiveModal(){
    const modal = document.getElementById('bulkArchiveModal');
    if (modal) modal.remove();
}

function setBulkArchiveReason(reason){
    document.getElementById('bulkArchiveReasonInput').value = reason;
}

function confirmBulkArchive(){
    const reason = document.getElementById('bulkArchiveReasonInput').value.trim();
    document.getElementById('bulkNewStatus').value = 'archived';
    document.getElementById('bulkArchiveReason').value = reason;
    closeBulkArchiveModal();
    submitBulkStatusChange();
}

function showBulkStatusChange(newStatus){
    const count = document.querySelectorAll('.project-checkbox:checked').length;
    if (count === 0) return false;
    const label = {active:'Active', inactive:'Inactive', archived:'Archived'}[newStatus] || newStatus;
    const msg = `Are you sure you want to mark ${count} project(s) as ${label}?`;
    if (window.showConfirm){ window.showConfirm(msg, { title: 'Change Project Status', confirmText: 'Change' }).then(function(ok){ if (ok){ document.getElementById('bulkNewStatus').value=newStatus; document.getElementById('bulkArchiveReason').value=''; submitBulkStatusChange(); }}); }
    return false;
}
function submitBulkStatusChange(){
    const form = document.getElementById('bulkStatusChange-form');
    form.querySelectorAll('input[name="project_ids[]"]').forEach(n => n.remove());
    document.querySelectorAll('.project-checkbox:checked').forEach(cb => {
        const i = document.createElement('input'); i.type='hidden'; i.name='project_ids[]'; i.value=cb.value; form.appendChild(i);
    });
    
    // 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);
    }
    
    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);
}

// Favorite project functionality
function toggleFavorite(projectId, button) {
    // Font Awesome converts <i> to <svg>, so we need to look for either
    const icon = button.querySelector('i, svg');
    
    // Safety check
    if (!icon) {
        console.error('Star icon not found in button');
        console.log('Button HTML:', button.innerHTML);
        return;
    }
    
    // Check if favorited by looking at classes (works for both <i> and <svg>)
    const isFavorited = icon.classList.contains('fa-star') && 
                        (icon.classList.contains('fas') || icon.getAttribute('data-prefix') === 'fas');
    const action = isFavorited ? 'unfavorite' : 'favorite';
    
    // Disable button to prevent double clicks
    button.disabled = true;
    
    // Optimistic UI update - toggle classes
    if (isFavorited) {
        // Change to unfilled star
        icon.classList.remove('fas', 'text-yellow-500');
        icon.classList.add('far', 'text-gray-400');
        if (icon.tagName === 'svg') {
            icon.setAttribute('data-prefix', 'far');
        }
        button.title = 'Add to favorites';
    } else {
        // Change to filled star
        icon.classList.remove('far', 'text-gray-400');
        icon.classList.add('fas', 'text-yellow-500');
        if (icon.tagName === 'svg') {
            icon.setAttribute('data-prefix', 'fas');
        }
        button.title = 'Remove from favorites';
    }
    
    // Send AJAX request
    fetch(`/projects/${projectId}/${action}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRFToken': document.querySelector('meta[name="csrf-token"]')?.content || ''
        },
        credentials: 'same-origin'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Success - show toast notification
            const message = action === 'favorite' ? 'Project added to favorites' : 'Project removed from favorites';
            if (window.toastManager) {
                window.toastManager.success(message, 'Success', 3000);
            } else if (window.showToast) {
                window.showToast(message, 'success');
            }
        } else {
            // Revert UI on error
            if (isFavorited) {
                icon.classList.remove('far', 'text-gray-400');
                icon.classList.add('fas', 'text-yellow-500');
                if (icon.tagName === 'svg') {
                    icon.setAttribute('data-prefix', 'fas');
                }
                button.title = 'Remove from favorites';
            } else {
                icon.classList.remove('fas', 'text-yellow-500');
                icon.classList.add('far', 'text-gray-400');
                if (icon.tagName === 'svg') {
                    icon.setAttribute('data-prefix', 'far');
                }
                button.title = 'Add to favorites';
            }
            if (window.showAlert) {
                window.showAlert(data.message || 'Failed to update favorite status');
            } else {
                alert(data.message || 'Failed to update favorite status');
            }
        }
    })
    .catch(error => {
        console.error('Error toggling favorite:', error);
        // Revert UI on error
        if (isFavorited) {
            icon.classList.remove('far', 'text-gray-400');
            icon.classList.add('fas', 'text-yellow-500');
            if (icon.tagName === 'svg') {
                icon.setAttribute('data-prefix', 'fas');
            }
            button.title = 'Remove from favorites';
        } else {
            icon.classList.remove('fas', 'text-yellow-500');
            icon.classList.add('far', 'text-gray-400');
            if (icon.tagName === 'svg') {
                icon.setAttribute('data-prefix', 'far');
            }
            button.title = 'Add to favorites';
        }
        if (window.showAlert) {
            window.showAlert('Failed to update favorite status');
        } else {
            alert('Failed to update favorite status');
        }
    })
    .finally(() => {
        // Re-enable button
        button.disabled = false;
    });
}

// Projects Filter Handler - Simple AJAX filtering
(function() {
    'use strict';
    
    let filterTimeout = null;
    let searchTimeout = null;
    
    function getFilterParams() {
        const form = document.getElementById('projectsFilterForm');
        if (!form) return {};
        
        const params = {};
        
        // Get search input value directly (more reliable than FormData for text inputs)
        const searchInput = form.querySelector('input[name="search"]');
        if (searchInput) {
            const searchValue = searchInput.value.trim();
            if (searchValue) {
                params.search = searchValue;
            }
        }
        
        // Get other form fields from FormData
        const formData = new FormData(form);
        for (const [key, value] of formData.entries()) {
            // Skip search as we already handled it above
            if (key === 'search') {
                continue;
            }
            const trimmed = String(value || '').trim();
            if (trimmed && trimmed !== '') {
                params[key] = trimmed;
            }
        }
        
        // Always include status, default to "all" if not set
        if (!params.status) {
            params.status = 'all';
        }
        
        return params;
    }
    
    function buildFilterUrl() {
        const params = getFilterParams();
        const queryString = new URLSearchParams(params).toString();
        return `/projects?${queryString}`;
    }
    
    function applyFilters() {
        const url = buildFilterUrl();
        const container = document.getElementById('projectsListContainer');
        
        if (!container) {
            console.error('projectsListContainer 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 => {
            // The response should be the projectsListContainer div
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = html.trim();
            
            const newContainer = tempDiv.querySelector('#projectsListContainer');
            
            if (newContainer) {
                container.innerHTML = newContainer.innerHTML;
            } else {
                // Fallback: try to extract content using regex
                const match = html.trim().match(/<div[^>]*id=["']projectsListContainer["'][^>]*>([\s\S]*?)<\/div>\s*$/);
                if (match && match[1]) {
                    container.innerHTML = match[1];
                } else {
                    // Last resort: use the HTML as-is
                    container.innerHTML = html;
                }
            }
            
            // Re-initialize view mode
            if (window.setViewMode) {
                const savedMode = localStorage.getItem('projectsViewMode') || 'list';
                setViewMode(savedMode);
            }
            
            // Update filter chips after successful filter
            updateFilterChips();
        })
        .catch(error => {
            console.error('Filter error:', error);
            // Restore container state
            container.style.opacity = '';
            container.style.pointerEvents = '';
            
            // Show error message
            if (window.toastManager) {
                window.toastManager.show('Failed to filter projects. Please refresh the page.', 'error');
            } else if (window.showToast) {
                window.showToast('Failed to filter projects. Please refresh the page.', 'error');
            }
        })
        .finally(() => {
            container.style.opacity = '';
            container.style.pointerEvents = '';
        });
    }
    
    function debouncedApplyFilters(delay = 100) {
        if (filterTimeout) {
            clearTimeout(filterTimeout);
        }
        filterTimeout = setTimeout(applyFilters, delay);
    }
    
    function debouncedSearch(delay = 500) {
        if (searchTimeout) {
            clearTimeout(searchTimeout);
        }
        searchTimeout = setTimeout(applyFilters, delay);
    }
    
    function updateFilterChips() {
        const form = document.getElementById('projectsFilterForm');
        if (!form) return;
        
        const params = getFilterParams();
        const chipsContainer = document.getElementById('filterChipsContainer');
        
        // Remove old chips container if it exists
        if (chipsContainer) {
            chipsContainer.remove();
        }
        
        // Get active filters (exclude empty values and "all" status)
        const activeFilters = {};
        Object.entries(params).forEach(([key, value]) => {
            if (value && value !== 'all' && value !== '' && value !== 'false') {
                activeFilters[key] = value;
            }
        });
        
        // If no active filters, don't show chips
        if (Object.keys(activeFilters).length === 0) {
            return;
        }
        
        // Create chips container
        const container = document.createElement('div');
        container.id = 'filterChipsContainer';
        container.className = 'flex flex-wrap items-center gap-2 mb-4';
        
        // Add filter chips
        Object.entries(activeFilters).forEach(([key, value]) => {
            const chip = document.createElement('span');
            chip.className = 'inline-flex items-center px-3 py-1 rounded-full text-sm bg-primary/10 dark:bg-primary/20 text-primary border border-primary/20 dark:border-primary/30';
            
            const input = form.querySelector(`[name="${key}"]`);
            const label = input?.labels?.[0]?.textContent || key;
            
            chip.innerHTML = `
                <span class="font-medium">${label}:</span>
                <span class="ml-1">${value}</span>
                <button type="button" class="ml-2 hover:text-red-600 transition-colors" data-filter-key="${key}">
                    <i class="fas fa-times"></i>
                </button>
            `;
            
            // Add remove listener
            chip.querySelector('button').addEventListener('click', () => {
                removeFilter(key);
            });
            
            container.appendChild(chip);
        });
        
        // Add "Clear All" button
        const clearAllBtn = document.createElement('button');
        clearAllBtn.type = 'button';
        clearAllBtn.className = 'text-sm text-gray-600 dark:text-gray-400 hover:text-red-600 dark:hover:text-red-400 transition-colors';
        clearAllBtn.innerHTML = '<i class="fas fa-times-circle mr-1"></i> Clear all';
        clearAllBtn.addEventListener('click', clearAllFilters);
        container.appendChild(clearAllBtn);
        
        // Insert after filter form
        const filterBody = document.getElementById('filterBody');
        if (filterBody) {
            filterBody.appendChild(container);
        }
    }
    
    function removeFilter(key) {
        const form = document.getElementById('projectsFilterForm');
        if (!form) return;
        
        const input = form.querySelector(`[name="${key}"]`);
        if (input) {
            if (input.tagName === 'SELECT') {
                input.value = input.options[0].value; // First option (usually "All" or empty)
            } else {
                input.value = '';
            }
        }
        
        applyFilters();
    }
    
    function clearAllFilters() {
        const form = document.getElementById('projectsFilterForm');
        if (!form) return;
        
        // Reset all form fields
        form.reset();
        
        // Set status to "all"
        const statusSelect = form.querySelector('[name="status"]');
        if (statusSelect) {
            statusSelect.value = 'all';
        }
        
        // Clear text inputs
        form.querySelectorAll('input[type="text"]').forEach(input => {
            input.value = '';
        });
        
        // Apply filters immediately
        applyFilters();
    }
    
    // Initialize when DOM is ready
    document.addEventListener('DOMContentLoaded', function() {
        const form = document.getElementById('projectsFilterForm');
        if (!form) {
            console.error('Projects 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', (e) => {
                debouncedSearch(500);
            });
            
            // Submit on Enter
            searchInput.addEventListener('keydown', (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    if (searchTimeout) {
                        clearTimeout(searchTimeout);
                    }
                    applyFilters();
                }
            });
        } else {
            console.error('Search input not found in form');
        }
        
        // Prevent form submission (use AJAX instead)
        form.addEventListener('submit', (e) => {
            e.preventDefault();
            e.stopPropagation();
            if (searchTimeout) {
                clearTimeout(searchTimeout);
            }
            if (filterTimeout) {
                clearTimeout(filterTimeout);
            }
            applyFilters();
        });
        
        // Initial filter chips update
        setTimeout(updateFilterChips, 100);
        
        // Export clear function
        window.clearProjectsFilters = clearAllFilters;
    });
})();
</script>
{% endblock %}
