{% extends "base.html" %}

{% block title %}{{ _('Edit Time Entry') }} - {{ app_name }}{% endblock %}

{% block extra_css %}
{# Toast UI Editor CSS loaded dynamically on desktop only (Issue #557 mobile freeze fix) #}
{% endblock %}

{% block extra_js %}
{% if can_edit_schedule %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const projectSelect = document.getElementById('project_id');
    const taskSelect = document.getElementById('task_id');
    const form = document.querySelector('form');
    const scriptRoot = {{ request.script_root|default('')|tojson }};

    function buildTasksUrl(projectId) {
        const pid = String(projectId || '').trim();
        if (!pid) return '';
        return (scriptRoot || '') + '/api/projects/' + encodeURIComponent(pid) + '/tasks';
    }
    
    if (projectSelect && taskSelect) {
        projectSelect.addEventListener('change', function() {
            const projectId = this.value;
            
            // Clear current tasks
            taskSelect.innerHTML = '<option value="">No Task</option>';
            
            if (projectId) {
                // Fetch tasks for the selected project
                fetch(buildTasksUrl(projectId), { credentials: 'same-origin' })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success && data.tasks) {
                            data.tasks.forEach(task => {
                                const option = document.createElement('option');
                                option.value = task.id;
                                option.textContent = task.name;
                                taskSelect.appendChild(option);
                            });
                        }
                    })
                    .catch(error => {
                        console.error('Error fetching tasks:', error);
                    });
            }
        });
    }
    
    // Add form submission confirmation for admin users
    if (form) {
        form.addEventListener('submit', function(e) {
            // If we already confirmed, let it proceed
            if (form.dataset.confirmed === '1') {
                delete form.dataset.confirmed;
                return true;
            }

            const originalProject = '{{ timer.project.name }}';
            const selectedProject = projectSelect.options[projectSelect.selectedIndex].text;
            const originalStart = '{{ timer.start_time.strftime("%Y-%m-%d %H:%M") }}';
            const originalEnd = '{{ timer.end_time.strftime("%Y-%m-%d %H:%M") if timer.end_time else "Running" }}';
            const originalNotes = {{ (timer.notes or '')|tojson }};
            const originalTags = {{ (timer.tags or '')|tojson }};
            const originalBillable = {{ 'true' if timer.billable else 'false' }};
            
            const startDate = document.getElementById('start_date').value;
            const startTime = document.getElementById('start_time').value;
            const endDate = document.getElementById('end_date').value;
            const endTime = document.getElementById('end_time').value;
            const notesInput = document.getElementById('notes');
            const notesVal = (notesInput && notesInput.value) ? notesInput.value : '';
            const tagsVal = document.getElementById('tags').value || '';
            const billableVal = document.getElementById('billable').checked;
            
            const newStart = startDate && startTime ? `${startDate} ${startTime}` : originalStart;
            const newEnd = endDate && endTime ? `${endDate} ${endTime}` : originalEnd;
            
            const changes = [];
            if (originalProject !== selectedProject) changes.push({ label: 'Project', from: originalProject, to: selectedProject });
            if (originalStart !== newStart) changes.push({ label: 'Start', from: originalStart, to: newStart });
            if (originalEnd !== newEnd) changes.push({ label: 'End', from: originalEnd, to: newEnd });
            if (originalNotes !== notesVal) changes.push({ label: 'Notes', from: originalNotes || '—', to: notesVal || '—' });
            if (originalTags !== tagsVal) changes.push({ label: 'Tags', from: originalTags || '—', to: tagsVal || '—' });
            if ((originalBillable ? true : false) !== billableVal) changes.push({ label: 'Billable', from: originalBillable ? 'Yes' : 'No', to: billableVal ? 'Yes' : 'No' });

            if (changes.length > 0) {
                e.preventDefault();

                let summaryHtml = changes.map(ch => `
                    <div class="mb-2 pb-2 border-b border-border-light dark:border-border-dark">
                        <div class="text-sm text-text-muted-light dark:text-text-muted-dark mb-1">${ch.label}</div>
                        <div class="flex items-center gap-2">
                            <span class="text-red-600 dark:text-red-400">${ch.from}</span>
                            <i class="fas fa-arrow-right text-text-muted-light dark:text-text-muted-dark"></i>
                            <span class="text-green-600 dark:text-green-400">${ch.to}</span>
                        </div>
                    </div>
                `).join('');

                window.showConfirm(
                    summaryHtml + '<div class="mt-4 p-3 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded"><i class="fas fa-info-circle text-amber-600 dark:text-amber-400 me-2"></i>' + '{{ _("These updates will modify this time entry permanently.") }}' + '</div>',
                    {
                        title: '{{ _("Confirm Changes") }}',
                        confirmText: '{{ _("Confirm & Save") }}'
                    }
                ).then(confirmed => {
                    if (confirmed) {
                        form.dataset.confirmed = '1';
                        if (typeof form.requestSubmit === 'function') {
                            form.requestSubmit();
                        } else {
                            form.submit();
                        }
                    }
                });
            }
        });
    }

    // Ensure admin save button programmatically submits the form
    const adminSaveBtn = document.getElementById('adminEditSaveBtn');
    if (adminSaveBtn && form) {
        adminSaveBtn.addEventListener('click', function(ev) {
            ev.preventDefault();
            if (typeof form.checkValidity === 'function' && !form.checkValidity()) {
                if (typeof form.reportValidity === 'function') form.reportValidity();
                return;
            }
            if (typeof form.requestSubmit === 'function') {
                form.requestSubmit();
            } else {
                form.submit();
            }
        });
    }

    // Live update duration when date/time fields change (admin form)
    const startDate = document.getElementById('start_date');
    const startTime = document.getElementById('start_time');
    const endDate = document.getElementById('end_date');
    const endTime = document.getElementById('end_time');
    const durationLabel = document.getElementById('adminEditDuration');
    function updateDuration() {
        if (!startDate || !startTime || !endDate || !endTime || !durationLabel) return;
        const sd = startDate.value;
        const st = startTime.value;
        const ed = endDate.value;
        const et = endTime.value;
        if (!sd || !st || !ed || !et) {
            durationLabel.textContent = '--:--:--';
            return;
        }
        const s = new Date(`${sd}T${st}`);
        const e = new Date(`${ed}T${et}`);
        const diff = Math.max(0, Math.floor((e - s) / 1000));
        const h = Math.floor(diff / 3600);
        const m = Math.floor((diff % 3600) / 60);
        const srem = diff % 60;
        durationLabel.textContent = `${h.toString().padStart(2,'0')}:${m.toString().padStart(2,'0')}:${srem.toString().padStart(2,'0')}`;
    }
    if (startDate && startTime && endDate && endTime) {
        startDate.addEventListener('change', updateDuration);
        startTime.addEventListener('change', updateDuration);
        endDate.addEventListener('change', updateDuration);
        endTime.addEventListener('change', updateDuration);
    }
});
</script>
{% endif %}
{% endblock %}

