{% extends "base.html" %}

{% block title %}{{ _('Projects') }} - {{ app_name }}{% endblock %}

{% block content %}
<div class="container-fluid">
    {% from "_components.html" import page_header %}
    <div class="row">
        <div class="col-12">
            {% set actions %}
            {% if current_user.is_admin %}
            <a href="{{ url_for('projects.create_project') }}" class="btn-header btn-primary">
                <i class="fas fa-plus me-2"></i>{{ _('New Project') }}
            </a>
            {% endif %}
            {% endset %}
            {{ page_header('fas fa-project-diagram', _('Projects'), _('Manage all projects') ~ ' • ' ~ (projects|length) ~ ' ' ~ _('total'), actions) }}
        </div>
    </div>

    {# Summary cards similar to invoices #}
    {% set _active = 0 %}
    {% set _archived = 0 %}
    {% set _total_hours = 0 %}
    {% for p in projects %}
        {% if p.status == 'active' %}{% set _active = _active + 1 %}{% endif %}
        {% if p.status == 'archived' %}{% set _archived = _archived + 1 %}{% endif %}
        {% set _total_hours = _total_hours + (p.total_hours or 0) %}
    {% endfor %}
    <div class="row mb-4">
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="card border-0 shadow-sm h-100 summary-card">
                <div class="card-body p-3 d-flex align-items-center">
                    <div class="summary-icon bg-primary bg-opacity-10 text-primary"><i class="fas fa-list"></i></div>
                    <div class="ms-3">
                        <div class="summary-label">{{ _('Total Projects') }}</div>
                        <div class="summary-value">{{ projects|length }}</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="card border-0 shadow-sm h-100 summary-card">
                <div class="card-body p-3 d-flex align-items-center">
                    <div class="summary-icon bg-success bg-opacity-10 text-success"><i class="fas fa-check-circle"></i></div>
                    <div class="ms-3">
                        <div class="summary-label">{{ _('Active') }}</div>
                        <div class="summary-value">{{ _active }}</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="card border-0 shadow-sm h-100 summary-card">
                <div class="card-body p-3 d-flex align-items-center">
                    <div class="summary-icon bg-secondary bg-opacity-10 text-secondary"><i class="fas fa-archive"></i></div>
                    <div class="ms-3">
                        <div class="summary-label">{{ _('Archived') }}</div>
                        <div class="summary-value">{{ _archived }}</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="card border-0 shadow-sm h-100 summary-card">
                <div class="card-body p-3 d-flex align-items-center">
                    <div class="summary-icon bg-info bg-opacity-10 text-info"><i class="fas fa-hourglass-half"></i></div>
                    <div class="ms-3">
                        <div class="summary-label">{{ _('Total Hours') }}</div>
                        <div class="summary-value">{{ '%.1f'|format(_total_hours) }}h</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card mobile-card">
                <div class="card-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <h6 class="mb-0">
                            <i class="fas fa-filter me-2 text-primary"></i>{{ _('Filters') }}
                        </h6>
                        <button type="button" class="btn btn-sm" id="toggleFilters" onclick="toggleFilterVisibility()" title="{{ _('Toggle Filters') }}">
                            <i class="fas fa-chevron-up" id="filterToggleIcon"></i>
                        </button>
                    </div>
                </div>
                <div class="card-body" id="filterBody">
                    <form method="GET" class="row g-3 mobile-form">
                        <div class="col-12 col-md-4 mobile-form-group">
                            <label for="status" class="form-label">{{ _('Status') }}</label>
                            <select class="form-select touch-target" id="status" name="status">
                                <option value="">{{ _('All Statuses') }}</option>
                                <option value="active" {% if request.args.get('status') == 'active' %}selected{% endif %}>{{ _('Active') }}</option>
                                <option value="archived" {% if request.args.get('status') == 'archived' %}selected{% endif %}>{{ _('Archived') }}</option>
                            </select>
                        </div>
                        <div class="col-12 col-md-4 mobile-form-group">
                            <label for="client" class="form-label">{{ _('Client') }}</label>
                            <select class="form-select touch-target" id="client" name="client">
                                <option value="">{{ _('All Clients') }}</option>
                                {% for client in clients %}
                                <option value="{{ client }}" {% if request.args.get('client') == client %}selected{% endif %}>{{ client }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="col-12 col-md-4 mobile-form-group">
                            <label for="search" class="form-label">{{ _('Search') }}</label>
                            <input type="text" class="form-control touch-target" id="search" name="search" 
                                   value="{{ request.args.get('search', '') }}" placeholder="{{ _('Project name or description') }}">
                        </div>
                        <div class="col-12 d-flex flex-column flex-md-row gap-2 mobile-stack">
                            <button type="submit" class="btn btn-primary mobile-btn flex-fill fw-semibold" style="height: 44px; display: flex; align-items: center; justify-content: center;">
                                <i class="fas fa-search me-1"></i>{{ _('Filter') }}
                            </button>
                            <a href="{{ url_for('projects.list_projects') }}" class="btn btn-outline-secondary mobile-btn flex-fill fw-semibold" style="height: 44px; display: flex; align-items: center; justify-content: center;">
                                <i class="fas fa-times me-1"></i>{{ _('Clear') }}
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Projects List -->
    <div class="row">
        <div class="col-12">
            <div class="card shadow-sm border-0 mobile-card">
                <div class="card-header bg-white py-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <h6 class="m-0 font-weight-bold text-primary">
                            <i class="fas fa-list me-2"></i>{{ _('All Projects') }}
                        </h6>
                        <div class="d-flex gap-2">
                            <div class="input-group input-group-sm" style="width: 250px;">
                                <span class="input-group-text bg-light border-end-0">
                                    <i class="fas fa-search text-muted"></i>
                                </span>
                                <input type="text" class="form-control border-start-0" id="searchInput" 
                                       placeholder="{{ _('Search projects...') }}">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-body p-0">
                    {% if projects %}
                    <div class="table-responsive">
                        <table class="table table-hover mb-0" id="projectsTable">
                            <thead class="table-light">
                                <tr>
                                    <th class="border-0">{{ _('Project') }}</th>
                                    <th class="border-0">{{ _('Client') }}</th>
                                    <th class="border-0">{{ _('Status') }}</th>
                                    <th class="border-0">{{ _('Hours') }}</th>
                                    <th class="border-0">{{ _('Rate') }}</th>
                                    <th class="border-0 text-center">{{ _('Actions') }}</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for project in projects %}
                                <tr>
                                    <td data-label="Project">
                                        <div>
                                            <a href="{{ url_for('projects.view_project', project_id=project.id) }}" class="text-decoration-none">
                                                <strong>{{ project.name }}</strong>
                                            </a>
                                            {% if project.description %}
                                            <br><small class="text-muted">{{ project.description[:100] }}{% if project.description|length > 100 %}...{% endif %}</small>
                                            {% endif %}
                                        </div>
                                    </td>
                                    <td data-label="Client">
                                        <span class="project-badge">{{ project.client }}</span>
                                    </td>
                                    <td data-label="Status">
                                        {% if project.status == 'active' %}
                                        <span class="status-badge bg-success text-white">{{ _('Active') }}</span>
                                        {% else %}
                                        <span class="status-badge bg-secondary text-white">{{ _('Archived') }}</span>
                                        {% endif %}
                                    </td>
                                    <td data-label="Hours" class="align-middle" style="min-width:180px;">
                                        {% set total_h = (project.total_hours or 0) %}
                                        {% set billable_h = (project.billable_hours or 0) %}
                                        {% set pct = (billable_h / total_h * 100) if total_h > 0 else 0 %}
                                        <div class="d-flex justify-content-between align-items-center mb-1">
                                            <strong>{{ "%.1f"|format(total_h) }} h</strong>
                                            <small class="text-success">{{ "%.1f"|format(billable_h) }} h {{ _('billable') }}</small>
                                        </div>
                                        <div class="progress bg-light rounded-pill" style="height:6px;">
                                            <div class="progress-bar bg-success rounded-pill" role="progressbar" data-pct="{{ pct|round(0, 'floor') }}" aria-valuenow="{{ pct|round(0, 'floor') }}" aria-valuemin="0" aria-valuemax="100"></div>
                                        </div>
                                    </td>
                                    <td data-label="Rate" class="text-end">
                                        {% if project.hourly_rate %}
                                        <span class="badge bg-primary-subtle text-primary border border-primary-subtle rounded-pill">{{ currency }}{{ "%.2f"|format(project.hourly_rate) }}/h</span>
                                        {% else %}
                                        <span class="text-muted">-</span>
                                        {% endif %}
                                    </td>
                                    <td class="actions-cell" data-label="Actions">
                                        <div class="btn-group btn-group-sm" role="group">
                                            <a href="{{ url_for('projects.view_project', project_id=project.id) }}" 
                                               class="btn btn-sm btn-action btn-action--view touch-target" title="{{ _('View project') }}">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            {% if current_user.is_admin %}
                                            <a href="{{ url_for('projects.edit_project', project_id=project.id) }}" 
                                               class="btn btn-sm btn-action btn-action--edit touch-target" title="{{ _('Edit project') }}">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <button type="button" class="btn btn-sm btn-action btn-action--danger touch-target" title="{{ _('Delete project') }}"
                                                    onclick="showDeleteProjectModal('{{ project.id }}', '{{ project.name }}')">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                            {% endif %}
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    {% else %}
                    <div class="text-center py-5">
                        <div class="empty-state">
                            <i class="fas fa-project-diagram fa-3x text-muted mb-3"></i>
                            <h5 class="text-muted">{{ _('No projects found') }}</h5>
                            <p class="text-muted mb-4">{{ _('Create your first project to get started.') }}</p>
                            {% if current_user.is_admin %}
                            <a href="{{ url_for('projects.create_project') }}" class="btn btn-primary touch-target">
                                <i class="fas fa-plus me-2"></i> {{ _('Create Project') }}
                            </a>
                            {% endif %}
                        </div>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Delete Project Modal -->
<div class="modal fade" id="deleteProjectModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-trash me-2 text-danger"></i>{{ _('Delete Project') }}
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>{{ _('Warning:') }}</strong> {{ _('This action cannot be undone.') }}
                </div>
                <p>{{ _('Are you sure you want to delete the project') }} <strong id="deleteProjectName"></strong>?</p>
                <p class="text-muted mb-0">{{ _('All associated time entries will also be deleted.') }}</p>
            </div>
            <div class="modal-footer d-flex flex-column flex-md-row">
                <button type="button" class="btn btn-secondary mb-2 mb-md-0 me-md-2 touch-target" data-bs-dismiss="modal">
                    <i class="fas fa-times me-1"></i>{{ _('Cancel') }}
                </button>
                <form method="POST" id="deleteProjectForm" class="d-inline">
                    <button type="submit" class="btn btn-danger touch-target">
                        <i class="fas fa-trash me-2"></i>{{ _('Delete Project') }}
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<style>
/* Project-specific styles - Modern styling handled by global CSS */

/* Project Badge */
.project-badge {
    background: var(--surface-variant);
    color: var(--text-secondary);
    padding: 4px 8px;
    border-radius: var(--border-radius-sm);
    font-size: 12px;
    font-weight: var(--font-weight-medium);
    backdrop-filter: blur(8px);
    -webkit-backdrop-filter: blur(8px);
    transition: var(--transition);
}

.project-badge:hover {
    background: var(--surface-hover);
    transform: translateY(-1px);
}

/* Filter toggle styles */
.filter-collapsed {
    display: none !important;
}

.filter-toggle-transition {
    transition: var(--transition-slow);
}

/* Table sorting styles */
thead th[style*="cursor: pointer"]:hover {
    background-color: var(--surface-hover);
    color: var(--primary-color);
}

thead th.sorted-asc::after {
    content: " ▲";
    color: var(--primary-color);
    font-weight: bold;
}

thead th.sorted-desc::after {
    content: " ▼";
    color: var(--primary-color);
    font-weight: bold;
}

/* Dark theme adjustments */
[data-theme="dark"] .project-badge {
    background: var(--surface-variant);
    color: var(--text-secondary);
}

[data-theme="dark"] .project-badge:hover {
    background: var(--surface-hover);
}

[data-theme="dark"] thead th[style*="cursor: pointer"]:hover {
    background-color: var(--surface-hover);
}
</style>

<script type="application/json" id="i18n-json-projects-list">
{
    "search_projects": {{ _('Search projects:')|tojson }},
    "length_menu": {{ _('Show _MENU_ projects per page')|tojson }},
    "info": {{ _('Showing _START_ to _END_ of _TOTAL_ projects')|tojson }},
    "status_active": {{ _('Active')|tojson }},
    "status_archived": {{ _('Archived')|tojson }},
    "deleting": {{ _('Deleting...')|tojson }},
    "hide_filters": {{ _('Hide Filters')|tojson }},
    "show_filters": {{ _('Show Filters')|tojson }}
}
</script>
<script>
var i18nProjects = (function(){ try{ var el = document.getElementById('i18n-json-projects-list'); return el ? JSON.parse(el.textContent) : {}; } catch(e){ return {}; } })();
</script>
<script>
function toggleFilterVisibility() {
    const filterBody = document.getElementById('filterBody');
    const toggleIcon = document.getElementById('filterToggleIcon');
    const toggleButton = document.getElementById('toggleFilters');
    
    if (filterBody.classList.contains('filter-collapsed')) {
        // Show filters
        filterBody.classList.remove('filter-collapsed');
        toggleIcon.className = 'fas fa-chevron-up';
        toggleButton.title = i18nProjects.hide_filters || 'Hide Filters';
        localStorage.setItem('projectFiltersVisible', 'true');
    } else {
        // Hide filters
        filterBody.classList.add('filter-collapsed');
        toggleIcon.className = 'fas fa-chevron-down';
        toggleButton.title = i18nProjects.show_filters || 'Show Filters';
        localStorage.setItem('projectFiltersVisible', 'false');
    }
}

document.addEventListener('DOMContentLoaded', function() {
    // Initialize filter visibility based on localStorage
    const filterBody = document.getElementById('filterBody');
    const toggleIcon = document.getElementById('filterToggleIcon');
    const toggleButton = document.getElementById('toggleFilters');
    
    // Check if user previously hid filters
    const filtersVisible = localStorage.getItem('projectFiltersVisible');
    if (filtersVisible === 'false') {
        filterBody.classList.add('filter-collapsed');
        toggleIcon.className = 'fas fa-chevron-down';
        toggleButton.title = i18nProjects.show_filters || 'Show Filters';
    }
    
    // Add transition class after initial setup
    setTimeout(() => {
        filterBody.classList.add('filter-toggle-transition');
    }, 100);
    
    // Initialize vanilla JavaScript table functionality
    initializeProjectsTable();

    // Fill progress bars
    document.querySelectorAll('#projectsTable .progress-bar').forEach(el => {
        const pct = el.getAttribute('data-pct') || 0;
        el.style.width = pct + '%';
    });
});

// Vanilla JavaScript table functionality
function initializeProjectsTable() {
    const table = document.getElementById('projectsTable');
    const searchInput = document.getElementById('searchInput');
    
    if (!table) return;
    
    // Store original rows for filtering
    const tbody = table.querySelector('tbody');
    const originalRows = Array.from(tbody.querySelectorAll('tr'));
    
    // Search functionality
    if (searchInput) {
        searchInput.addEventListener('keyup', function() {
            const searchTerm = this.value.toLowerCase();
            filterTable(searchTerm, 'all');
        });
    }
    
    // Table sorting functionality
    const headers = table.querySelectorAll('thead th');
    headers.forEach((header, index) => {
        // Skip the actions column (last column)
        if (index === headers.length - 1) return;
        
        header.style.cursor = 'pointer';
        header.addEventListener('click', () => sortTable(index));
    });
    
    function filterTable(searchTerm, statusFilter) {
        const rows = tbody.querySelectorAll('tr');
        
        rows.forEach(row => {
            const cells = row.querySelectorAll('td');
            let textMatch = false;
            let statusMatch = true;
            
            // Check text match in project name and description
            if (cells[0]) {
                const projectText = cells[0].textContent.toLowerCase();
                textMatch = searchTerm === '' || projectText.includes(searchTerm);
            }
            
            // Check status match
            if (statusFilter !== 'all' && cells[2]) {
                const statusText = cells[2].textContent.toLowerCase();
                const activeLabel = (i18nProjects.status_active || 'Active').toLowerCase();
                const archivedLabel = (i18nProjects.status_archived || 'Archived').toLowerCase();
                
                if (statusFilter === 'active') {
                    statusMatch = statusText.includes(activeLabel);
                } else if (statusFilter === 'archived') {
                    statusMatch = statusText.includes(archivedLabel);
                }
            }
            
            row.style.display = (textMatch && statusMatch) ? '' : 'none';
        });
    }
    
    function sortTable(columnIndex) {
        const rows = Array.from(tbody.querySelectorAll('tr'));
        const isAscending = !table.dataset.sortAsc || table.dataset.sortAsc === 'false';
        
        rows.sort((a, b) => {
            const aText = a.cells[columnIndex].textContent.trim();
            const bText = b.cells[columnIndex].textContent.trim();
            
            // Try to parse as numbers for numeric columns
            const aNum = parseFloat(aText.replace(/[^\d.-]/g, ''));
            const bNum = parseFloat(bText.replace(/[^\d.-]/g, ''));
            
            if (!isNaN(aNum) && !isNaN(bNum)) {
                return isAscending ? aNum - bNum : bNum - aNum;
            } else {
                return isAscending ? aText.localeCompare(bText) : bText.localeCompare(aText);
            }
        });
        
        // Clear and re-append sorted rows
        tbody.innerHTML = '';
        rows.forEach(row => tbody.appendChild(row));
        
        // Update sort indicator
        table.dataset.sortAsc = isAscending.toString();
        
        // Update header indicators
        headers.forEach(h => h.classList.remove('sorted-asc', 'sorted-desc'));
        headers[columnIndex].classList.add(isAscending ? 'sorted-asc' : 'sorted-desc');
    }
    
    // Store the filter function for external use
    window.filterProjectsTable = filterTable;
}

function filterByStatus(status) {
    const searchInput = document.getElementById('searchInput');
    const searchTerm = searchInput ? searchInput.value.toLowerCase() : '';
    
    if (window.filterProjectsTable) {
        window.filterProjectsTable(searchTerm, status);
    }
    
    document.querySelectorAll('.dropdown-item').forEach(i => i.classList.remove('active'));
    const active = document.querySelector(`[onclick="filterByStatus('${status}')"]`);
    if (active) active.classList.add('active');
}

// Function to show delete project modal
function showDeleteProjectModal(projectId, projectName) {
    document.getElementById('deleteProjectName').textContent = projectName;
    document.getElementById('deleteProjectForm').action = "{{ url_for('projects.delete_project', project_id=0) }}".replace('0', projectId);
    new bootstrap.Modal(document.getElementById('deleteProjectModal')).show();
}

// Add loading state to delete project form
document.addEventListener('DOMContentLoaded', function() {
    const deleteForm = document.getElementById('deleteProjectForm');
    if (deleteForm) {
        deleteForm.addEventListener('submit', function() {
            const submitBtn = this.querySelector('button[type="submit"]');
            submitBtn.innerHTML = '<div class="loading-spinner me-2"></div>' + (i18nProjects.deleting || 'Deleting...');
            submitBtn.disabled = true;
        });
    }
});
</script>
{% endblock %}
