{% extends "base.html" %}

{% block title %}{{ task.name }} - Time Tracker{% endblock %}

{% block content %}
<div class="container mt-4">
    <!-- Breadcrumb -->
    <nav aria-label="breadcrumb" class="mb-4">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="{{ url_for('tasks.list_tasks') }}">{{ _('Tasks') }}</a></li>
            <li class="breadcrumb-item active">{{ task.name }}</li>
        </ol>
    </nav>

    <!-- Task Header -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card mobile-card">
                <div class="card-body py-4">
                    <div class="row align-items-start">
                        <div class="col-lg-8 col-md-7 mb-3 mb-md-0">
                            <div class="d-flex align-items-start mb-3">
                                <div class="bg-primary bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 48px; height: 48px;">
                                    <i class="fas fa-tasks text-primary fa-lg"></i>
                                </div>
                                <div class="flex-grow-1">
                                    <h1 class="h2 mb-2">{{ task.name }}</h1>
                                </div>
                            </div>
                            
                            <!-- Status and Priority -->
                            <div class="d-flex flex-wrap gap-2 mb-3">
                                <span class="status-badge status-{{ task.status }}">
                                    {{ task.status_display }}
                                </span>
                                <span class="priority-badge priority-{{ task.priority }}">
                                    {{ task.priority_display }}
                                </span>
                                {% if task.is_overdue %}
                                <span class="badge bg-danger">
                                    <i class="fas fa-exclamation-triangle me-1"></i>Overdue
                                </span>
                                {% endif %}
                            </div>
                        </div>
                        
                        <div class="col-lg-4 col-md-5">
                            <div class="d-flex flex-column gap-2">
                                {% if current_user.active_timer and current_user.active_timer.task_id == task.id %}
                                <form method="POST" action="{{ url_for('timer.stop_timer') }}" class="d-inline">
                                    <button type="submit" class="btn btn-danger">
                                        <i class="fas fa-stop me-2"></i>{{ _('Stop Timer') }}
                                    </button>
                                </form>
                                {% elif not current_user.active_timer %}
                                <a href="{{ url_for('timer.start_timer_for_project', project_id=task.project_id, task_id=task.id) }}" class="btn btn-success">
                                    <i class="fas fa-play me-2"></i>{{ _('Start Timer') }}
                                </a>
                                {% endif %}
                                
                                {% if current_user.is_admin or task.created_by == current_user.id %}
                                <a href="{{ url_for('tasks.edit_task', task_id=task.id) }}" class="btn btn-outline-primary">
                                    <i class="fas fa-edit me-2"></i>{{ _('Edit Task') }}
                                </a>
                                {% endif %}
                                
                                <a href="{{ url_for('tasks.list_tasks') }}" class="btn btn-outline-secondary">
                                    <i class="fas fa-arrow-left me-2"></i>{{ _('Back to Tasks') }}
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Task Details Grid -->
    <div class="row g-4">
        <!-- Main Task Information -->
        <div class="col-lg-8">
            <!-- Task Description -->
            {% if task.description %}
            <div class="card mobile-card mb-4">
                <div class="card-header d-flex align-items-center justify-content-between">
                    <h6 class="mb-0">
                        <i class="fas fa-align-left me-2 text-primary"></i>{{ _('Description') }}
                    </h6>
                </div>
                <div class="card-body">
                    <div class="task-description-content">
                        {{ task.description | markdown | safe }}
                    </div>
                </div>
            </div>
            {% endif %}

            <!-- Project Information -->
            <div class="card mobile-card mb-4">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-project-diagram me-2 text-primary"></i>Project Information
                    </h6>
                </div>
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="bg-primary bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 40px; height: 40px;">
                            <i class="fas fa-project-diagram text-primary"></i>
                        </div>
                        <div>
                            <h6 class="mb-1">{{ task.project.name }}</h6>
                            <p class="text-muted mb-0">{{ task.project.description or _('No description available') }}</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Time Tracking -->
            <div class="card mobile-card mb-4">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-clock me-2 text-warning"></i>{{ _('Time Tracking') }}
                    </h6>
                </div>
                <div class="card-body">
                    <div class="row g-3">
                        {% if task.estimated_hours %}
                        <div class="col-6 col-md-3">
                            <div class="text-center">
                                <div class="h4 text-warning mb-1">{{ task.estimated_hours }}</div>
                                <small class="text-muted">{{ _('Estimated Hours') }}</small>
                            </div>
                        </div>
                        {% endif %}
                        
                        {% if task.total_hours > 0 %}
                        <div class="col-6 col-md-3">
                            <div class="text-center">
                                <div class="h4 text-success mb-1">{{ task.total_hours }}</div>
                                <small class="text-muted">{{ _('Actual Hours') }}</small>
                            </div>
                        </div>
                        {% endif %}
                        
                        {% if task.estimated_hours and task.total_hours > 0 %}
                        <div class="col-6 col-md-3">
                            <div class="text-center">
                                <div class="h4 text-info mb-1">{{ task.progress_percentage }}%</div>
                                <small class="text-muted">{{ _('Progress') }}</small>
                            </div>
                        </div>
                        {% endif %}
                        
                        <div class="col-6 col-md-3">
                            <div class="text-center">
                                <div class="h4 text-primary mb-1">{{ task.time_entries.count() }}</div>
                                <small class="text-muted">{{ _('Time Entries') }}</small>
                            </div>
                        </div>
                    </div>
                    
                    {% if task.estimated_hours and task.total_hours > 0 %}
                    <div class="mt-3">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <small class="text-muted">{{ _('Progress Overview') }}</small>
                            <small class="text-muted fw-bold">{{ task.progress_percentage }}% {{ _('Complete') }}</small>
                        </div>
                        <div class="progress" style="height: 8px;">
                            <div class="progress-bar bg-primary" role="progressbar" 
                                 style="width: {{ task.progress_percentage }}%"
                                 aria-valuenow="{{ task.progress_percentage }}" 
                                 aria-valuemin="0" aria-valuemax="100">
                            </div>
                        </div>
                    </div>
                    {% endif %}
                </div>
            </div>

            <!-- Recent Time Entries -->
            {% if task.time_entries.count() > 0 %}
            <div class="card mobile-card mb-4">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-history me-2 text-info"></i>{{ _('Recent Time Entries') }}
                    </h6>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>{{ _('Date') }}</th>
                                    <th>{{ _('Duration') }}</th>
                                    <th>{{ _('Notes') }}</th>
                                    <th>{{ _('User') }}</th>
                                    <th class="text-end">{{ _('Actions') }}</th>
                                </tr>
                            </thead>
                            <tbody id="timeEntriesTableBody">
                                {% for entry in time_entries %}
                                <tr>
                                    <td>{{ entry.start_time.strftime('%b %d, %Y') }}</td>
                                    <td>
                                        {% if entry.duration_seconds %}
                                            {{ (entry.duration_seconds / 3600)|round(2) }}h
                                        {% else %}
                                            <span class="text-muted">-</span>
                                        {% endif %}
                                    </td>
                                    <td>{{ entry.notes[:50] if entry.notes else '-' }}</td>
                                    <td>{{ entry.user.display_name if entry.user else '-' }}</td>
                                    <td class="text-end pe-4 actions-cell">
                                        <div class="btn-group" role="group">
                                            <a href="{{ url_for('timer.edit_timer', timer_id=entry.id) }}"
                                               class="btn btn-sm btn-action btn-action--edit touch-target" title="{{ _('Edit entry') }}">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            {% if current_user.is_admin or entry.user_id == current_user.id %}
                                            <button type="button" class="btn btn-sm btn-action btn-action--danger touch-target" title="{{ _('Delete entry') }}"
                                                    onclick="showDeleteEntryModal('{{ entry.id }}', '{{ task.project.name }}', '{{ entry.duration_formatted }}')">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                            {% endif %}
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    {% if task.time_entries.count() > 10 %}
                    <div class="d-flex justify-content-between align-items-center mt-3">
                        <small class="text-muted" id="entriesInfo">{{ _('Showing') }} 10 {{ _('of') }} {{ task.time_entries.count() }} {{ _('entries') }}</small>
                        <div class="d-flex gap-2">
                            <button class="btn btn-sm btn-outline-secondary" id="showMoreBtn" onclick="showMoreEntries()">
                                <i class="fas fa-chevron-down me-2"></i>{{ _('Show more') }}
                            </button>
                            <button class="btn btn-sm btn-outline-secondary d-none" id="showLessBtn" onclick="showLessEntries()">
                                <i class="fas fa-chevron-up me-2"></i>{{ _('Show less') }}
                            </button>
                        </div>
                    </div>
                    {% endif %}
                </div>
            </div>
            {% endif %}
        </div>

        <!-- Sidebar Information -->
        <div class="col-lg-4">
            <!-- Task Details -->
            <div class="card mobile-card mb-4">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-info-circle me-2 text-secondary"></i>{{ _('Task Details') }}
                    </h6>
                </div>
                <div class="card-body">
                    <div class="task-detail-item mb-3">
                        <small class="text-muted d-block mb-1">{{ _('Status') }}</small>
                        <span class="status-badge status-{{ task.status }}">
                            {{ task.status_display }}
                        </span>
                    </div>
                    
                    <div class="task-detail-item mb-3">
                        <small class="text-muted d-block mb-1">{{ _('Priority') }}</small>
                        <span class="priority-badge priority-{{ task.priority }}">
                            {{ task.priority_display }}
                        </span>
                    </div>
                    
                    {% if task.assigned_user %}
                    <div class="task-detail-item mb-3">
                        <small class="text-muted d-block mb-1">{{ _('Assigned To') }}</small>
                        <div class="d-flex align-items-center">
                            <div class="bg-info bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 24px; height: 24px;">
                                <i class="fas fa-user text-info fa-xs"></i>
                            </div>
                            <span>{{ task.assigned_user.display_name }}</span>
                        </div>
                    </div>
                    {% endif %}
                    
                    <div class="task-detail-item mb-3">
                        <small class="text-muted d-block mb-1">{{ _('Created By') }}</small>
                        <div class="d-flex align-items-center">
                            <div class="bg-secondary bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 24px; height: 24px;">
                                <i class="fas fa-user-plus text-secondary fa-xs"></i>
                            </div>
                            <span>{{ task.creator.display_name }}</span>
                        </div>
                    </div>
                    
                    {% if task.due_date %}
                    <div class="task-detail-item mb-3">
                        <small class="text-muted d-block mb-1">{{ _('Due Date') }}</small>
                        <div class="d-flex align-items-center">
                            <div class="bg-{% if task.is_overdue %}danger{% else %}secondary{% endif %} bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 24px; height: 24px;">
                                <i class="fas fa-calendar text-{% if task.is_overdue %}danger{% else %}secondary{% endif %} fa-xs"></i>
                            </div>
                            <span class="{% if task.is_overdue %}text-danger fw-bold{% endif %}">
                                {{ task.due_date.strftime('%B %d, %Y') }}
                            </span>
                        </div>
                    </div>
                    {% endif %}
                    
                    {% if task.started_at %}
                    <div class="task-detail-item mb-3">
                        <small class="text-muted d-block mb-1">{{ _('Started') }}</small>
                        <div class="d-flex align-items-center">
                            <div class="bg-warning bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 24px; height: 24px;">
                                <i class="fas fa-play text-warning fa-xs"></i>
                            </div>
                            <span>{{ task.started_at.strftime('%B %d, %Y %H:%M') }}</span>
                        </div>
                    </div>
                    {% endif %}
                    
                    {% if task.completed_at %}
                    <div class="task-detail-item mb-3">
                        <small class="text-muted d-block mb-1">{{ _('Completed') }}</small>
                        <div class="d-flex align-items-center">
                            <div class="bg-success bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 24px; height: 24px;">
                                <i class="fas fa-check text-success fa-xs"></i>
                            </div>
                            <span>{{ task.completed_at.strftime('%B %d, %Y %H:%M') }}</span>
                        </div>
                    </div>
                    {% endif %}
                </div>
            </div>

            <!-- Quick Actions -->
            <div class="card mobile-card mb-4">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-bolt me-2 text-warning"></i>Quick Actions
                    </h6>
                </div>
                <div class="card-body">
                    <div class="quick-actions d-flex flex-wrap gap-2">
                        {% if task.status == 'todo' %}
                        <button class="btn btn-sm btn-action btn-action--success" onclick="openStatusModal('in_progress')" title="{{ _('Start Task') }}" data-bs-toggle="tooltip">
                            <i class="fas fa-play"></i>
                        </button>
                        {% elif task.status == 'in_progress' %}
                        <div class="btn-group" role="group">
                            <button class="btn btn-sm btn-action btn-action--view" onclick="openStatusModal('review')" title="{{ _('Mark for Review') }}" data-bs-toggle="tooltip">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button class="btn btn-sm btn-action btn-action--warning" onclick="openStatusModal('todo')" title="{{ _('Pause Task') }}" data-bs-toggle="tooltip">
                                <i class="fas fa-pause"></i>
                            </button>
                        </div>
                        {% elif task.status == 'review' %}
                        <div class="btn-group" role="group">
                            <button class="btn btn-sm btn-action btn-action--success" onclick="openStatusModal('done')" title="{{ _('Complete Task') }}" data-bs-toggle="tooltip">
                                <i class="fas fa-check"></i>
                            </button>
                            <button class="btn btn-sm btn-action btn-action--edit" onclick="openStatusModal('in_progress')" title="{{ _('Back to Progress') }}" data-bs-toggle="tooltip">
                                <i class="fas fa-undo"></i>
                            </button>
                        </div>
                        {% elif task.status == 'done' %}
                        <button class="btn btn-sm btn-action btn-action--warning" onclick="openStatusModal('todo')" title="{{ _('Reopen Task') }}" data-bs-toggle="tooltip">
                            <i class="fas fa-undo"></i>
                        </button>
                        {% endif %}
                        
                        {% if task.status != 'done' and task.status != 'cancelled' %}
                        <button class="btn btn-sm btn-action btn-action--danger" onclick="openStatusModal('cancelled')" title="{{ _('Cancel Task') }}" data-bs-toggle="tooltip">
                            <i class="fas fa-times"></i>
                        </button>
                        {% endif %}
                    </div>
                </div>
            </div>

            <!-- Task Timeline -->
            <div class="card mobile-card">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-history me-2 text-info"></i>{{ _('Task Timeline') }}
                    </h6>
                </div>
                <div class="card-body">
                    <div class="timeline">
                        <div class="timeline-item">
                            <div class="timeline-marker bg-primary"></div>
                            <div class="timeline-content">
                                <small class="text-muted">{{ task.created_at.strftime('%b %d, %Y') }}</small>
                                <p class="mb-0">{{ _('Task created') }}</p>
                            </div>
                        </div>
                        
                        {% if task.started_at %}
                        <div class="timeline-item">
                            <div class="timeline-marker bg-warning"></div>
                            <div class="timeline-content">
                                <small class="text-muted">{{ task.started_at.strftime('%b %d, %Y') }}</small>
                                <p class="mb-0">{{ _('Task started') }}</p>
                            </div>
                        </div>
                        {% endif %}
                        
                        {% if task.completed_at %}
                        <div class="timeline-item">
                            <div class="timeline-marker bg-success"></div>
                            <div class="timeline-content">
                                <small class="text-muted">{{ task.completed_at.strftime('%b %d, %Y') }}</small>
                                <p class="mb-0">{{ _('Task completed') }}</p>
                            </div>
                        </div>
                        {% endif %}
                        
                        <div class="timeline-item">
                            <div class="timeline-marker bg-secondary"></div>
                            <div class="timeline-content">
                                <small class="text-muted">{{ task.updated_at.strftime('%b %d, %Y') }}</small>
                                <p class="mb-0">{{ _('Last updated') }}</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Comments -->
            <div class="card mobile-card mt-4">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-comments me-2 text-primary"></i>{{ _('Task Comments') }}
                    </h6>
                </div>
                <div class="card-body">
                    {% include 'comments/_comments_section.html' with context %}
                </div>
            </div>

            <!-- Activity Log -->
            {% if task.activities.count() > 0 %}
            <div class="card mobile-card mt-4">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-clipboard-list me-2 text-secondary"></i>{{ _('Activity Log') }}
                    </h6>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-sm align-middle">
                            <thead>
                                <tr>
                                    <th>{{ _('When') }}</th>
                                    <th>{{ _('Event') }}</th>
                                    <th>{{ _('User') }}</th>
                                    <th>{{ _('Details') }}</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for act in activities %}
                                <tr>
                                    <td>{{ act.created_at.strftime('%Y-%m-%d %H:%M') }}</td>
                                    <td class="text-capitalize">{{ act.event.replace('_', ' ') }}</td>
                                    <td>{{ act.user.display_name if act.user else '-' }}</td>
                                    <td class="text-muted">{{ act.details or '' }}</td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            {% endif %}
        </div>
    </div>