{% block content %}
<div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6">
    <div>
        <h1 class="text-2xl font-bold flex items-center gap-2">
            <i class="fas fa-edit text-primary"></i>
            {{ _('Edit Time Entry') }}
        </h1>
        <p class="text-text-muted-light dark:text-text-muted-dark">
            {{ timer.project.name }}{% if timer.task %} - {{ timer.task.name }}{% endif %}
        </p>
    </div>
    {% if current_user.is_admin %}
    <span class="inline-flex items-center px-3 py-1.5 rounded-lg bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300 text-sm font-medium mt-4 md:mt-0">
        <i class="fas fa-shield-alt mr-2"></i>{{ _('Admin Mode') }}
    </span>
    {% endif %}
</div>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
    <div class="lg:col-span-2">
        <div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
            {% if can_edit_schedule %}
            {% if current_user.is_admin %}
            <!-- Admin notification -->
            <div class="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4 mb-6">
                <div class="flex items-start gap-3">
                    <i class="fas fa-info-circle text-blue-600 dark:text-blue-400 mt-1"></i>
                    <div>
                        <p class="text-sm text-blue-800 dark:text-blue-200">
                            <strong>{{ _('Admin Mode:') }}</strong> {{ _('You can edit all fields of this time entry, including project, task, start/end times, and source.') }}
                        </p>
                    </div>
                </div>
            </div>
            {% else %}
            <div class="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4 mb-6">
                <div class="flex items-start gap-3">
                    <i class="fas fa-info-circle text-blue-600 dark:text-blue-400 mt-1"></i>
                    <div>
                        <p class="text-sm text-blue-800 dark:text-blue-200">
                            {{ _("You can edit this entry's project, task, start and end times, and break.") }}
                        </p>
                    </div>
                </div>
            </div>
            {% endif %}

            <form method="POST" action="{{ url_for('timer.edit_timer', timer_id=timer.id) }}">
                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                
                <!-- Project and Task Selection -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                    <div>
                        <label for="project_id" class="form-label">
                            <i class="fas fa-project-diagram mr-1"></i>{{ _('Project') }}
                        </label>
                        <select class="form-input" id="project_id" name="project_id" required>
                            {% for project in projects %}
                            <option value="{{ project.id }}" {% if project.id == timer.project_id %}selected{% endif %}>
                                {{ project.name }}
                            </option>
                            {% endfor %}
                        </select>
                        <p class="text-xs text-text-muted-light dark:text-text-muted-dark mt-1">{{ _('Select the project this time entry belongs to') }}</p>
                    </div>
                    <div>
                        <label for="task_id" class="form-label">
                            <i class="fas fa-tasks mr-1"></i>{{ _('Task (Optional)') }}
                        </label>
                        <select class="form-input" id="task_id" name="task_id">
                            <option value="">No Task</option>
                            {% for task in tasks %}
                            <option value="{{ task.id }}" {% if task.id == timer.task_id %}selected{% endif %}>
                                {{ task.name }}
                            </option>
                            {% endfor %}
                        </select>
                        <p class="text-xs text-text-muted-light dark:text-text-muted-dark mt-1">{{ _('Select a specific task within the project') }}</p>
                    </div>
                </div>

                <!-- Start Date/Time -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                    <div>
                        <label for="start_date" class="form-label">
                            <i class="fas fa-clock mr-1"></i>{{ _('Start Date') }}
                        </label>
                        <input type="date" class="form-input" id="start_date" name="start_date" 
                               value="{{ timer.start_time.strftime('%Y-%m-%d') }}" required>
                        <p class="text-xs text-text-muted-light dark:text-text-muted-dark mt-1">{{ _('When the work started') }}</p>
                    </div>
                    <div>
                        <label for="start_time" class="form-label">
                            <i class="fas fa-clock mr-1"></i>{{ _('Start Time') }}
                        </label>
                        <input type="time" class="form-input" id="start_time" name="start_time" 
                               value="{{ timer.start_time.strftime('%H:%M') }}" required>
                        <p class="text-xs text-text-muted-light dark:text-text-muted-dark mt-1">{{ _('Time the work started') }}</p>
                    </div>
                </div>

                <!-- End Date/Time -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                    <div>
                        <label for="end_date" class="form-label">
                            <i class="fas fa-stop-circle mr-1"></i>{{ _('End Date') }}
                        </label>
                        <input type="date" class="form-input" id="end_date" name="end_date" 
                               value="{{ timer.end_time.strftime('%Y-%m-%d') if timer.end_time else '' }}">
                        <p class="text-xs text-text-muted-light dark:text-text-muted-dark mt-1">{{ _('When the work ended (leave empty if still running)') }}</p>
                    </div>
                    <div>
                        <label for="end_time" class="form-label">
                            <i class="fas fa-stop-circle mr-1"></i>{{ _('End Time') }}
                        </label>
                        <input type="time" class="form-input" id="end_time" name="end_time" 
                               value="{{ timer.end_time.strftime('%H:%M') if timer.end_time else '' }}">
                        <p class="text-xs text-text-muted-light dark:text-text-muted-dark mt-1">{{ _('Time the work ended') }}</p>
                    </div>
                    <div>
                        <label for="break_time" class="form-label">
                            <i class="fas fa-coffee mr-1"></i>{{ _('Break') }}
                        </label>
                        <input type="text" class="form-input" id="break_time" name="break_time" placeholder="HH:MM"
                               value="{% if timer.break_seconds %}{{ (timer.break_seconds // 3600) }}:{{ '%02d' | format((timer.break_seconds % 3600) // 60) }}{% endif %}">
                        <p class="text-xs text-text-muted-light dark:text-text-muted-dark mt-1">{{ _('Break duration (HH:MM). Subtracted from total to get worked duration.') }}</p>
                    </div>
                </div>

                <!-- Source (admin only), Billable, Duration -->
                <div class="grid grid-cols-1 {% if show_source_dropdown %}md:grid-cols-3{% else %}md:grid-cols-2{% endif %} gap-4 mb-6">
                    {% if show_source_dropdown %}
                    <div>
                        <label for="source" class="form-label">
                            <i class="fas fa-tag mr-1"></i>{{ _('Source') }}
                        </label>
                        <select class="form-input" id="source" name="source">
                            <option value="manual" {% if timer.source == 'manual' %}selected{% endif %}>{{ _('Manual') }}</option>
                            <option value="auto" {% if timer.source == 'auto' %}selected{% endif %}>{{ _('Automatic') }}</option>
                        </select>
                        <p class="text-xs text-text-muted-light dark:text-text-muted-dark mt-1">{{ _('How this entry was created') }}</p>
                    </div>
                    {% endif %}
                    <div class="flex items-center">
                        <div class="flex items-center gap-3 mt-6">
                            <input type="checkbox" id="billable" name="billable" class="h-5 w-5 rounded border-gray-300 text-primary focus:ring-0" {% if timer.billable %}checked{% endif %}>
                            <label for="billable" class="text-sm font-medium text-gray-700 dark:text-gray-300">
                                <i class="fas fa-dollar-sign mr-1"></i>{{ _('Billable') }}
                            </label>
                        </div>
                    </div>
                    <div class="flex items-center">
                        <div class="text-sm mt-6">
                            <strong class="text-gray-700 dark:text-gray-300">{{ _('Duration:') }}</strong>
                            <span id="adminEditDuration" class="ml-2 text-primary font-mono">{{ timer.duration_formatted }}</span>
                        </div>
                    </div>
                </div>

                <!-- Notes -->
                <div class="mb-6">
                    <label for="notes" class="form-label">
                        <i class="fas fa-sticky-note mr-1"></i>{{ _('Notes') }}
                    </label>
                    <div class="markdown-editor-wrapper">
                        <textarea class="form-input hidden" id="notes" name="notes" placeholder="{{ _('Describe what you worked on') }}">{{ timer.notes or '' }}</textarea>
                        <div id="notes_editor"></div>
                    </div>
                </div>

                <!-- Tags -->
                <div class="mb-6">
                    <label for="tags" class="form-label">
                        <i class="fas fa-tags mr-1"></i>{{ _('Tags') }}
                    </label>
                    <input type="text" class="form-input" id="tags" name="tags" placeholder="{{ _('tag1, tag2') }}" value="{{ timer.tags or '' }}">
                    <p class="text-xs text-text-muted-light dark:text-text-muted-dark mt-1">{{ _('Separate tags with commas') }}</p>
                </div>

                <!-- Paid Status and Invoice Number -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                    <div class="flex items-center">
                        <div class="flex items-center gap-3">
                            <input type="checkbox" id="paid" name="paid" class="h-5 w-5 rounded border-gray-300 text-primary focus:ring-0" {% if timer.paid %}checked{% endif %}>
                            <label for="paid" class="text-sm font-medium text-gray-700 dark:text-gray-300">
                                <i class="fas fa-check-circle mr-1"></i>{{ _('Paid') }}
                            </label>
                        </div>
                    </div>
                    <div>
                        <label for="invoice_number" class="form-label">
                            <i class="fas fa-file-invoice mr-1"></i>{{ _('Invoice Number') }}
                        </label>
                        <input type="text" class="form-input" id="invoice_number" name="invoice_number" placeholder="{{ _('Internal invoice reference') }}" value="{{ timer.invoice_number or '' }}" maxlength="100">
                        <p class="text-xs text-text-muted-light dark:text-text-muted-dark mt-1">{{ _('Reference to internal invoice number') }}</p>
                    </div>
                </div>

                <!-- Reason for Change -->
                <div class="mb-6">
                    <label for="reason" class="form-label">
                        <i class="fas fa-comment-alt mr-1"></i>{{ _('Reason for Change') }} <span class="text-text-muted-light dark:text-text-muted-dark text-xs">({{ _('Optional but recommended') }})</span>
                    </label>
                    <textarea class="form-input" id="reason" name="reason" rows="3" placeholder="{{ _('e.g., Corrected duration, updated project assignment, etc.') }}"></textarea>
                    <p class="text-xs text-text-muted-light dark:text-text-muted-dark mt-1">{{ _('Explain why you are making these changes') }}</p>
                </div>

                <!-- Action Buttons -->
                <div class="flex flex-col sm:flex-row justify-between gap-3 mt-8 pt-6 border-t border-border-light dark:border-border-dark">
                    <div class="flex flex-col sm:flex-row gap-2">
                        <a href="{{ url_for('main.dashboard') }}" class="px-4 py-2 rounded-lg border border-border-light dark:border-border-dark text-text-light dark:text-text-dark hover:bg-background-light dark:hover:bg-background-dark">
                            <i class="fas fa-arrow-left mr-1"></i>{{ _('Back') }}
                        </a>
                        <a href="{{ url_for('timer.duplicate_timer', timer_id=timer.id) }}" class="px-4 py-2 rounded-lg border border-primary text-primary hover:bg-primary hover:text-white transition-colors">
                            <i class="fas fa-copy mr-1"></i>{{ _('Duplicate') }}
                        </a>
                    </div>
                    <button type="submit" class="w-full sm:w-auto bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary-dark transition-colors" id="adminEditSaveBtn">
                        <i class="fas fa-save mr-2"></i>{{ _('Save Changes') }}
                    </button>
                </div>
            </form>

            {% else %}
            <!-- Regular user form -->
            <form method="POST" action="{{ url_for('timer.edit_timer', timer_id=timer.id) }}">
                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                
                <!-- Read-only information -->
                <div class="bg-background-light dark:bg-background-dark p-4 rounded-lg mb-6">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                        <div>
                            <span class="text-text-muted-light dark:text-text-muted-dark">{{ _('Project:') }}</span>
                            <span class="ml-2 font-medium">{{ timer.project.name }}</span>
                        </div>
                        {% if timer.task %}
                        <div>
                            <span class="text-text-muted-light dark:text-text-muted-dark">{{ _('Task:') }}</span>
                            <span class="ml-2 font-medium">{{ timer.task.name }}</span>
                        </div>
                        {% endif %}
                        <div>
                            <span class="text-text-muted-light dark:text-text-muted-dark">{{ _('Start:') }}</span>
                            <span class="ml-2 font-medium">{{ timer.start_time.strftime('%Y-%m-%d %H:%M') }}</span>
                        </div>
                        <div>
                            <span class="text-text-muted-light dark:text-text-muted-dark">{{ _('End:') }}</span>
                            {% if timer.end_time %}
                            <span class="ml-2 font-medium">{{ timer.end_time.strftime('%Y-%m-%d %H:%M') }}</span>
                            {% else %}
                            <span class="ml-2 text-amber-600 dark:text-amber-400 font-medium">{{ _('Running') }}</span>
                            {% endif %}
                        </div>
                    </div>
                    <div class="mt-3 flex gap-2">
                        <span class="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-primary/10 text-primary">
                            {{ _('Duration:') }} {{ timer.duration_formatted }}
                        </span>
                        {% if timer.source == 'manual' %}
                        <span class="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-200">
                            {{ _('Manual') }}
                        </span>
                        {% else %}
                        <span class="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300">
                            {{ _('Automatic') }}
                        </span>
                        {% endif %}
                    </div>
                </div>

                <!-- Notes -->
                <div class="mb-6">
                    <label for="notes" class="form-label">
                        <i class="fas fa-sticky-note mr-1"></i>{{ _('Notes') }}
                    </label>
                    <div class="markdown-editor-wrapper">
                        <textarea class="form-input hidden" id="notes" name="notes" placeholder="{{ _('Describe what you worked on') }}">{{ timer.notes or '' }}</textarea>
                        <div id="notes_editor"></div>
                    </div>
                </div>

                <!-- Tags and Billable -->
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                    <div class="md:col-span-2">
                        <label for="tags" class="form-label">
                            <i class="fas fa-tags mr-1"></i>{{ _('Tags') }}
                        </label>
                        <input type="text" class="form-input" id="tags" name="tags" placeholder="{{ _('tag1, tag2') }}" value="{{ timer.tags or '' }}">
                        <p class="text-xs text-text-muted-light dark:text-text-muted-dark mt-1">{{ _('Separate tags with commas') }}</p>
                    </div>
                    <div class="flex items-center">
                        <div class="flex items-center gap-3 mt-6">
                            <input type="checkbox" id="billable" name="billable" class="h-5 w-5 rounded border-gray-300 text-primary focus:ring-0" {% if timer.billable %}checked{% endif %}>
                            <label for="billable" class="text-sm font-medium text-gray-700 dark:text-gray-300">
                                <i class="fas fa-dollar-sign mr-1"></i>{{ _('Billable') }}
                            </label>
                        </div>
                    </div>
                </div>

                <!-- Paid Status and Invoice Number -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                    <div class="flex items-center">
                        <div class="flex items-center gap-3">
                            <input type="checkbox" id="paid" name="paid" class="h-5 w-5 rounded border-gray-300 text-primary focus:ring-0" {% if timer.paid %}checked{% endif %}>
                            <label for="paid" class="text-sm font-medium text-gray-700 dark:text-gray-300">
                                <i class="fas fa-check-circle mr-1"></i>{{ _('Paid') }}
                            </label>
                        </div>
                    </div>
                    <div>
                        <label for="invoice_number" class="form-label">
                            <i class="fas fa-file-invoice mr-1"></i>{{ _('Invoice Number') }}
                        </label>
                        <input type="text" class="form-input" id="invoice_number" name="invoice_number" placeholder="{{ _('Internal invoice reference') }}" value="{{ timer.invoice_number or '' }}" maxlength="100">
                        <p class="text-xs text-text-muted-light dark:text-text-muted-dark mt-1">{{ _('Reference to internal invoice number') }}</p>
                    </div>
                </div>

                <!-- Reason for Change -->
                <div class="mb-6">
                    <label for="reason" class="form-label">
                        <i class="fas fa-comment-alt mr-1"></i>{{ _('Reason for Change') }} <span class="text-text-muted-light dark:text-text-muted-dark text-xs">({{ _('Optional but recommended') }})</span>
                    </label>
                    <textarea class="form-input" id="reason" name="reason" rows="3" placeholder="{{ _('e.g., Corrected duration, updated project assignment, etc.') }}"></textarea>
                    <p class="text-xs text-text-muted-light dark:text-text-muted-dark mt-1">{{ _('Explain why you are making these changes') }}</p>
                </div>

                <!-- Action Buttons -->
                <div class="flex flex-col sm:flex-row justify-between gap-3 mt-8 pt-6 border-t border-border-light dark:border-border-dark">
                    <div class="flex flex-col sm:flex-row gap-2">
                        <a href="{{ url_for('main.dashboard') }}" class="px-4 py-2 rounded-lg border border-border-light dark:border-border-dark text-text-light dark:text-text-dark hover:bg-background-light dark:hover:bg-background-dark">
                            <i class="fas fa-arrow-left mr-1"></i>{{ _('Back') }}
                        </a>
                        <a href="{{ url_for('timer.duplicate_timer', timer_id=timer.id) }}" class="px-4 py-2 rounded-lg border border-primary text-primary hover:bg-primary hover:text-white transition-colors">
                            <i class="fas fa-copy mr-1"></i>{{ _('Duplicate') }}
                        </a>
                    </div>
                    <button type="submit" class="w-full sm:w-auto bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary-dark transition-colors">
                        <i class="fas fa-save mr-2"></i>{{ _('Save Changes') }}
                    </button>
                </div>
            </form>
            {% endif %}
        </div>
    </div>

    <!-- Sidebar with additional info -->
    <div class="lg:col-span-1 space-y-6">
        <div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
            <h2 class="text-lg font-semibold mb-4">{{ _('Entry Details') }}</h2>
            <div class="space-y-3 text-sm">
                <div>
                    <span class="text-text-muted-light dark:text-text-muted-dark block mb-1">{{ _('Created') }}</span>
                    <span class="font-medium">{{ timer.created_at.strftime('%Y-%m-%d %H:%M') if timer.created_at else 'N/A' }}</span>
                </div>
                {% if timer.user and (current_user.is_admin or timer.user_id == current_user.id) %}
                <div>
                    <span class="text-text-muted-light dark:text-text-muted-dark block mb-1">{{ _('User') }}</span>
                    <span class="font-medium">{{ timer.user.full_name or timer.user.username }}</span>
                </div>
                {% endif %}
                <div>
                    <span class="text-text-muted-light dark:text-text-muted-dark block mb-1">{{ _('Entry ID') }}</span>
                    <span class="font-mono text-xs">#{{ timer.id }}</span>
                </div>
            </div>
        </div>

        {% if current_user.is_admin %}
        <div class="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4">
            <h3 class="text-sm font-semibold text-amber-800 dark:text-amber-300 mb-2">
                <i class="fas fa-exclamation-triangle mr-1"></i>{{ _('Admin Notice') }}
            </h3>
            <p class="text-xs text-amber-700 dark:text-amber-400">
                {{ _('As an admin, you have full editing privileges for this time entry. Changes will be logged for audit purposes.') }}
            </p>
        </div>
        {% endif %}
    </div>
