<?php
require_once 'includes/db.php';

$user_id = $_SESSION['user_id'] ?? 0;
$emp = fetch("SELECT id FROM employees WHERE user_id = ?", [$user_id]);
$emp_id = $emp['id'] ?? 0;

$tasks = fetchAll("
    SELECT t.*, 
           COALESCE(s.name, t.status) as status, 
           s.color_code,
           pl.name as line_name,
           pl.is_active as line_active,
           stg.name as stage_name
    FROM tasks t
    LEFT JOIN task_statuses s ON t.status = s.name
    LEFT JOIN line_stages ls ON t.line_stage_id = ls.id
    LEFT JOIN production_lines pl ON ls.production_line_id = pl.id
    LEFT JOIN workflow_stages stg ON ls.workflow_stage_id = stg.id
    WHERE t.employee_id = ? AND t.status != 'Suspended'
    ORDER BY t.created_at DESC
", [$emp_id]);

$statuses = fetchAll("SELECT * FROM task_statuses ORDER BY FIELD(name, 'NEW', 'WIP', 'COMPLETED', 'BLOCKED')");
?>

<div id="worklist-view">
    <div style="display: flex; gap: 1rem; margin-bottom: 1.5rem; background: var(--bg-card); padding: 1rem; border-radius: 16px; border: 1px solid var(--border); align-items: center; flex-wrap: wrap;">
        <div style="flex: 1; min-width: 300px; position: relative;">
            <i class="fas fa-search" style="position: absolute; left: 1rem; top: 50%; transform: translateY(-50%); color: var(--text-muted);"></i>
            <input type="text" id="worklist-search" class="form-control" placeholder="Search by Task ID, Title, or Description..." style="padding-left: 2.75rem; border-radius: 12px; height: 45px;">
        </div>
        <div style="width: 200px;">
            <select id="worklist-filter-status" class="form-control" style="border-radius: 12px; height: 45px; cursor: pointer;">
                <option value="">All Statuses</option>
                <?php foreach ($statuses as $s): ?>
                    <option value="<?php echo $s['name']; ?>"><?php echo $s['name']; ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div style="background: var(--bg-dark); padding: 0.5rem 1rem; border-radius: 12px; border: 1px solid var(--border); display: flex; align-items: center; gap: 0.5rem;">
            <span style="font-size: 0.75rem; color: var(--text-muted);">Tasks:</span>
            <span id="task-count-badge" style="font-weight: 700; color: var(--primary);"><?php echo count($tasks); ?></span>
        </div>
    </div>

    <div class="card" style="padding: 0; overflow: hidden;">

        <div class="table-responsive desktop-only">
            <table class="table">
                <thead>
                    <tr>
                        <th style="width: 100px; padding-left: 1.5rem;">Task ID</th>
                        <th>Production Line</th>
                        <th>Description</th>
                        <th>Schedule</th>
                        <th style="text-align: center;">Status</th>
                        <th>Last Updated</th>
                        <th style="text-align: right; padding-right: 1.5rem;">Action</th>
                    </tr>
                </thead>
                <tbody id="worklist-table-body">
                    <!-- Table rows injected here -->
                </tbody>
            </table>
        </div>

        <div id="worklist-cards-body" class="mobile-only" style="display: none; flex-direction: column; gap: 1rem; padding: 1rem;">
            <!-- Mobile cards injected here -->
        </div>

        <div style="padding: 1.5rem; display: flex; justify-content: space-between; align-items: center; border-top: 1px solid var(--border); background: var(--bg-dark); border-bottom-left-radius: 16px; border-bottom-right-radius: 16px;">
            <div style="font-size: 0.85rem; color: var(--text-muted);" id="pagination-info">
                Showing 1 to 10 of 0 tasks
            </div>
            <div style="display: flex; gap: 0.5rem;" id="pagination-controls">
                <!-- Pagination buttons will be injected here -->
            </div>
        </div>
    </div>
</div>

<script>
    const allTasks = <?php echo json_encode($tasks); ?>;
    let filteredTasks = [...allTasks];
    const itemsPerPage = 10;
    let currentPage = 1;

    function renderWorklist() {
        const tbody = document.getElementById('worklist-table-body');
        const cardsBody = document.getElementById('worklist-cards-body');
        const start = (currentPage - 1) * itemsPerPage;
        const end = start + itemsPerPage;
        const pageTasks = filteredTasks.slice(start, end);
        const today = new Date().toISOString().split('T')[0];
        
        // Render Desktop Table
        tbody.innerHTML = pageTasks.map(task => {
            const statusColor = task.color_code || 'var(--primary)';
            const isCompleted = (task.status || '').toUpperCase() === 'COMPLETED';
            const isLineInactive = !task.line_active;
            const isUpcoming = task.start_date > today;

            return `
                <tr>
                    <td style="font-family: monospace; font-weight: 600; color: var(--text-muted); padding-left: 1.5rem;">#TSK-${String(task.id).padStart(4, '0')}</td>
                    <td>
                        <div style="font-weight: 700; color: var(--text-main);">${task.line_name}</div>
                        <div style="font-size: 0.7rem; color: var(--primary); font-weight: 700; text-transform: uppercase;">
                            <i class="fas fa-industry"></i> ${task.stage_name}
                        </div>
                    </td>
                    <td style="max-width: 250px;">
                        <div style="font-size: 0.85rem; color: var(--text-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;" title="${task.description}">
                            ${task.description || 'No description'}
                        </div>
                    </td>
                    <td>
                        <div style="font-size: 0.85rem; color: var(--text-main); display: flex; align-items: center; gap: 0.5rem;">
                            <i class="far fa-calendar-alt" style="color: var(--primary);"></i>
                            ${formatDateShort(task.start_date)} &rarr; ${formatDateShort(task.due_date)}
                        </div>
                    </td>
                    <td style="text-align: center;">
                        <span style="font-size: 0.65rem; padding: 0.25rem 0.75rem; border-radius: 50px; background: ${statusColor}15; color: ${statusColor}; border: 1px solid ${statusColor}40; font-weight: 800; text-transform: uppercase;">
                            ${task.status}
                        </span>
                    </td>
                    <td style="font-size: 0.85rem; color: var(--text-muted);">
                        ${task.updated_at ? new Date(task.updated_at).toLocaleString('en-US', { month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }) : (task.created_at ? new Date(task.created_at).toLocaleString('en-US', { month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }) : 'Never')}
                    </td>
                    <td style="text-align: right; padding-right: 1.5rem;">
                        ${isCompleted ? `
                            <span style="color: var(--success); font-weight: 700; font-size: 0.85rem; display: inline-flex; align-items: center; gap: 0.4rem;">
                                <i class="fas fa-check-circle"></i> Task Completed
                            </span>
                        ` : (isLineInactive ? `
                            <span style="color: var(--danger); font-size: 0.75rem; font-weight: 700; opacity: 0.8;">
                                <i class="fas fa-exclamation-triangle"></i> Line Inactive
                            </span>
                        ` : (isUpcoming ? `
                            <span style="color: var(--text-muted); font-size: 0.75rem; font-weight: 700; opacity: 0.7;">
                                <i class="far fa-clock"></i> Starts ${formatDateShort(task.start_date)}
                            </span>
                        ` : `
                            <button class="btn btn-primary" onclick="openLogTime(allTasks.find(t => t.id == ${task.id}))" style="padding: 0.4rem 1rem; font-size: 0.8rem; font-weight: 600; border-radius: 8px;">
                                <i class="fas fa-clock"></i> Log Time
                            </button>
                        `))}
                    </td>
                </tr>
            `;
        }).join('');

        // Render Mobile Cards
        cardsBody.innerHTML = pageTasks.map(task => {
            const statusColor = task.color_code || 'var(--primary)';
            const isCompleted = (task.status || '').toUpperCase() === 'COMPLETED';
            const isLineInactive = !task.line_active;
            const isUpcoming = task.start_date > today;

            return `
                <div class="card" style="padding: 1.25rem; border: 1px solid var(--border); background: var(--bg-card); margin-bottom: 0rem; border-left: 4px solid ${isLineInactive ? 'var(--danger)' : (isCompleted ? 'var(--success)' : (isUpcoming ? 'var(--text-muted)' : 'var(--primary)'))};">
                    <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 0.75rem;">
                        <div>
                            <div style="font-family: monospace; font-size: 0.7rem; color: var(--text-muted); font-weight: 700;">#TSK-${String(task.id).padStart(4, '0')}</div>
                            <h3 style="font-size: 1rem; font-weight: 800; color: var(--text-main); margin: 0.2rem 0;">${task.line_name}</h3>
                            <div style="font-size: 0.65rem; color: var(--primary); font-weight: 800; text-transform: uppercase; letter-spacing: 0.5px;">
                                <i class="fas fa-industry"></i> ${task.stage_name}
                            </div>
                        </div>
                        <span style="font-size: 0.6rem; padding: 0.2rem 0.6rem; border-radius: 50px; background: ${statusColor}15; color: ${statusColor}; border: 1px solid ${statusColor}40; font-weight: 800; text-transform: uppercase;">
                            ${task.status}
                        </span>
                    </div>
                    
                    <p style="font-size: 0.8rem; color: var(--text-muted); margin-bottom: 1rem; line-height: 1.4;">${task.description || 'No description provided'}</p>
                    
                    <div style="display: flex; justify-content: space-between; align-items: flex-end; padding-top: 0.75rem; border-top: 1px solid var(--border);">
                        <div>
                            <div style="font-size: 0.55rem; color: var(--text-muted); text-transform: uppercase; font-weight: 800; margin-bottom: 0.2rem;">Schedule</div>
                            <div style="font-size: 0.75rem; color: var(--text-main); font-weight: 700; display: flex; align-items: center; gap: 0.3rem;">
                                <i class="far fa-calendar-alt" style="color: var(--primary);"></i>
                                ${formatDateShort(task.start_date)} - ${formatDateShort(task.due_date)}
                            </div>
                        </div>
                        <div>
                            ${isCompleted ? `
                                <span style="color: var(--success); font-weight: 800; font-size: 0.75rem; display: flex; align-items: center; gap: 0.3rem;">
                                    <i class="fas fa-check-circle"></i> Done
                                </span>
                            ` : (isLineInactive ? `
                                <span style="color: var(--danger); font-size: 0.7rem; font-weight: 800; opacity: 0.8;">
                                    <i class="fas fa-exclamation-triangle"></i> Inactive
                                </span>
                            ` : (isUpcoming ? `
                                <span style="color: var(--text-muted); font-size: 0.7rem; font-weight: 800; opacity: 0.7;">
                                    <i class="far fa-clock"></i> Starts ${formatDateShort(task.start_date)}
                                </span>
                            ` : `
                                <button class="btn btn-primary" onclick="openLogTime(allTasks.find(t => t.id == ${task.id}))" style="padding: 0.4rem 0.8rem; font-size: 0.75rem; font-weight: 700;">
                                    Log Time
                                </button>
                            `))}
                        </div>
                    </div>
                </div>
            `;
        }).join('');

        if (filteredTasks.length === 0) {
            const emptyState = `<div style="text-align: center; padding: 4rem; color: var(--text-muted);"><i class="fas fa-search fa-2x" style="margin-bottom: 1rem; opacity: 0.3;"></i><br>No tasks found matching your criteria.</div>`;
            tbody.innerHTML = `<tr><td colspan="7">${emptyState}</td></tr>`;
            cardsBody.innerHTML = emptyState;
        }

        updatePagination();
    }

    function updatePagination() {
        const totalItems = filteredTasks.length;
        const totalPages = Math.ceil(totalItems / itemsPerPage);
        const start = totalItems === 0 ? 0 : (currentPage - 1) * itemsPerPage + 1;
        const end = Math.min(currentPage * itemsPerPage, totalItems);
        
        document.getElementById('pagination-info').innerText = `Showing ${start} to ${end} of ${totalItems} tasks`;
        document.getElementById('task-count-badge').innerText = totalItems;

        const controls = document.getElementById('pagination-controls');
        let html = '';
        
        if (totalPages > 1) {
            html += `<button class="btn-page" ${currentPage === 1 ? 'disabled' : ''} onclick="goToPage(${currentPage - 1})"><i class="fas fa-chevron-left"></i></button>`;
            
            for (let i = 1; i <= totalPages; i++) {
                if (i === 1 || i === totalPages || (i >= currentPage - 1 && i <= currentPage + 1)) {
                    html += `<button class="btn-page ${i === currentPage ? 'active' : ''}" onclick="goToPage(${i})">${i}</button>`;
                } else if (i === currentPage - 2 || i === currentPage + 2) {
                    html += `<span style="padding: 0 0.5rem; color: var(--text-muted);">...</span>`;
                }
            }
            
            html += `<button class="btn-page" ${currentPage === totalPages ? 'disabled' : ''} onclick="goToPage(${currentPage + 1})"><i class="fas fa-chevron-right"></i></button>`;
        }
        
        controls.innerHTML = html;
    }

    function goToPage(page) {
        currentPage = page;
        renderWorklist();
    }

    function formatDateShort(dateStr) {
        if (!dateStr) return 'N/A';
        const d = new Date(dateStr);
        return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
    }

    // Search and Filter Logic
    function applyFilters() {
        const searchTerm = document.getElementById('worklist-search').value.toLowerCase();
        const statusFilter = document.getElementById('worklist-filter-status').value;

        filteredTasks = allTasks.filter(task => {
            const matchesSearch = 
                String(task.id).includes(searchTerm) || 
                task.title.toLowerCase().includes(searchTerm) || 
                (task.description && task.description.toLowerCase().includes(searchTerm)) ||
                task.line_name.toLowerCase().includes(searchTerm);
            
            const matchesStatus = !statusFilter || task.status === statusFilter;
            
            return matchesSearch && matchesStatus;
        });

        currentPage = 1;
        renderWorklist();
    }

    document.getElementById('worklist-search').addEventListener('input', applyFilters);
    document.getElementById('worklist-filter-status').addEventListener('change', applyFilters);

    // Initial render
    window.addEventListener('DOMContentLoaded', renderWorklist);
</script>

<style>
    .desktop-only { display: block; }
    .mobile-only { display: none; }
    
    @media (max-width: 992px) {
        .desktop-only { display: none; }
        .mobile-only { display: flex !important; }
    }

    .btn-page {
        width: 36px;
        height: 36px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 10px;
        border: 1px solid var(--border);
        background: var(--bg-card);
        color: var(--text-main);
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s;
    }
    .btn-page:hover:not(:disabled) {
        border-color: var(--primary);
        color: var(--primary);
        background: rgba(124, 58, 237, 0.05);
    }
    .btn-page.active {
        background: var(--primary);
        color: white;
        border-color: var(--primary);
        box-shadow: 0 4px 10px rgba(124, 58, 237, 0.3);
    }
    .btn-page:disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }
    .btn-sm {
        padding: 0.25rem 0.75rem;
        font-size: 0.75rem;
    }