</div>

<style>
/* Status and Priority Badges */
.status-badge, .priority-badge {
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.75rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.status-todo {
    background-color: #e2e8f0;
    color: #475569;
}

.status-in_progress {
    background-color: #fef3c7;
    color: #92400e;
}

.status-review {
    background-color: #dbeafe;
    color: #1e40af;
}

.status-done {
    background-color: #dcfce7;
    color: #166534;
}

.status-cancelled {
    background-color: #fee2e2;
    color: #991b1b;
}

.priority-low {
    background-color: #dcfce7;
    color: #166534;
}

.priority-medium {
    background-color: #fef3c7;
    color: #92400e;
}

.priority-high {
    background-color: #fed7aa;
    color: #c2410c;
}

.priority-urgent {
    background-color: #fee2e2;
    color: #991b1b;
}

/* Task Detail Items */
.task-detail-item {
    padding: 0.75rem;
    border-radius: 8px;
    background-color: #f8fafc;
    transition: all 0.2s ease;
}

.task-detail-item:hover {
    background-color: #f1f5f9;
    transform: translateX(4px);
}

/* Timeline Styling */
.timeline {
    position: relative;
    padding-left: 1rem;
}

.timeline::before {
    content: '';
    position: absolute;
    left: 0.5rem;
    top: 0;
    bottom: 0;
    width: 2px;
    background-color: #e2e8f0;
}

.timeline-item {
    position: relative;
    margin-bottom: 1.5rem;
}

.timeline-marker {
    position: absolute;
    left: -0.75rem;
    top: 0.25rem;
    width: 12px;
    height: 12px;
    border-radius: 50%;
    border: 2px solid white;
    box-shadow: 0 0 0 2px #e2e8f0;
}

.timeline-content {
    margin-left: 1rem;
}

.timeline-content small {
    font-size: 0.75rem;
}

.timeline-content p {
    font-size: 0.875rem;
    margin: 0.25rem 0 0 0;
}

/* Progress Bar */
.progress {
    background-color: #f1f5f9;
    border-radius: 10px;
    overflow: hidden;
}

.progress-bar {
    background: linear-gradient(90deg, var(--primary-color) 0%, var(--primary-dark) 100%);
    border-radius: 10px;
}

/* Mobile Optimizations */
@media (max-width: 768px) {
    .card-header {
        padding: 1rem 1rem 0.75rem 1rem;
    }
    
    .card-body {
        padding: 0.75rem 1rem;
    }
    
    .timeline {
        padding-left: 0.75rem;
    }
    
    .timeline-marker {
        left: -0.625rem;
        width: 10px;
        height: 10px;
    }
    
    .timeline-content {
        margin-left: 0.75rem;
    }
}

/* Hover Effects */
.task-detail-item:hover {
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

/* Dark mode for task details */
[data-theme="dark"] .task-detail-item {
    background-color: #0f172a;
}
[data-theme="dark"] .task-detail-item:hover {
    background-color: #0b1220;
}
[data-theme="dark"] .timeline::before { background-color: #1f2937; }
[data-theme="dark"] .timeline-marker { box-shadow: 0 0 0 2px #1f2937; }
[data-theme="dark"] .card.mobile-card .card-header h6 { color: #e5e7eb; }

.btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
</style>
<style>
/* Quick actions: prevent full-width buttons, improve spacing */
.quick-actions .btn { width: auto; }
@media (max-width: 768px) {
    .quick-actions { gap: 0.5rem; }
}
</style>

<script>
function updateTaskStatus(status) {
    // Build and submit form without default confirm
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = '{{ url_for("tasks.update_task_status", task_id=task.id) }}';

    const statusInput = document.createElement('input');
    statusInput.type = 'hidden';
    statusInput.name = 'status';
    statusInput.value = status;

    form.appendChild(statusInput);
    document.body.appendChild(form);
    form.submit();
}

function toggleEntries() { /* deprecated - replaced by showMoreEntries/showLessEntries */ }

document.addEventListener('DOMContentLoaded', function() {
    const rows = document.querySelectorAll('#timeEntriesTableBody tr');
    const total = rows.length;
    const initial = Math.min(10, total);
    rows.forEach((row, idx) => row.style.display = (idx < initial ? '' : 'none'));
    const info = document.getElementById('entriesInfo');
    if (info && total > 10) info.textContent = `Showing ${initial} of ${total} entries`;

    // Initialize tooltips
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
    tooltipTriggerList.forEach(function (tooltipTriggerEl) {
        new bootstrap.Tooltip(tooltipTriggerEl)
    })
});

// Quick Action Modal
let pendingStatus = null;
function openStatusModal(status) {
    pendingStatus = status;
    const titleMap = {
        'in_progress': 'Start Task',
        'review': 'Mark for Review',
        'todo': 'Pause / Reopen Task',
        'done': 'Complete Task',
        'cancelled': 'Cancel Task'
    };
    const bodyMap = {
        'in_progress': 'Are you sure you want to start this task now?',
        'review': 'Move this task to Review?',
        'todo': 'Move this task to To Do?',
        'done': 'Mark this task as Completed?',
        'cancelled': 'Cancel this task? You can reopen it later.'
    };

    const modalEl = document.getElementById('statusConfirmModal');
    modalEl.querySelector('.modal-title').textContent = titleMap[status] || 'Confirm Action';
    modalEl.querySelector('.modal-body-text').textContent = bodyMap[status] || 'Are you sure?';
    const modal = new bootstrap.Modal(modalEl);
    modal.show();
}

function confirmStatusChange() {
    if (!pendingStatus) return;
    const btn = document.getElementById('statusConfirmBtn');
    if (btn) {
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Working...';
    }
    updateTaskStatus(pendingStatus);
}

// Progressive show more/less for time entries
function showMoreEntries() {
    const rows = Array.from(document.querySelectorAll('#timeEntriesTableBody tr'));
    const info = document.getElementById('entriesInfo');
    const showMoreBtn = document.getElementById('showMoreBtn');
    const showLessBtn = document.getElementById('showLessBtn');
    const currentlyVisible = rows.filter(r => r.style.display !== 'none').length;
    const toShow = Math.min(currentlyVisible + 10, rows.length);
    rows.forEach((row, idx) => row.style.display = (idx < toShow ? '' : 'none'));
    if (info) info.textContent = (toShow < rows.length) ? `Showing ${toShow} of ${rows.length} entries` : `Showing all ${rows.length} entries`;
    if (toShow >= rows.length) {
        showMoreBtn.classList.add('d-none');
        showLessBtn.classList.remove('d-none');
    } else {
        showLessBtn.classList.remove('d-none');
    }
}

function showLessEntries() {
    const rows = Array.from(document.querySelectorAll('#timeEntriesTableBody tr'));
    const info = document.getElementById('entriesInfo');
    const showMoreBtn = document.getElementById('showMoreBtn');
    const showLessBtn = document.getElementById('showLessBtn');
    const initial = Math.min(10, rows.length);
    rows.forEach((row, idx) => row.style.display = (idx < initial ? '' : 'none'));
    if (info) info.textContent = `Showing ${initial} of ${rows.length} entries`;
    showMoreBtn.classList.remove('d-none');
    showLessBtn.classList.add('d-none');
}

// Function to show delete time entry modal
function showDeleteEntryModal(entryId, projectName, duration) {
    const nameEl = document.getElementById('deleteEntryProjectName');
    const durationEl = document.getElementById('deleteEntryDuration');
    const formEl = document.getElementById('deleteEntryForm');
    if (nameEl) nameEl.textContent = projectName || '';
    if (durationEl) durationEl.textContent = duration || '';
    if (formEl) formEl.action = "{{ url_for('timer.delete_timer', timer_id=0) }}".replace('0', entryId);
    const modal = document.getElementById('deleteEntryModal');
    if (modal) new bootstrap.Modal(modal).show();
}

// Loading state on delete submit
document.addEventListener('DOMContentLoaded', function() {
    const deleteForm = document.getElementById('deleteEntryForm');
    if (deleteForm) {
        deleteForm.addEventListener('submit', function() {
            const btn = deleteForm.querySelector('button[type="submit"]');
            if (btn) {
                btn.innerHTML = '<div class="loading-spinner me-2"></div>Deleting...';
                btn.disabled = true;
            }
        });
    }
});
</script>

<!-- Status Confirm Modal -->
<div class="modal fade" id="statusConfirmModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">{{ _('Confirm Action') }}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="{{ _('Close') }}"></button>
            </div>
            <div class="modal-body">
                <p class="modal-body-text">{{ _('Are you sure?') }}</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times me-2"></i>{{ _('Cancel') }}
                </button>
                <button type="button" id="statusConfirmBtn" class="btn btn-primary" onclick="confirmStatusChange()">
                    <i class="fas fa-check me-2"></i>{{ _('Confirm') }}
                </button>
            </div>
        </div>
    </div>
    </div>

<!-- Delete Time Entry Modal -->
<div class="modal fade" id="deleteEntryModal" 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 Time Entry') }}
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></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 time entry for') }} <strong id="deleteEntryProjectName"></strong>?</p>
                <p class="text-muted mb-0">{{ _('Duration:') }} <strong id="deleteEntryDuration"></strong></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times me-1"></i>{{ _('Cancel') }}
                </button>
                <form method="POST" id="deleteEntryForm" class="d-inline">
                    <button type="submit" class="btn btn-danger">
                        <i class="fas fa-trash me-2"></i>{{ _('Delete Entry') }}
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Delete Comment Modal -->
<div class="modal fade" id="deleteCommentModal" 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 Comment') }}
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></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 this comment?') }}</p>
                <div id="comment-preview" class="bg-light p-3 rounded mt-3" style="display: none;">
                    <div class="text-muted small mb-1">{{ _('Comment preview:') }}</div>
                    <div id="comment-preview-text"></div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times me-1"></i>{{ _('Cancel') }}
                </button>
                <form method="POST" id="deleteCommentForm" class="d-inline">
                    <button type="submit" class="btn btn-danger">
                        <i class="fas fa-trash me-2"></i>{{ _('Delete Comment') }}
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

{% endblock %}