</div>

<script>
(function() {
    // Issue #557: avoid loading Toast UI Editor on mobile to prevent browser freeze
    window.isMobileView = window.matchMedia('(max-width: 767px)').matches;
    if (window.isMobileView) {
        document.querySelectorAll('.markdown-editor-wrapper').forEach(function(wrapper) {
            var notes = wrapper.querySelector('textarea[name="notes"]');
            var editorEl = wrapper.querySelector('[id="notes_editor"]');
            if (notes) {
                notes.classList.remove('hidden');
                notes.classList.add('form-input');
                if (!notes.getAttribute('rows')) notes.setAttribute('rows', '5');
            }
            if (editorEl) editorEl.style.display = 'none';
        });
    }
})();
</script>

<!-- Toast UI Editor: load only on desktop to avoid mobile freeze (Issue #557) -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    if (window.isMobileView) {
        window.mdEditor = null;
        return;
    }
    var link1 = document.createElement('link');
    link1.rel = 'stylesheet';
    link1.href = 'https://uicdn.toast.com/editor/latest/toastui-editor.min.css';
    document.head.appendChild(link1);
    var link2 = document.createElement('link');
    link2.rel = 'stylesheet';
    link2.href = 'https://uicdn.toast.com/editor/latest/theme/toastui-editor-dark.css';
    document.head.appendChild(link2);
    var scriptEl = document.createElement('script');
    scriptEl.src = 'https://uicdn.toast.com/editor/latest/toastui-editor-all.min.js';
    scriptEl.onload = function initToastEditorEditTimer() {
    const notesInput = document.getElementById('notes');
    let mdEditor = null;

    if (notesInput && window.toastui && window.toastui.Editor) {
        const theme = document.documentElement.classList.contains('dark') ? 'dark' : 'light';
        mdEditor = new toastui.Editor({
            el: document.getElementById('notes_editor'),
            height: '300px',
            initialEditType: 'wysiwyg',
            previewStyle: 'vertical',
            usageStatistics: false,
            hideModeSwitch: false,
            placeholder: '{{ _("Describe what you worked on") }}',
            theme: theme,
            toolbarItems: [
                ['heading', 'bold', 'italic', 'strike'],
                ['hr', 'quote'],
                ['ul', 'ol', 'task'],
                ['link', 'code', 'codeblock', 'table'],
                ['image'],
                ['scrollSync']
            ],
            initialValue: notesInput.value || ''
        });

        // Apply theme changes dynamically if supported
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if (mutation.type === 'attributes' && mutation.attributeName === 'class' && mdEditor) {
                    const nextTheme = document.documentElement.classList.contains('dark') ? 'dark' : 'light';
                    try {
                        if (typeof mdEditor.setTheme === 'function') {
                            mdEditor.setTheme(nextTheme);
                        }
                    } catch (e) {}
                }
            });
        });
        observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });

        // Multiple image upload handler - improved version
        mdEditor.removeHook && mdEditor.removeHook('addImageBlobHook');
        
        // Create custom multiple file input with unique ID
        const fileInputId = 'edit-timer-image-input-' + Date.now();
        let fileInput = document.getElementById(fileInputId);
        if (!fileInput) {
            fileInput = document.createElement('input');
            fileInput.id = fileInputId;
            fileInput.type = 'file';
            fileInput.accept = 'image/*';
            fileInput.setAttribute('multiple', 'multiple'); // Use setAttribute to ensure it's set
            fileInput.style.display = 'none';
            fileInput.style.position = 'absolute';
            fileInput.style.left = '-9999px';
            document.body.appendChild(fileInput);
        }
        
        // Verify multiple attribute is set
        if (!fileInput.hasAttribute('multiple')) {
            fileInput.setAttribute('multiple', 'multiple');
        }
        console.log('File input multiple attribute:', fileInput.multiple, fileInput.hasAttribute('multiple'));
        
        // Function to find image button with multiple strategies
        function findImageButton(toolbar, retries = 0) {
            if (!toolbar) return null;
            
            // Try multiple selectors in order of reliability
            const selectors = [
                '[data-tooltip="Insert image"]',
                '[data-tooltip*="image" i]',
                '[aria-label*="image" i]',
                '.toastui-editor-toolbar-icons.image',
                'button[class*="image"]',
                '.toastui-editor-toolbar-group button:nth-child(5)', // Common position for image button
                '.toastui-editor-toolbar-group button:nth-child(6)',
                '.toastui-editor-toolbar-group button:nth-child(4)'
            ];
            
            for (const selector of selectors) {
                try {
                    const button = toolbar.querySelector(selector);
                    if (button) {
                        // Verify it's likely the image button by checking if it has image-related attributes or classes
                        const buttonText = (button.textContent || '').toLowerCase();
                        const buttonTitle = (button.title || button.getAttribute('title') || '').toLowerCase();
                        if (buttonText.includes('image') || buttonTitle.includes('image') || 
                            selector.includes('image') || button.classList.toString().includes('image')) {
                            return button;
                        }
                    }
                } catch (e) {
                    // Continue to next selector
                }
            }
            
            return null;
        }
        
        // Function to intercept image button with retry logic
        function setupImageButtonInterception(editor, input, maxRetries = 5) {
            let attempts = 0;
            let intercepted = false;
            
            function tryIntercept() {
                attempts++;
                try {
                    // Get the editor's root element - try multiple ways
                    const editorContainer = document.getElementById('notes_editor');
                    if (!editorContainer) {
                        throw new Error('Editor container element not found');
                    }
                    
                    // Find toolbar - try multiple ways to access it
                    let toolbar = null;
                    // Try finding toolbar relative to editor container
                    let editorWrapper = null;
                    if (editorContainer.closest) {
                        editorWrapper = editorContainer.closest('.toastui-editor');
                    }
                    if (!editorWrapper && editorContainer.parentElement) {
                        editorWrapper = editorContainer.parentElement;
                    }
                    if (editorWrapper) {
                        toolbar = editorWrapper.querySelector('.toastui-editor-toolbar');
                    }
                    // Fallback: search entire document
                    if (!toolbar) {
                        toolbar = document.querySelector('.toastui-editor-toolbar');
                    }
                    
                    if (toolbar && !intercepted) {
                        const imageButton = findImageButton(toolbar, attempts);
                        if (imageButton) {
                            // Use capture phase to intercept before ToastUI's handler
                            imageButton.addEventListener('click', function handler(e) {
                                e.preventDefault();
                                e.stopPropagation();
                                e.stopImmediatePropagation();
                                
                                // Small delay to ensure default behavior is prevented
                                setTimeout(() => {
                                    input.click();
                                }, 10);
                                
                                return false;
                            }, true); // Use capture phase
                            
                            intercepted = true;
                            console.log('Successfully intercepted image button for multiple file selection');
                            return true;
                        }
                    }
                } catch (err) {
                    console.warn('Error intercepting image button (attempt ' + attempts + '):', err);
                }
                
                // Retry if we haven't exceeded max retries
                if (attempts < maxRetries && !intercepted) {
                    setTimeout(tryIntercept, 200 * attempts); // Exponential backoff
                    return false;
                } else if (!intercepted) {
                    console.warn('Could not intercept image button after ' + maxRetries + ' attempts. Multiple image selection may not work via toolbar button.');
                    return false;
                }
                return false;
            }
            
            // Start with initial delay to ensure toolbar is ready
            setTimeout(tryIntercept, 100);
        }
        
        // Override the addImageBlobHook to use multiple file selection
        // This is the fallback if button interception fails
        if (mdEditor && typeof mdEditor.addHook === 'function') {
            mdEditor.addHook('addImageBlobHook', async function(blob, callback) {
                // Prevent the default single file behavior
                // Trigger our multiple file input instead
                setTimeout(function() {
                    fileInput.click();
                }, 10);
                // Don't call callback - let fileInput.change handle it
            });
        }
        
        // Setup button interception
        if (mdEditor) {
            setupImageButtonInterception(mdEditor, fileInput);
        }
        
        // Handle multiple file selection with progress feedback
        fileInput.addEventListener('change', async (e) => {
            const files = Array.from(e.target.files);
            console.log('File input changed. Files selected:', files.length, 'Multiple attribute:', fileInput.multiple);
            
            if (files.length === 0) {
                console.log('No files selected');
                return;
            }
            
            // Log file details for debugging
            files.forEach((file, index) => {
                console.log(`File ${index + 1}: ${file.name}, type: ${file.type}, size: ${file.size}`);
            });
            
            // Validate file types
            const allowedTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/webp'];
            const validFiles = files.filter(file => {
                const isValid = allowedTypes.includes(file.type) || /\.(png|jpg|jpeg|gif|webp)$/i.test(file.name);
                if (!isValid) {
                    console.warn('Skipping invalid file type:', file.name, file.type);
                }
                return isValid;
            });
            
            if (validFiles.length === 0) {
                alert('{{ _("No valid image files selected. Please select PNG, JPG, GIF, or WebP images.") }}');
                fileInput.value = '';
                return;
            }
            
            if (validFiles.length < files.length) {
                console.warn('Some files were skipped due to invalid type');
            }
            
            // Show loading feedback
            const fileCount = validFiles.length;
            const loadingMsg = fileCount > 1 ? 
                `{{ _("Uploading") }} ${fileCount} {{ _("images") }}...` : 
                '{{ _("Uploading image") }}...';
            
            // Try to show a temporary loading indicator (if toast/notification system exists)
            let loadingIndicator = null;
            try {
                // Check if there's a toast/notification system we can use
                if (window.showToast || window.showNotification) {
                    const showToast = window.showToast || window.showNotification;
                    loadingIndicator = showToast(loadingMsg, 'info', { duration: 0 });
                }
            } catch (e) {
                // No toast system available, continue without it
            }
            
            try {
                const formData = new FormData();
                validFiles.forEach(file => {
                    formData.append('images', file);
                });
                
                const res = await fetch('{{ url_for('api.upload_editor_images_bulk') }}', {
                    method: 'POST',
                    body: formData
                });
                
                const data = await res.json();
                if (data && data.urls && data.urls.length > 0) {
                    // Insert all images into editor
                    const imagesMarkdown = data.urls.map((url, index) => {
                        const fileName = validFiles[index].name || 'image';
                        return `![${fileName}](${url})`;
                    }).join('\n\n');
                    
                    // Get current markdown content
                    const currentMarkdown = mdEditor.getMarkdown() || '';
                    
                    // Append images to current content (with proper spacing)
                    const newMarkdown = currentMarkdown 
                        ? currentMarkdown + '\n\n' + imagesMarkdown
                        : imagesMarkdown;
                    
                    // Set the markdown which will properly render images in WYSIWYG mode
                    mdEditor.setMarkdown(newMarkdown);
                    
                    // Show success message
                    const successMsg = data.urls.length > 1 ? 
                        `{{ _("Successfully uploaded") }} ${data.urls.length} {{ _("images") }}` : 
                        '{{ _("Image uploaded successfully") }}';
                    
                    if (loadingIndicator && typeof loadingIndicator.update === 'function') {
                        loadingIndicator.update(successMsg, 'success');
                        setTimeout(() => loadingIndicator.remove && loadingIndicator.remove(), 2000);
                    }
                    
                    // Show warnings if any
                    if (data.warnings && data.warnings.length > 0) {
                        console.warn('Some images failed to upload:', data.warnings);
                        const warningMsg = `{{ _("Warning") }}: ${data.warnings.length} {{ _("image(s) failed to upload") }}`;
                        if (window.showToast || window.showNotification) {
                            const showToast = window.showToast || window.showNotification;
                            showToast(warningMsg, 'warning');
                        } else {
                            alert(warningMsg);
                        }
                    }
                } else {
                    const errorMsg = data.error || '{{ _("Failed to upload images. Please try again.") }}';
                    console.error('Upload failed', data);
                    if (loadingIndicator && typeof loadingIndicator.remove === 'function') {
                        loadingIndicator.remove();
                    }
                    alert(errorMsg);
                }
            } catch (error) {
                console.error('Multiple image upload error', error);
                if (loadingIndicator && typeof loadingIndicator.remove === 'function') {
                    loadingIndicator.remove();
                }
                alert('{{ _("Failed to upload images. Please check your connection and try again.") }}');
            }
            
            // Reset file input
            fileInput.value = '';
        });

        // Sync editor content to hidden textarea on form submit (attach to all forms so both admin and regular user form work)
        document.querySelectorAll('form').forEach(function(form) {
            form.addEventListener('submit', function(e) {
                if (mdEditor && notesInput) {
                    try {
                        notesInput.value = mdEditor.getMarkdown();
                    } catch (err) {
                        console.error('Failed to sync markdown editor:', err);
                    }
                }
            });
        });
    }
    }; // end Toast UI init onload
    document.head.appendChild(scriptEl);
});
</script>
{% endblock %}