</style>

<div id="log-time-view" style="display: none;">
    <div class="card">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
            <div>
                <button class="btn" style="margin-bottom: 1rem; padding: 0.5rem; background: var(--bg-dark);" onclick="closeLogTime()">
                    <i class="fas fa-arrow-left"></i> Back to Work List
                </button>
                <h2 id="log-task-title" style="font-size: 1.5rem; font-weight: 700; color: var(--text-main);">Log Time: Product Name</h2>
                <p id="log-task-subtitle" style="color: var(--text-muted);">Assigned Period: May 06 - May 08, 2026</p>
            </div>
        </div>

        <form id="logTimeForm" enctype="multipart/form-data">
            <input type="hidden" id="log_task_id" name="task_id">
            
            <div class="log-grid" style="display: grid; grid-template-columns: 1fr 1fr; gap: 2rem;">
                <style>
                    @media (max-width: 992px) {
                        .log-grid { grid-template-columns: 1fr !important; gap: 2rem !important; }
                        .log-form-grid { grid-template-columns: 1fr !important; }
                    }
                </style>
                <!-- Left: Entry Form -->
                <div style="background: rgba(255,255,255,0.02); padding: 2rem; border-radius: 20px; border: 1px solid var(--border);">
                    <h3 style="font-size: 1rem; font-weight: 700; margin-bottom: 1.5rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 1px;">Daily Effort Entry</h3>
                    
                    <div class="log-form-grid" style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem;">
                        <div class="form-group">
                            <label class="form-label">Date</label>
                            <input type="text" class="form-control" value="<?php echo date('D, M d, Y'); ?>" readonly style="background: var(--bg-dark); opacity: 0.7;">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Hours Spent</label>
                            <div style="position: relative;">
                                <input type="number" name="hours_spent" class="form-control" step="0.1" placeholder="0.0" style="background: var(--bg-dark); padding-right: 2.5rem;" min="0" max="24" required>
                                <span style="position: absolute; right: 1rem; top: 50%; transform: translateY(-50%); font-size: 0.7rem; color: var(--text-muted);">hrs</span>
                            </div>
                        </div>
                    </div>

                    <div class="form-group" style="margin-top: 1.5rem;">
                        <label class="form-label">Current Status</label>
                        <select id="log_status_id" name="task_status_id" class="form-control" style="background: var(--bg-dark);" required>
                            <?php foreach ($statuses as $s): ?>
                                <option value="<?php echo $s['id']; ?>"><?php echo $s['name']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group" style="margin-top: 1.5rem;">
                        <label class="form-label">Multiple Attachments</label>
                        <div style="border: 2px dashed var(--border); padding: 1.5rem; border-radius: 12px; text-align: center; background: var(--bg-dark);">
                            <i class="fas fa-images fa-2x" style="color: var(--primary); margin-bottom: 1rem; opacity: 0.5;"></i>
                            <input type="file" name="attachments[]" id="attachments" multiple style="display: none;" onchange="updateFileNames(this)">
                            <label for="attachments" class="btn" style="display: block; cursor: pointer; background: var(--bg-card);">Select Files</label>
                            <div id="file-names" style="font-size: 0.75rem; color: var(--text-muted); margin-top: 0.5rem;">No files selected</div>
                        </div>
                    </div>

                    <div class="form-group" style="margin-top: 1.5rem;">
                        <label class="form-label">Progress Notes</label>
                        <textarea name="comments" class="form-control" rows="3" style="background: var(--bg-dark);" placeholder="Describe your progress..."></textarea>
                    </div>

                    <div style="margin-top: 2rem; display: flex; justify-content: flex-end;">
                        <button type="submit" class="btn btn-primary" style="padding: 0.75rem 2.5rem; font-weight: 700; width: 100%;">
                            <i class="fas fa-save" style="margin-right: 0.5rem;"></i> Submit Log
                        </button>
                    </div>
                </div>

                <!-- Right: Log History -->
                <div>
                    <h3 style="font-size: 1rem; font-weight: 700; margin-bottom: 1.5rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 1px;">Log History</h3>
                    <div id="log-history-container" style="max-height: 600px; overflow-y: auto; padding-right: 0.5rem;">
                        <!-- History will be injected here -->
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
function updateFileNames(input) {
    const count = input.files.length;
    document.getElementById('file-names').innerText = count > 0 ? `${count} files selected` : 'No files selected';
}


async function openLogTime(task) {
    document.getElementById('worklist-view').style.display = 'none';
    document.getElementById('log-time-view').style.display = 'block';
    
    document.getElementById('log-task-title').innerText = 'Log Time: ' + task.line_name + ' (' + task.stage_name + ')';
    
    // Format period dates
    const start = new Date(task.start_date).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
    const end = new Date(task.due_date).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
    document.getElementById('log-task-subtitle').innerText = 'Assigned Period: ' + start + ' → ' + end;
    
    document.getElementById('log_task_id').value = task.id;
    
    // Set status
    const statusOptions = Array.from(document.getElementById('log_status_id').options);
    const currentStatus = statusOptions.find(o => o.text.toUpperCase() === task.status.toUpperCase());
    if (currentStatus) document.getElementById('log_status_id').value = currentStatus.value;

    loadLogHistory(task.id);
}

async function loadLogHistory(taskId) {
    const container = document.getElementById('log-history-container');
    container.innerHTML = '<div style="text-align: center; padding: 2rem; color: var(--text-muted);">Loading history...</div>';
    
    const result = await apiCall('tasks', { action: 'get-log-history', task_id: taskId });
    if (result.success) {
        if (result.data.length === 0) {
            container.innerHTML = '<div style="text-align: center; padding: 2rem; color: var(--text-muted); background: var(--bg-dark); border-radius: 12px;">No logs recorded yet.</div>';
            return;
        }
        
        container.innerHTML = result.data.map(log => `
            <div class="card" style="margin-bottom: 0.75rem; border: 1px solid var(--border); background: var(--bg-dark); padding: 0.75rem; border-radius: 12px;">
                <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 0.5rem;">
                    <div>
                        <div style="font-weight: 700; color: var(--text-main); font-size: 0.85rem;">${new Date(log.log_date).toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric' })}</div>
                        <div style="font-size: 0.7rem; color: var(--text-muted); opacity: 0.6;">${new Date(log.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true })}</div>
                    </div>
                    <div style="text-align: right;">
                        <div style="font-weight: 700; color: var(--primary); font-size: 0.9rem;">${log.hours_spent} hrs</div>
                        <span style="font-size: 0.65rem; color: var(--text-muted); text-transform: uppercase; font-weight: 600; letter-spacing: 0.5px;">${log.status_name}</span>
                    </div>
                </div>
                
                ${log.comments ? `<p style="font-size: 0.8rem; color: var(--text-muted); margin-bottom: 0.5rem; padding: 0.5rem; background: rgba(255,255,255,0.03); border-radius: 6px; line-height: 1.3;">${log.comments}</p>` : ''}
                
                <div style="display: flex; justify-content: space-between; align-items: center; gap: 0.5rem;">
                    <div style="display: flex; gap: 0.35rem; flex-wrap: wrap;">
                        ${log.attachments.map(a => `
                            <a href="${a.file_path}" target="_blank" style="font-size: 0.65rem; color: var(--primary); background: rgba(79,70,229,0.1); padding: 0.15rem 0.4rem; border-radius: 4px; text-decoration: none; border: 1px solid rgba(79,70,229,0.2);">
                                <i class="fas fa-paperclip" style="font-size: 0.6rem;"></i> ${a.file_name}
                            </a>
                        `).join('')}
                    </div>
                    
                    ${isToday(log.log_date) ? `
                        <button type="button" class="btn" style="color: var(--danger); padding: 0.2rem 0.4rem; font-size: 0.65rem; background: rgba(239, 68, 68, 0.05); border: none;" onclick="deleteLog(${log.id}, ${taskId})">
                            <i class="fas fa-trash"></i>
                        </button>
                    ` : ''}
                </div>
            </div>
        `).join('');
    }
}

function isToday(dateStr) {
    const today = new Date().toISOString().split('T')[0];
    return dateStr === today;
}

async function deleteLog(logId, taskId) {
    if (await confirmAction({ title: 'Delete Log', message: 'Are you sure? This will permanently remove today\'s entry.', confirmText: 'Delete Log' })) {
        const result = await apiCall('tasks', { action: 'delete-log', log_id: logId });
        if (result.success) {
            notify(result.message);
            loadLogHistory(taskId);
        } else {
            notify(result.message, 'error');
        }
    }
}

function closeLogTime() {
    location.reload();
}

document.getElementById('logTimeForm').onsubmit = async (e) => {
    e.preventDefault();
    const btn = e.target.querySelector('button[type="submit"]');
    const originalBtnHtml = btn.innerHTML;
    
    try {
        // Show loading state
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Uploading & Processing...';
        
        const formData = new FormData(e.target);
        
        // Handle image compression (Parallelized)
        const fileInput = document.getElementById('attachments');
        if (fileInput.files.length > 0) {
            formData.delete('attachments[]'); // Clear original files
            
            // Create an array of compression promises
            const compressionPromises = Array.from(fileInput.files).map(file => compressImage(file));
            
            // Wait for all to complete in parallel
            const compressedFiles = await Promise.all(compressionPromises);
            
            // Append compressed files
            compressedFiles.forEach(compressed => {
                formData.append('attachments[]', compressed);
            });
        }
        
        formData.append('action', 'log-effort');
        
        const taskId = document.getElementById('log_task_id').value;
        const result = await apiCall('tasks', formData);
        if (result.success) {
            notify(result.message);
            e.target.reset();
            document.getElementById('file-names').innerText = 'No files selected';
            loadLogHistory(taskId);
        } else {
            notify(result.message, 'error');
        }
    } catch (err) {
        notify('Compression or Upload failed', 'error');
        console.error(err);
    } finally {
        btn.disabled = false;
        btn.innerHTML = originalBtnHtml;
        btn.classList.remove('btn-loading');
        btn.dataset.submitting = 'false';
    }
};
</script>
