<?php
require_once 'includes/db.php';
$lines = fetchAll("SELECT * FROM production_lines WHERE company_id = ? ORDER BY created_at DESC", [$_SESSION['company_id']]);
$available_products = fetchAll("SELECT p.*, b.name as buyer_name FROM products p LEFT JOIN buyers b ON p.buyer_id = b.id WHERE p.company_id = ? ORDER BY p.name ASC", [$_SESSION['company_id']]);
$workflow_stages = fetchAll("SELECT * FROM workflow_stages WHERE is_active = 1 ORDER BY name ASC");
$all_staff = fetchAll("SELECT e.*, GROUP_CONCAT(s.name) as skill_names FROM employees e LEFT JOIN employee_skill es ON e.id = es.employee_id LEFT JOIN skills s ON es.skill_id = s.id LEFT JOIN roles r ON e.role_id = r.id WHERE e.company_id = ? AND r.name NOT IN ('Owner', 'Manager') GROUP BY e.id ORDER BY e.name ASC", [$_SESSION['company_id']]);
$all_machinery = fetchAll("SELECT * FROM machinery WHERE is_active = 1 ORDER BY name ASC");
?>

<div id="dashboard-view">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2.5rem; background: var(--bg-card); padding: 1rem; border-radius: 20px; border: 1px solid var(--border);">
        <div class="tab-nav" style="display: flex; gap: 0.5rem; background: var(--bg-dark); padding: 0.4rem; border-radius: 14px;">
            <button class="tab-btn active" onclick="switchTab(this, 'in-progress')" style="padding: 0.6rem 1.5rem; border-radius: 10px; border: none; background: transparent; color: var(--text-muted); cursor: pointer; font-weight: 700; font-size: 0.9rem; transition: all 0.3s;">
                <i class="fas fa-spinner fa-spin-pulse"></i> In Progress
            </button>
            <button class="tab-btn" onclick="switchTab(this, 'completed')" style="padding: 0.6rem 1.5rem; border-radius: 10px; border: none; background: transparent; color: var(--text-muted); cursor: pointer; font-weight: 700; font-size: 0.9rem; transition: all 0.3s;">
                <i class="fas fa-check-double"></i> Completed
            </button>
        </div>
        <button class="btn btn-primary" onclick="openAddLineModal()" style="border-radius: 12px; padding: 0.75rem 1.5rem;">
            <i class="fas fa-plus"></i> Initialize Production Line
        </button>
    </div>

    <style>
        .tab-btn.active { background: var(--primary) !important; color: white !important; box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3); }
        .production-tab-content { display: none; }
        .production-tab-content.active { display: grid; }
    </style>

    <div id="in-progress-content" class="data-grid production-tab-content active" style="grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));">
        <?php 
        $hasInProgress = false;
        foreach ($lines as $line): 
            if ($line['status'] === 'Completed') continue;
            $hasInProgress = true;
        ?>
        <?php 
            // Fetch products for this line
            $line_products = fetchAll("SELECT p.id, p.name, lp.quantity FROM production_line_products lp JOIN products p ON lp.product_id = p.id WHERE lp.production_line_id = ?", [$line['id']]);
            $line['products'] = $line_products;
            
            // Fetch stages for this line
            $line_stages = fetchAll("
                SELECT ls.*, ws.name as stage_name, ws.color_code 
                FROM line_stages ls 
                JOIN workflow_stages ws ON ls.workflow_stage_id = ws.id 
                WHERE ls.production_line_id = ? 
                ORDER BY ls.sort_order ASC
            ", [$line['id']]);
            
            // For each stage, fetch staff, machinery and calculated hours
            foreach ($line_stages as &$ls) {
                $ls['staff'] = fetchAll("SELECT e.name, e.profile_picture FROM line_stage_staff lss JOIN employees e ON lss.employee_id = e.id WHERE lss.line_stage_id = ?", [$ls['id']]);
                $ls['machinery'] = fetchAll("SELECT m.name FROM line_stage_machinery lsm JOIN machinery m ON lsm.machinery_id = m.id WHERE lsm.line_stage_id = ?", [$ls['id']]);
                
                // Calculate total hours spent from tasks
                $time_data = fetch("
                    SELECT SUM(tl.hours_spent) as total_hours 
                    FROM tasks t 
                    JOIN task_time_logs tl ON t.id = tl.task_id 
                    WHERE t.line_stage_id = ?
                ", [$ls['id']]);
                $ls['total_hours'] = $time_data['total_hours'] ?? 0;

                // Employee Time Logs with Attachments
                $timelogs = fetchAll("
                    SELECT tl.*, e.name as employee_name, ts.name as status_name 
                    FROM task_time_logs tl 
                    JOIN tasks t ON tl.task_id = t.id 
                    JOIN employees e ON tl.user_id = e.user_id 
                    JOIN task_statuses ts ON tl.task_status_id = ts.id 
                    WHERE t.line_stage_id = ? 
                    ORDER BY tl.created_at DESC
                ", [$ls['id']]);

                foreach ($timelogs as &$log) {
                    $log['attachments'] = fetchAll("SELECT * FROM task_log_attachments WHERE log_id = ?", [$log['id']]);
                }
                $ls['timelogs'] = $timelogs;

                // Manager Updates with Attachments
                $updates = fetchAll("
                    SELECT u.*, e.name as manager_name 
                    FROM line_stage_updates u 
                    JOIN employees e ON u.user_id = e.user_id 
                    WHERE u.line_stage_id = ? 
                    ORDER BY u.created_at DESC
                ", [$ls['id']]);

                foreach ($updates as &$upd) {
                    $upd['attachments'] = fetchAll("SELECT * FROM line_stage_update_attachments WHERE update_id = ?", [$upd['id']]);
                }
                $ls['updates'] = $updates;
            }
            unset($ls); // Crucial to avoid reference bugs
            $line['full_stages'] = $line_stages;
        ?>
        <?php 
            // Check if any stage is blocked
            $blockedStage = null;
            foreach ($line['full_stages'] as $ls) {
                if ($ls['status'] === 'Blocked') {
                    $blockedStage = $ls;
                    break;
                }
            }
            $isBlocked = !empty($blockedStage);
        ?>
        <div class="data-card" style="border-top: 4px solid <?php echo $isBlocked ? 'var(--danger)' : ($line['is_active'] ? 'var(--success)' : 'var(--border)'); ?>; min-height: 220px; display: flex; flex-direction: column; transition: all 0.3s; <?php echo !$line['is_active'] ? 'filter: grayscale(0.4) opacity(0.8);' : ''; ?> <?php echo $isBlocked ? 'box-shadow: 0 0 20px rgba(239, 68, 68, 0.2); border: 1px solid rgba(239, 68, 68, 0.3);' : ''; ?>">
            <div class="data-card-header" style="padding: 1.25rem 1rem; padding-bottom: 0.5rem; display: flex; justify-content: space-between; align-items: flex-start; gap: 1rem;">
                <div style="flex: 1; min-width: 0;">
                    <h3 style="font-size: 1.15rem; font-weight: 800; margin-bottom: 0.35rem; color: var(--text-main); line-height: 1.2; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"><?php echo $line['name']; ?></h3>
                    <div style="display: flex; gap: 0.5rem; align-items: center; flex-wrap: wrap;">
                        <div style="font-size: 0.75rem; font-weight: 800; color: <?php echo $line['status'] === 'Completed' ? 'var(--primary)' : ($line['status'] === 'Blocked' ? 'var(--danger)' : ($line['is_active'] ? 'var(--success)' : 'var(--danger)')); ?>; text-transform: uppercase; letter-spacing: 0.05em; display: flex; align-items: center; gap: 0.3rem;">
                            <i class="fas <?php echo $line['status'] === 'Completed' ? 'fa-flag-checkered' : ($line['status'] === 'Blocked' ? 'fa-exclamation-triangle' : ($line['is_active'] ? 'fa-check-circle' : 'fa-times-circle')); ?>"></i>
                            <?php echo $line['status'] === 'Completed' ? 'COMPLETED' : ($line['status'] === 'Blocked' ? 'BLOCKED' : ($line['is_active'] ? 'ACTIVE' : 'INACTIVE')); ?>
                        </div>
                        <?php if ($isBlocked && $line['status'] !== 'Blocked'): ?>
                            <div class="pulse-red" style="font-size: 0.65rem; font-weight: 900; background: var(--danger); color: white; padding: 0.15rem 0.5rem; border-radius: 6px; letter-spacing: 1px;">BLOCKED</div>
                        <?php endif; ?>
                    </div>
                </div>
                <div style="display: flex; gap: 0.5rem; align-items: center; flex-shrink: 0;">
                    <button class="btn-icon" onclick='deleteProductionLine(<?php echo $line['id']; ?>, "<?php echo addslashes($line['name']); ?>")' title="Delete Production Line" style="background: var(--bg-dark); color: var(--danger); border-radius: 50%; width: 34px; height: 34px; display: flex; align-items: center; justify-content: center; border: 1px solid var(--border); cursor: pointer; transition: all 0.2s;">
                        <i class="fas fa-trash" style="font-size: 0.85rem;"></i>
                    </button>
                    <button class="btn-icon" onclick='viewLine(<?php echo json_encode($line); ?>)' title="View Details" style="background: var(--bg-dark); color: var(--primary); border-radius: 50%; width: 34px; height: 34px; display: flex; align-items: center; justify-content: center; border: 1px solid var(--border); cursor: pointer; transition: all 0.2s;">
                        <i class="fas fa-eye" style="font-size: 0.85rem;"></i>
                    </button>
                    <div class="toggle-switch <?php echo $line['is_active'] ? 'active' : ''; ?>" 
                         onclick="<?php echo $line['status'] === 'Completed' ? 'notify(\'Completed lines cannot be toggled.\', \'warning\')' : 'toggleLineStatus(' . $line['id'] . ', ' . $line['is_active'] . ')'; ?>" 
                         style="cursor: <?php echo $line['status'] === 'Completed' ? 'default' : 'pointer'; ?>; flex-shrink: 0;" 
                         title="<?php echo $line['status'] === 'Completed' ? 'Archived Production' : 'Toggle Operation Status'; ?>">
                        <div style="width: 46px; height: 24px; background: <?php echo $line['status'] === 'Completed' ? 'var(--primary)' : ($line['is_active'] ? 'var(--success)' : 'var(--border)'); ?>; border-radius: 20px; position: relative; transition: all 0.3s; border: 1px solid rgba(255,255,255,0.1); opacity: <?php echo $line['status'] === 'Completed' ? '0.6' : '1'; ?>;">
                            <div style="width: 18px; height: 18px; background: white; border-radius: 50%; position: absolute; top: 2px; left: <?php echo ($line['is_active'] || $line['status'] === 'Completed') ? '24px' : '2px'; ?>; transition: all 0.3s; box-shadow: 0 2px 4px rgba(0,0,0,0.2);"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="data-card-body" style="flex: 1; padding: 0 1rem;">
                <div style="font-size: 0.8rem; color: var(--text-muted); margin-bottom: 1rem; display: flex; align-items: center; gap: 0.5rem;">
                    <i class="far fa-calendar-alt"></i>
                    <?php echo date('M d', strtotime($line['start_date'])); ?> - <?php echo date('M d, Y', strtotime($line['end_date'])); ?>
                </div>

                <div style="margin-bottom: 1rem;">
                    <div style="font-size: 0.65rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 1px; margin-bottom: 0.5rem;">Assigned Products</div>
                    <div style="display: flex; flex-wrap: wrap; gap: 0.3rem;">
                        <?php foreach ($line['products'] as $p): ?>
                            <span onclick="event.stopPropagation(); viewProductDetails(<?php echo $p['id']; ?>)" style="cursor: pointer; font-size: 0.7rem; color: var(--text-main); background: var(--bg-dark); padding: 0.1rem 0.5rem; border-radius: 4px; border: 1px solid var(--border); display: flex; align-items: center; gap: 0.3rem;">
                                <i class="fas fa-shopping-bag" style="font-size: 0.6rem; opacity: 0.5;"></i>
                                <?php echo htmlspecialchars($p['name']); ?> <span style="color: var(--primary); font-weight: 700;">(<?php echo $p['quantity']; ?>)</span>
                            </span>
                        <?php endforeach; ?>
                    </div>
                </div>

                <?php if ($isBlocked): ?>
                    <div style="background: rgba(239, 68, 68, 0.1); border: 1px solid rgba(239, 68, 68, 0.2); border-radius: 12px; padding: 0.75rem; margin-bottom: 1rem;">
                        <div style="font-size: 0.65rem; font-weight: 700; color: var(--danger); text-transform: uppercase; margin-bottom: 0.25rem;">
                            <i class="fas fa-exclamation-triangle"></i> Blocker Reason (<?php echo $blockedStage['stage_name']; ?>)
                        </div>
                        <p style="font-size: 0.75rem; color: var(--text-main); margin: 0; line-height: 1.4; font-style: italic;">
                            "<?php echo $blockedStage['current_status_note'] ?: 'No reason specified'; ?>"
                        </p>
                    </div>
                <?php endif; ?>

                <?php 
                    // Identify current stage
                    $currentStage = null;
                    foreach ($line['full_stages'] as $ls) {
                        if ($ls['status'] !== 'Completed') {
                            $currentStage = $ls;
                            break;
                        }
                    }
                    
                    // If all stages are completed (Final Review state), show the progress of the last stage
                    $displayStage = $currentStage;
                    if (!$currentStage && !empty($line['full_stages'])) {
                        $displayStage = end($line['full_stages']);
                    }

                    $currentPercent = 0;
                    if ($displayStage) {
                        $currentPercent = ($displayStage['completed_units'] / ($displayStage['quantity'] ?: 1)) * 100;
                    }
                ?>

                <div style="margin-bottom: 1rem;">
                    <div style="font-size: 0.65rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 1px; margin-bottom: 0.75rem; display: flex; align-items: center; gap: 0.4rem;">
                        <i class="fas fa-stream" style="font-size: 0.6rem;"></i> Workflow Sequence
                    </div>
                    <div style="display: flex; gap: 0.4rem; flex-wrap: wrap;">
                        <?php foreach ($line['full_stages'] as $ls): ?>
                            <?php 
                                $isCurrent = ($currentStage && $currentStage['id'] === $ls['id']); 
                                $isCompleted = ($ls['status'] === 'Completed');
                                
                                $bg = 'var(--bg-dark)';
                                $border = 'var(--border)';
                                $color = 'var(--text-muted)';
                                $weight = '500';

                                if ($isCurrent) {
                                    $bg = 'rgba(79, 70, 229, 0.05)';
                                    $border = 'var(--primary)';
                                    $color = 'var(--text-main)';
                                    $weight = '700';
                                } elseif ($isCompleted) {
                                    $bg = 'rgba(16, 185, 129, 0.05)';
                                    $border = 'var(--success)';
                                    $color = 'var(--success)';
                                } elseif ($ls['status'] === 'Blocked') {
                                    $border = 'var(--danger)';
                                    $color = 'var(--danger)';
                                }
                            ?>
                            <span style="font-size: 0.7rem; padding: 0.2rem 0.6rem; background: <?php echo $bg; ?>; border-radius: 6px; display: flex; align-items: center; gap: 0.4rem; border: 1px solid <?php echo $border; ?>; color: <?php echo $color; ?>; font-weight: <?php echo $weight; ?>;">
                                <div style="width: 6px; height: 6px; border-radius: 50%; background: <?php echo $ls['status'] === 'Blocked' ? 'var(--danger)' : ($ls['color_code'] ?: 'var(--primary)'); ?>; <?php echo !$line['is_active'] ? 'filter: grayscale(1);' : ''; ?>"></div>
                                <?php echo $ls['stage_name']; ?>
                                <?php if ($isCompleted): ?>
                                    <i class="fas fa-check-circle" style="color: var(--success); font-size: 0.65rem;"></i>
                                <?php endif; ?>
                            </span>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <div class="data-card-footer" style="padding: 0.75rem 1rem; border-top: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; background: <?php echo $line['is_active'] ? 'transparent' : 'rgba(0,0,0,0.05)'; ?>;">
                <div style="display: flex; flex-direction: column; line-height: 1.2;">
                    <div style="font-size: 1.1rem; font-weight: 800; color: <?php echo $isBlocked ? 'var(--danger)' : ($line['is_active'] ? 'var(--success)' : 'var(--text-muted)'); ?>;"><?php echo number_format($currentPercent, 1); ?>%</div>
                    <div style="font-size: 0.55rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.5px; font-weight: 700;">Stage Progress</div>
                </div>
                
                <button class="btn" 
                        style="flex-shrink: 0; background: <?php echo $line['status'] === 'Completed' ? 'rgba(79, 70, 229, 0.05)' : ($isBlocked ? 'var(--danger)' : ($line['is_active'] ? 'var(--primary)' : 'var(--bg-dark)')); ?>; 
                               color: <?php echo $line['status'] === 'Completed' ? 'var(--primary)' : 'white'; ?>; 
                               border: <?php echo $line['status'] === 'Completed' ? '2px solid var(--primary)' : 'none'; ?>; 
                               padding: 0.5rem 1.25rem; border-radius: 12px; font-weight: 700; font-size: 0.85rem; cursor: pointer; display: flex; align-items: center; gap: 0.5rem;" 
                        onclick="openUpdateWorkspace(<?php echo $line['id']; ?>)">
                    <i class="fas <?php echo $line['status'] === 'Completed' ? 'fa-eye' : ($isBlocked ? 'fa-exclamation-circle' : ($line['is_active'] ? 'fa-sync-alt' : 'fa-lock')); ?>"></i> 
                    <?php echo $line['status'] === 'Completed' ? 'View Details' : ($isBlocked ? 'Manage Blocker' : ($line['is_active'] ? 'Update' : 'Locked')); ?>
                </button>
            </div>
        </div>
        <?php endforeach; ?>
        <?php if (!$hasInProgress): ?>
        <div style="grid-column: 1 / -1; text-align: center; padding: 5rem; background: var(--bg-card); border-radius: 24px; border: 2px dashed var(--border);">
            <i class="fas fa-rocket fa-4x" style="color: var(--text-muted); opacity: 0.3; margin-bottom: 1.5rem;"></i>
            <h3 style="color: var(--text-main);">No Active Production Lines</h3>
            <p style="color: var(--text-muted);">Initialize a new line to start tracking production.</p>
        </div>
        <?php endif; ?>
    </div>

    <div id="completed-content" class="data-grid production-tab-content" style="grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));">
        <?php 
        $hasCompleted = false;
        foreach ($lines as $line): 
            if ($line['status'] !== 'Completed') continue;
            $hasCompleted = true;
            // Simplified fetch for completed cards
            $line_products = fetchAll("SELECT p.id, p.name, lp.quantity FROM production_line_products lp JOIN products p ON lp.product_id = p.id WHERE lp.production_line_id = ?", [$line['id']]);
            $line['products'] = $line_products;
            $line_stages = fetchAll("SELECT ls.*, ws.name as stage_name, ws.color_code FROM line_stages ls JOIN workflow_stages ws ON ls.workflow_stage_id = ws.id WHERE ls.production_line_id = ? ORDER BY ls.sort_order ASC", [$line['id']]);
            foreach ($line_stages as &$ls) {
                $ls['staff'] = fetchAll("SELECT e.name, e.profile_picture FROM line_stage_staff lss JOIN employees e ON lss.employee_id = e.id WHERE lss.line_stage_id = ?", [$ls['id']]);
                $ls['machinery'] = fetchAll("SELECT m.name FROM line_stage_machinery lsm JOIN machinery m ON lsm.machinery_id = m.id WHERE lsm.line_stage_id = ?", [$ls['id']]);
                $time_data = fetch("SELECT SUM(tl.hours_spent) as total_hours FROM tasks t JOIN task_time_logs tl ON t.id = tl.task_id WHERE t.line_stage_id = ?", [$ls['id']]);
                $ls['total_hours'] = $time_data['total_hours'] ?? 0;

                // Employee Time Logs with Attachments
                $timelogs = fetchAll("
                    SELECT tl.*, e.name as employee_name, ts.name as status_name 
                    FROM task_time_logs tl 
                    JOIN tasks t ON tl.task_id = t.id 
                    JOIN employees e ON tl.user_id = e.user_id 
                    JOIN task_statuses ts ON tl.task_status_id = ts.id 
                    WHERE t.line_stage_id = ? 
                    ORDER BY tl.created_at DESC
                ", [$ls['id']]);

                foreach ($timelogs as &$log) {
                    $log['attachments'] = fetchAll("SELECT * FROM task_log_attachments WHERE log_id = ?", [$log['id']]);
                }
                $ls['timelogs'] = $timelogs;

                // Manager Updates with Attachments
                $updates = fetchAll("
                    SELECT u.*, e.name as manager_name 
                    FROM line_stage_updates u 
                    JOIN employees e ON u.user_id = e.user_id 
                    WHERE u.line_stage_id = ? 
                    ORDER BY u.created_at DESC
                ", [$ls['id']]);

                foreach ($updates as &$upd) {
                    $upd['attachments'] = fetchAll("SELECT * FROM line_stage_update_attachments WHERE update_id = ?", [$upd['id']]);
                }
                $ls['updates'] = $updates;
            }
            unset($ls);
            $line['full_stages'] = $line_stages;
        ?>
            <div class="data-card" style="border-top: 4px solid var(--primary); min-height: 220px; display: flex; flex-direction: column; transition: all 0.3s; background: rgba(79, 70, 229, 0.02);">
                <div class="data-card-header" style="padding: 1.25rem 1rem; padding-bottom: 0.5rem; display: flex; justify-content: space-between; align-items: flex-start; gap: 1rem;">
                    <div style="flex: 1; min-width: 0;">
                        <h3 style="font-size: 1.15rem; font-weight: 800; margin-bottom: 0.35rem; color: var(--text-main); line-height: 1.2; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"><?php echo $line['name']; ?></h3>
                        <div style="display: flex; gap: 0.5rem; align-items: center;">
                            <div style="font-size: 0.7rem; font-weight: 800; color: var(--primary); text-transform: uppercase; letter-spacing: 0.05em; display: flex; align-items: center; gap: 0.3rem;">
                                <i class="fas fa-flag-checkered"></i> COMPLETED
                            </div>
                        </div>
                    </div>
                    <div style="display: flex; gap: 0.5rem; align-items: center; flex-shrink: 0;">
                        <button class="btn-icon" onclick='deleteProductionLine(<?php echo $line['id']; ?>, "<?php echo addslashes($line['name']); ?>")' title="Delete Production Line" style="background: var(--bg-dark); color: var(--danger); border-radius: 50%; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; border: 1px solid var(--border); cursor: pointer; transition: all 0.2s;">
                            <i class="fas fa-trash" style="font-size: 0.8rem;"></i>
                        </button>
                        <button class="btn-icon" onclick='viewLine(<?php echo json_encode($line); ?>)' title="View Details" style="background: var(--bg-dark); color: var(--primary); border-radius: 50%; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; border: 1px solid var(--border); cursor: pointer; transition: all 0.2s;">
                            <i class="fas fa-eye" style="font-size: 0.8rem;"></i>
                        </button>
                    </div>
                </div>

                <div class="data-card-body" style="flex: 1; padding: 0 1rem;">
                    <div style="font-size: 0.8rem; color: var(--text-muted); margin-bottom: 1rem; display: flex; align-items: center; gap: 0.5rem;">
                        <i class="far fa-calendar-alt"></i>
                        <?php echo date('M d', strtotime($line['start_date'])); ?> - <?php echo date('M d, Y', strtotime($line['end_date'])); ?>
                    </div>
                    <div style="margin-bottom: 1rem;">
                        <div style="font-size: 0.65rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 1px; margin-bottom: 0.5rem;">Assigned Products</div>
                        <div style="display: flex; flex-wrap: wrap; gap: 0.3rem;">
                            <?php foreach ($line['products'] as $p): ?>
                                <span onclick="event.stopPropagation(); viewProductDetails(<?php echo $p['id']; ?>)" style="cursor: pointer; font-size: 0.7rem; color: var(--text-main); background: var(--bg-dark); padding: 0.1rem 0.5rem; border-radius: 4px; border: 1px solid var(--border); display: flex; align-items: center; gap: 0.3rem;">
                                    <i class="fas fa-shopping-bag" style="font-size: 0.6rem; opacity: 0.5;"></i>
                                    <?php echo htmlspecialchars($p['name']); ?> <span style="color: var(--primary); font-weight: 700;">(<?php echo $p['quantity']; ?>)</span>
                                </span>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                <div class="data-card-footer" style="padding: 0.75rem 1rem; border-top: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; background: rgba(0,0,0,0.02);">
                    <div style="display: flex; flex-direction: column; line-height: 1.2;">
                        <div style="font-size: 1.1rem; font-weight: 800; color: var(--primary);">100%</div>
                        <div style="font-size: 0.55rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.5px; font-weight: 700;">Final Progress</div>
                    </div>
                    <button class="btn" style="background: rgba(79, 70, 229, 0.1); color: var(--primary); border-radius: 8px; padding: 0.4rem 1rem; font-size: 0.8rem; font-weight: 700; border: 1px solid var(--primary);" onclick="openUpdateWorkspace(<?php echo $line['id']; ?>)">
                        <i class="fas fa-file-invoice"></i> Audit Summary
                    </button>
                </div>
            </div>
        <?php endforeach; ?>

        <?php if (!$hasCompleted): ?>
        <div style="grid-column: 1 / -1; text-align: center; padding: 5rem; background: var(--bg-card); border-radius: 24px; border: 2px dashed var(--border);">
            <i class="fas fa-archive fa-4x" style="color: var(--text-muted); opacity: 0.3; margin-bottom: 1.5rem;"></i>
            <h3 style="color: var(--text-main);">No Completed Production</h3>
            <p style="color: var(--text-muted);">Finished production lines will appear here for archival and reporting.</p>
        </div>
        <?php endif; ?>
    </div>
</div>

<div id="update-workspace" style="display: none;">
    <div class="card" style="margin-bottom: 2rem; min-height: calc(100vh - 120px); display: flex; flex-direction: column;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
            <div>
                <button class="btn" style="margin-bottom: 0.5rem; padding: 0.5rem 1rem; background: var(--bg-dark); border-radius: 8px;" onclick="closeUpdateWorkspace()">
                    <i class="fas fa-arrow-left"></i> Back to Dashboard
                </button>
                <h2 id="update-line-name" style="font-size: 1.5rem; font-weight: 700; color: var(--text-main);">Line Update: Loading...</h2>
                <p id="update-line-period" style="font-size: 0.85rem; color: var(--text-muted);">Production Period: N/A</p>
                <div id="update-line-products" style="display: flex; flex-wrap: wrap; gap: 0.5rem; margin-top: 0.75rem;"></div>
            </div>
        </div>

        <!-- Stage Progress Indicator -->
        <div id="update-step-indicator" style="display: flex; justify-content: space-between; padding: 1rem 0; border-bottom: 1px solid var(--border); margin-bottom: 2rem; position: sticky; top: 0; background: var(--bg-card); z-index: 10;">
            <!-- Steps will be injected here -->
        </div>

        <div id="stages-update-container" style="flex: 1;">
            <!-- Current stage content will be injected here -->
        </div>
    </div>
</div>

<!-- Setup Workspace (Replacing Dashboard) -->
<div id="setup-view" style="display: none; height: calc(100vh - 120px);">
    <div style="background: var(--bg-card); border-radius: 24px; border: 1px solid var(--border); height: 100%; display: flex; flex-direction: column; overflow: hidden; box-shadow: var(--shadow-xl);">
        <div class="modal-header" style="border-bottom: 1px solid var(--border); flex-shrink: 0;">
            <h2 id="modalTitle">Initialize Production Line</h2>
            <button class="btn" style="background: var(--bg-dark); color: var(--text-muted); border-radius: 50%; width: 40px; height: 40px; padding: 0;" onclick="closeSetupView()">
                <i class="fas fa-times"></i>
            </button>
        </div>
        
        <!-- Step Indicator -->
        <div style="display: flex; justify-content: space-between; padding: 1rem 2rem; background: var(--bg-dark); border-bottom: 1px solid var(--border); flex-shrink: 0;">
            <div class="step-item active" id="step-idx-1">
                <div class="step-num">1</div>
                <div class="step-label">Products</div>
            </div>
            <div class="step-line"></div>
            <div class="step-item" id="step-idx-2">
                <div class="step-num">2</div>
                <div class="step-label">Stages</div>
            </div>
            <div class="step-line"></div>
            <div class="step-item" id="step-idx-3">
                <div class="step-num">3</div>
                <div class="step-label">Resources</div>
            </div>
            <div class="step-line"></div>
            <div class="step-item" id="step-idx-4">
                <div class="step-num">4</div>
                <div class="step-label">Review</div>
            </div>
        </div>

        <div class="setup-body" style="flex: 1; overflow-y: auto; padding: 0;">
            <form id="lineForm">
                <input type="hidden" id="line_id" name="id">
                
                <!-- Step 1: Select Products -->
                <div id="step-1" class="setup-step">
                    <div style="padding: 2rem;">
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; margin-bottom: 2rem;">
                            <div class="form-group" style="grid-column: 1 / -1;">
                                <label class="form-label">Production Line Name <span class="required-mark">*</span></label>
                                <input type="text" id="line_name" name="name" class="form-control" placeholder="e.g. Line A - Denim" required>
                            </div>
                            <div class="form-group">
                                <label class="form-label">Start Date <span class="required-mark">*</span></label>
                                <input type="date" id="line_start_date" name="start_date" class="form-control" required>
                            </div>
                            <div class="form-group">
                                <label class="form-label">End Date <span class="required-mark">*</span></label>
                                <input type="date" id="line_end_date" name="end_date" class="form-control" required>
                            </div>
                        </div>

                        <h4 style="margin-bottom: 1rem; color: var(--text-main); font-size: 0.875rem; text-transform: uppercase; letter-spacing: 0.05em;">Assign Products</h4>
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; height: calc(100vh - 480px); min-height: 250px;">
                            <!-- Available Products -->
                            <div style="display: flex; flex-direction: column; border: 1px solid var(--border); border-radius: 16px; background: var(--bg-dark); overflow: hidden;">
                                <div style="padding: 0.75rem; border-bottom: 1px solid var(--border);">
                                    <input type="text" placeholder="Search products..." oninput="filterAvailableProducts(this.value)" style="width: 100%; background: var(--bg-card); border: 1px solid var(--border); border-radius: 8px; padding: 0.5rem; font-size: 0.875rem; color: var(--text-main);">
                                </div>
                                <div id="available-products-list" style="flex: 1; overflow-y: auto; padding: 0.5rem;">
                                    <?php foreach ($available_products as $product): ?>
                                    <div class="product-item" data-id="<?php echo $product['id']; ?>" data-name="<?php echo htmlspecialchars($product['name']); ?>" data-sku="<?php echo $product['sku']; ?>" onclick="toggleProductSelection(this)">
                                        <div style="font-weight: 600;"><?php echo $product['name']; ?></div>
                                        <div style="font-size: 0.7rem; color: var(--text-muted);"><?php echo $product['sku']; ?> • <?php echo $product['buyer_name']; ?></div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>

                            <!-- Selected Products -->
                            <div style="display: flex; flex-direction: column; border: 1px solid var(--border); border-radius: 16px; background: var(--bg-card); overflow: hidden;">
                                <div style="padding: 0.75rem; background: var(--bg-dark); border-bottom: 1px solid var(--border); font-weight: 700; font-size: 0.875rem; color: var(--primary);">
                                    Selected Products (<span id="selected-count">0</span>)
                                </div>
                                <div id="selected-products-list" style="flex: 1; overflow-y: auto; padding: 0.5rem;">
                                    <div id="no-products-msg" style="padding: 2rem; text-align: center; color: var(--text-muted); font-size: 0.875rem;">
                                        <i class="fas fa-shopping-bag" style="display: block; margin-bottom: 0.5rem; opacity: 0.3; font-size: 1.5rem;"></i>
                                        Click products on the left to add
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Material Requirement & Stock Status -->
                        <div id="material-check-section" style="display: none; margin-top: 1.5rem; border: 1px solid var(--border); border-radius: 16px; background: var(--bg-card); overflow: hidden;">
                            <div style="padding: 0.75rem 1rem; background: var(--bg-dark); border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center;">
                                <div style="font-weight: 700; font-size: 0.875rem; color: var(--text-main);">
                                    <i class="fas fa-microchip" style="margin-right: 0.5rem; color: var(--primary);"></i> 
                                    Material Availability & Stock Status
                                </div>
                                <div id="stock-overall-status"></div>
                            </div>
                            <div id="material-status-list" style="padding: 1rem; max-height: 200px; overflow-y: auto;">
                                <!-- Material requirements will be listed here -->
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Step 2: Select Stages -->
                <div id="step-2" class="setup-step" style="display: none;">
                    <div style="padding: 2rem;">
                        <h4 style="margin-bottom: 1rem; color: var(--text-main); font-size: 0.875rem; text-transform: uppercase; letter-spacing: 0.05em;">Define Workflow Sequence</h4>
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; height: calc(100vh - 420px); min-height: 300px;">
                            <!-- Available Stages -->
                            <div style="display: flex; flex-direction: column; border: 1px solid var(--border); border-radius: 16px; background: var(--bg-dark); overflow: hidden;">
                                <div style="padding: 0.75rem; border-bottom: 1px solid var(--border);">
                                    <input type="text" placeholder="Search stages..." oninput="filterAvailableStages(this.value)" style="width: 100%; background: var(--bg-card); border: 1px solid var(--border); border-radius: 8px; padding: 0.5rem; font-size: 0.875rem; color: var(--text-main);">
                                </div>
                                <div id="available-stages-list" style="flex: 1; overflow-y: auto; padding: 0.5rem;">
                                    <?php foreach ($workflow_stages as $stage): ?>
                                    <div class="stage-item" data-id="<?php echo $stage['id']; ?>" data-name="<?php echo htmlspecialchars($stage['name']); ?>" data-color="<?php echo $stage['color_code']; ?>" onclick="toggleStageSelection(this)">
                                        <div style="display: flex; align-items: center; gap: 0.75rem;">
                                            <div style="width: 10px; height: 10px; border-radius: 50%; background: <?php echo $stage['color_code']; ?>;"></div>
                                            <div style="font-weight: 600;"><?php echo $stage['name']; ?></div>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>

                            <!-- Selected Stages (Sortable UI) -->
                            <div style="display: flex; flex-direction: column; border: 1px solid var(--border); border-radius: 16px; background: var(--bg-card); overflow: hidden;">
                                <div style="padding: 0.75rem; background: var(--bg-dark); border-bottom: 1px solid var(--border); font-weight: 700; font-size: 0.875rem; color: var(--primary);">
                                    Workflow Sequence (<span id="selected-stages-count">0</span>)
                                </div>
                                <div id="selected-stages-list" style="flex: 1; overflow-y: auto; padding: 0.5rem;">
                                    <div id="no-stages-msg" style="padding: 2rem; text-align: center; color: var(--text-muted); font-size: 0.875rem;">
                                        <i class="fas fa-layer-group" style="display: block; margin-bottom: 0.5rem; opacity: 0.3; font-size: 1.5rem;"></i>
                                        Click stages on the left to build sequence
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Step 3: Allocate Resources -->
                <div id="step-3" class="setup-step" style="display: none;">
                    <div style="padding: 2rem;">
                        <h4 style="margin-bottom: 1rem; color: var(--text-main); font-size: 0.875rem; text-transform: uppercase; letter-spacing: 0.05em;">Resource Allocation per Stage</h4>
                        <div id="stage-resources-container" style="display: flex; flex-direction: column; gap: 1.5rem; padding-bottom: 250px;">
                            <!-- Stage forms will be generated here -->
                            <div style="padding: 3rem; text-align: center; color: var(--text-muted);">
                                Please select stages in Step 2 first...
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Step 4: Review -->
                <div id="step-4" class="setup-step" style="display: none;">
                    <div style="padding: 2rem;">
                        <h4 style="margin-bottom: 1rem; color: var(--text-main);">Final Review</h4>
                        <p style="color: var(--text-muted); font-size: 0.875rem; margin-bottom: 1.5rem;">Verify the production line setup before initialization.</p>
                        
                        <div id="setup-summary-container" style="display: flex; flex-direction: column; gap: 1.5rem;">
                            <!-- Header Info -->
                            <div style="background: var(--bg-dark); border-radius: 16px; padding: 1.5rem; display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 1.5rem;">
                                <div>
                                    <div style="font-size: 0.75rem; color: var(--text-muted); margin-bottom: 0.25rem;">Line Name</div>
                                    <div id="summary-name" style="font-weight: 700; color: var(--primary); font-size: 1.1rem;">N/A</div>
                                </div>
                                <div>
                                    <div style="font-size: 0.75rem; color: var(--text-muted); margin-bottom: 0.25rem;">Start Date</div>
                                    <div id="summary-start" style="font-weight: 600;">N/A</div>
                                </div>
                                <div>
                                    <div style="font-size: 0.75rem; color: var(--text-muted); margin-bottom: 0.25rem;">End Date</div>
                                    <div id="summary-end" style="font-weight: 600;">N/A</div>
                                </div>
                            </div>

                            <!-- Products -->
                            <div style="background: var(--bg-dark); border-radius: 16px; padding: 1.5rem;">
                                <div style="font-size: 0.75rem; color: var(--text-muted); margin-bottom: 0.75rem; text-transform: uppercase; font-weight: 700;">Assigned Products</div>
                                <div id="summary-products" style="display: flex; flex-wrap: wrap; gap: 0.5rem;"></div>
                            </div>

                            <!-- Workflow & Resources -->
                            <div style="background: var(--bg-dark); border-radius: 16px; padding: 1.5rem;">
                                <div style="font-size: 0.75rem; color: var(--text-muted); margin-bottom: 1rem; text-transform: uppercase; font-weight: 700;">Workflow & Resource Allocation</div>
                                <div id="summary-workflow-detailed" style="display: flex; flex-direction: column; gap: 1rem;"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
        <div class="modal-footer" style="background: var(--bg-dark); border-top: 1px solid var(--border); flex-shrink: 0;">
            <button type="button" class="btn" style="background: var(--glass-bg);" onclick="closeSetupView()">Cancel</button>
            <button type="button" class="btn" id="prevBtn" style="display: none; background: var(--glass-bg); margin-left: 0.5rem;" onclick="changeStep(-1)">Previous</button>
            <div style="flex: 1;"></div>
            <button type="button" class="btn btn-primary" id="nextBtn" onclick="changeStep(1)">Next</button>
            <button type="button" class="btn btn-primary" id="finishBtn" style="display: none;" onclick="finishSetup()">Initialize Production Line</button>
        </div>
    </div>
</div>

<!-- View Line Details Modal (Same as dashboard.php) -->
<div id="viewLineModal" class="modal-overlay">
    <div class="modal-content" style="width: 900px; max-width: 95vw; background: var(--bg-card); border-radius: 24px;">
        <div class="modal-header" style="border-bottom: 1px solid var(--border); padding: 1.5rem 2rem;">
            <h2 id="viewModalTitle" style="font-weight: 800; font-size: 1.5rem;">Production Line Details</h2>
            <button class="btn-icon" style="background: var(--bg-dark); color: var(--text-muted); border-radius: 50%; width: 36px; height: 36px;" onclick="closeModal('viewLineModal')">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div class="modal-body" style="padding: 2rem; max-height: 80vh; overflow-y: auto;">
            <div id="view-summary-container" style="display: flex; flex-direction: column; gap: 1.5rem;">
                <!-- Streamlined Header Row -->
                <div style="background: var(--bg-dark); border-radius: 16px; padding: 1.25rem 1.5rem; display: flex; flex-wrap: wrap; align-items: center; gap: 1.5rem; border: 1px solid var(--border);">
                    <div style="display: flex; flex-wrap: wrap; gap: 1.5rem; align-items: center; flex: 1;">
                        <div style="min-width: 120px;">
                            <div style="font-size: 0.55rem; color: var(--text-muted); margin-bottom: 0.2rem; text-transform: uppercase; font-weight: 800; letter-spacing: 0.5px;">Production Line</div>
                            <div id="view-summary-name" style="font-weight: 800; color: var(--primary); font-size: 1.1rem; letter-spacing: -0.5px;"></div>
                        </div>
                        <div style="min-width: 200px;">
                            <div style="font-size: 0.55rem; color: var(--text-muted); margin-bottom: 0.2rem; text-transform: uppercase; font-weight: 800; letter-spacing: 0.5px;">Operational Timeline</div>
                            <div style="font-weight: 700; color: var(--text-main); font-size: 0.85rem; white-space: nowrap;">
                                <span id="view-summary-start"></span> <i class="fas fa-long-arrow-alt-right" style="margin: 0 0.4rem; color: var(--text-muted); font-size: 0.7rem;"></i> <span id="view-summary-end"></span>
                            </div>
                        </div>
                    </div>
                    <div style="flex: 2; min-width: 250px; border-left: 1px solid var(--border); padding-left: 1.5rem;" class="products-header-col">
                        <style>
                            @media (max-width: 768px) {
                                .products-header-col { border-left: none !important; padding-left: 0 !important; border-top: 1px solid var(--border); padding-top: 1rem !important; }
                            }
                        </style>
                        <div style="font-size: 0.55rem; color: var(--text-muted); margin-bottom: 0.4rem; text-transform: uppercase; font-weight: 800; letter-spacing: 0.5px;">Assigned Products & Targets</div>
                        <div id="view-summary-products" style="display: flex; flex-wrap: wrap; gap: 0.4rem;"></div>
                    </div>
                </div>

                <div style="background: var(--bg-dark); border-radius: 16px; padding: 1.5rem; border: 1px solid var(--border);">
                    <div style="font-size: 0.6rem; color: var(--text-muted); margin-bottom: 1.25rem; text-transform: uppercase; font-weight: 800;">Workflow & Resource Allocation</div>
                    <div id="view-summary-workflow-detailed"></div>
                </div>
            </div>
        </div>
        <div class="modal-footer" style="background: var(--bg-dark); border-top: 1px solid var(--border); padding: 1.5rem 2rem; border-bottom-left-radius: 24px; border-bottom-right-radius: 24px; justify-content: flex-end;">
            <button class="btn btn-primary" onclick="closeModal('viewLineModal')">Close</button>
        </div>
    </div>
</div>

<!-- Product Quick View Modal -->
<div id="productViewModal" class="modal-overlay">
    <div class="modal-content" style="width: 750px; max-width: 95vw; background: var(--bg-card); border-radius: 24px;">
        <div class="modal-header" style="border-bottom: 1px solid var(--border); padding: 1.5rem 2rem;">
            <h2 style="font-weight: 800; font-size: 1.5rem; display: flex; align-items: center; gap: 0.75rem;">
                <i class="fas fa-shopping-bag" style="color: var(--primary);"></i>
                Product Details
            </h2>
            <button class="btn-icon" style="background: var(--bg-dark); color: var(--text-muted); border-radius: 50%; width: 36px; height: 36px;" onclick="closeModal('productViewModal')">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div class="modal-body" id="product-view-body" style="padding: 2rem; max-height: 70vh; overflow-y: auto;">
            <div style="text-align: center; padding: 3rem;"><i class="fas fa-spinner fa-spin fa-2x"></i></div>
        </div>
    </div>
</div>

<style>
.status-badge { padding: 0.3rem 0.8rem; border-radius: 20px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; }
.status-badge.active { background: rgba(16, 185, 129, 0.1); color: var(--success); }
.status-badge.inactive { background: rgba(107, 114, 128, 0.1); color: var(--text-muted); }
.step-item { display: flex; align-items: center; gap: 0.75rem; opacity: 0.4; transition: all 0.3s; }
.step-item.active { opacity: 1; }
.step-num { width: 36px; height: 36px; border-radius: 50%; background: var(--primary); color: white; display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: 1rem; z-index: 2; }
.step-line { flex: 1; height: 2px; background: var(--border); margin: 15px -10px 0; z-index: 1; }
.step-item.active .step-num { box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.2); }
.step-label { font-weight: 700; font-size: 0.95rem; color: var(--text-main); white-space: nowrap; }
.setup-step { min-height: 500px; }

.product-item, .stage-item {
    padding: 0.75rem;
    border-radius: 10px;
    margin-bottom: 0.5rem;
    cursor: pointer;
    transition: all 0.2s;
    border: 1px solid transparent;
}
.product-item:hover, .stage-item:hover {
    background: var(--bg-card);
    border-color: var(--border);
}
.stage-item { background: var(--bg-card); border: 1px solid var(--border); }

.resource-stage-card { background: var(--bg-card); border: 1px solid var(--border); border-radius: 16px; position: relative; }
.resource-stage-header { padding: 0.75rem 1.5rem; border-bottom: 1px solid var(--border); }
.resource-search-results {
    position: absolute; top: 100%; left: 0; right: 0; background: var(--bg-card); 
    border: 1px solid var(--border); border-radius: 8px; z-index: 1000; display: none;
    max-height: 200px; overflow-y: auto; box-shadow: var(--shadow-xl); padding: 0.5rem;
}
.search-result-item {
    padding: 0.75rem 1rem; border-radius: 8px; cursor: pointer; transition: all 0.2s;
    border: 1px solid transparent; margin-bottom: 0.25rem;
}
.search-result-item:hover {
    background: var(--bg-dark); border-color: var(--primary); transform: translateX(5px);
}
.resource-tag {
    display: inline-flex; align-items: center; gap: 0.5rem; padding: 0.4rem 0.8rem; 
    background: var(--bg-dark); border: 1px solid var(--border); border-radius: 20px;
    font-size: 0.75rem; margin: 0.25rem; box-shadow: var(--shadow-sm);
}
.resource-tag.machine { border-color: var(--accent); color: var(--accent); }
.resource-tag i { cursor: pointer; color: var(--danger); }
.pulse-red {
    animation: pulse-red-anim 2s infinite;
    box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7);
}
@keyframes pulse-red-anim {
    0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7); }
    70% { transform: scale(1); box-shadow: 0 0 0 10px rgba(239, 68, 68, 0); }
    100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(239, 68, 68, 0); }
}
</style>

<script>
function formatDate(dateStr) {
    if (!dateStr) return 'N/A';
    const options = { year: 'numeric', month: 'long', day: 'numeric' };
    try {
        return new Date(dateStr).toLocaleDateString(undefined, options);
    } catch (e) {
        return dateStr;
    }
}

let currentStep = 1;

async function changeStep(n) {
    // Step validation
    if (n === 1) {
        if (currentStep === 1) {
            const name = document.getElementById('line_name').value;
            const start = document.getElementById('line_start_date').value;
            const end = document.getElementById('line_end_date').value;
            const productCount = document.querySelectorAll('#selected-products-list .product-item').length;

            if (!name || !start || !end) {
                notify('Please fill all mandatory fields', 'warning');
                return;
            }
            if (productCount === 0) {
                notify('Please select at least one product', 'warning');
                return;
            }
            if (!isStockSufficient) {
                const proceed = await confirmAction({
                    title: 'Insufficient Stock',
                    message: 'Some materials have insufficient stock for the selected production quantity. Would you like to proceed with initialization anyway?',
                    confirmText: 'Proceed Anyway',
                    confirmClass: 'var(--warning)'
                });
                if (!proceed) return;
            }
        } else if (currentStep === 2) {
            const stageCount = document.querySelectorAll('#selected-stages-list .stage-item').length;
            if (stageCount === 0) {
                notify('Please define at least one production stage', 'warning');
                return;
            }
        } else if (currentStep === 3) {
            const unitInputs = document.querySelectorAll('.stage-units');
            let allFilled = true;
            unitInputs.forEach(input => {
                if (!input.value || input.value <= 0) {
                    allFilled = false;
                    input.style.borderColor = 'var(--danger)';
                } else {
                    input.style.borderColor = 'var(--border)';
                }
            });
            if (!allFilled) {
                notify('Please specify units to complete for all stages', 'warning');
                return;
            }
        }
    }

    document.getElementById(`step-${currentStep}`).style.display = 'none';
    document.getElementById(`step-idx-${currentStep}`).classList.remove('active');
    
    currentStep += n;
    
    document.getElementById(`step-${currentStep}`).style.display = 'block';
    document.getElementById(`step-idx-${currentStep}`).classList.add('active');
    
    // Step specific logic
    if (currentStep === 3) {
        generateStageResourceForms();
    }

    // Summary update
    if (currentStep === 4) {
        document.getElementById('summary-name').innerText = document.getElementById('line_name').value;
        document.getElementById('summary-start').innerText = formatDate(document.getElementById('line_start_date').value);
        document.getElementById('summary-end').innerText = formatDate(document.getElementById('line_end_date').value);
        
        // Products summary
        const products = Array.from(document.querySelectorAll('#selected-products-list .product-item'))
            .map(p => {
                const qty = p.querySelector('.product-qty')?.value || '0';
                return `<span class="resource-tag" style="cursor: pointer; background: var(--bg-card);" onclick="viewProductDetails(${p.dataset.id})"><i class="fas fa-shopping-bag" style="font-size: 0.7rem; opacity: 0.5;"></i> ${p.dataset.name} (${qty} units)</span>`;
            })
            .join('');
        document.getElementById('summary-products').innerHTML = products || '<span style="color: var(--text-muted);">No products selected</span>';

        // Detailed Workflow summary
        const stageCards = Array.from(document.querySelectorAll('.resource-stage-card'));
        const detailedWorkflow = stageCards.map((card, idx) => {
            const stageName = card.querySelector('.resource-stage-header div').innerText;
            const start = formatDate(card.querySelector('.stage-start-date').value);
            const end = formatDate(card.querySelector('.stage-end-date').value);
            const units = card.querySelector('.stage-units').value || 'N/A';
            const remarks = card.querySelector('.stage-remarks').value || 'None';
            
            const staff = Array.from(card.querySelectorAll('[data-staff-id]')).map(s => s.innerHTML.replace('<i class="fas fa-times" onclick="this.parentElement.remove()" style="margin-left: 0.3rem;"></i>', '')).join(' ');
            const machinery = Array.from(card.querySelectorAll('[data-machine-id]')).map(m => m.innerHTML.replace('<i class="fas fa-times" onclick="this.parentElement.remove()" style="margin-left: 0.3rem;"></i>', '')).join(' ');

            return `
                <div style="padding: 1rem; border: 1px solid var(--border); border-radius: 12px; background: var(--bg-card);">
                    <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 0.75rem;">
                        <div style="font-weight: 700; color: var(--text-main);">${stageName}</div>
                        <div style="font-size: 0.75rem; color: var(--text-muted); font-weight: 600;">${start} → ${end}</div>
                    </div>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                        <div>
                            <div style="font-size: 0.65rem; color: var(--text-muted); text-transform: uppercase; margin-bottom: 0.25rem;">Resources</div>
                            <div style="display: flex; flex-wrap: wrap; gap: 0.3rem;">
                                ${staff || '<span style="font-size: 0.75rem; color: var(--text-muted);">No staff assigned</span>'}
                                ${machinery || ''}
                            </div>
                        </div>
                        <div style="text-align: right;">
                            <div style="font-size: 0.65rem; color: var(--text-muted); text-transform: uppercase; margin-bottom: 0.25rem;">Target & Remarks</div>
                            <div style="font-size: 0.8rem; font-weight: 600;">Target: ${units} units</div>
                            <div style="font-size: 0.7rem; color: var(--text-muted); font-style: italic;">"${remarks}"</div>
                        </div>
                    </div>
                </div>
            `;
        }).join('');
        
        document.getElementById('summary-workflow-detailed').innerHTML = detailedWorkflow || '<span style="color: var(--text-muted);">No resources allocated yet. Save as draft or complete Step 3.</span>';
    }

function formatDate(dateStr) {
    if (!dateStr) return 'N/A';
    const options = { year: 'numeric', month: 'long', day: 'numeric' };
    return new Date(dateStr).toLocaleDateString(undefined, options);
}

    // Button visibility
    document.getElementById('prevBtn').style.display = currentStep > 1 ? 'block' : 'none';
    document.getElementById('nextBtn').style.display = currentStep < 4 ? 'block' : 'none';
    document.getElementById('finishBtn').style.display = currentStep === 4 ? 'block' : 'none';
}

const allStaff = <?php echo json_encode($all_staff); ?>;
const allMachinery = <?php echo json_encode($all_machinery); ?>;

function generateStageResourceForms() {
    const container = document.getElementById('stage-resources-container');
    const selectedStages = Array.from(document.querySelectorAll('#selected-stages-list .stage-item'));
    
    // 1. Map existing cards by stageId to preserve them
    const existingCards = {};
    container.querySelectorAll('.resource-stage-card').forEach(card => {
        existingCards[card.dataset.stageId] = card;
    });
    
    // 2. Create fragment to hold the re-ordered/new cards
    const fragment = document.createDocumentFragment();
    
    selectedStages.forEach((s, idx) => {
        const stageId = s.dataset.id;
        let card;
        
        if (existingCards[stageId]) {
            card = existingCards[stageId];
            // Update the index/title (e.g. "1. Cutting" -> "2. Cutting" if re-ordered)
            card.querySelector('.resource-stage-header div').innerText = `${idx + 1}. ${s.dataset.name}`;
            delete existingCards[stageId]; // Mark as kept
        } else {
            // Create new card
            const div = document.createElement('div');
            div.className = 'resource-stage-card';
            div.dataset.stageId = stageId;
            div.innerHTML = `
                <div class="resource-stage-header" style="background: ${s.dataset.color}15; border-left: 4px solid ${s.dataset.color};">
                    <div style="font-weight: 700; color: var(--text-main);">${idx + 1}. ${s.dataset.name}</div>
                </div>
                <div style="padding: 1.5rem; display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem;">
                    <!-- Dates & Units -->
                    <div style="display: flex; flex-direction: column; gap: 1rem;">
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                            <div class="form-group">
                                <label class="form-label">Start Date *</label>
                                <input type="date" class="form-control stage-start-date" required value="${document.getElementById('line_start_date').value}">
                            </div>
                            <div class="form-group">
                                <label class="form-label">End Date *</label>
                                <input type="date" class="form-control stage-end-date" required value="${document.getElementById('line_end_date').value}">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Units to Complete *</label>
                            <input type="number" class="form-control stage-units" placeholder="e.g. 1000" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Special Remarks</label>
                            <textarea class="form-control stage-remarks" rows="2" placeholder="Instructions..."></textarea>
                        </div>
                    </div>

                    <!-- Staff & Machinery -->
                    <div style="display: flex; flex-direction: column; gap: 1rem;">
                        <div class="form-group">
                            <label class="form-label">Allocate Staff (Search by Skill)</label>
                            <div style="position: relative;">
                                <input type="text" class="form-control" placeholder="Search staff..." oninput="searchStaff(this, ${stageId})">
                                <div class="resource-search-results staff-results-${stageId}"></div>
                            </div>
                            <div class="allocated-list staff-list-${stageId}"></div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Allocate Machinery</label>
                            <div style="position: relative;">
                                <input type="text" class="form-control" placeholder="Search machinery..." oninput="searchMachinery(this, ${stageId})">
                                <div class="resource-search-results machine-results-${stageId}"></div>
                            </div>
                            <div class="allocated-list machine-list-${stageId}"></div>
                        </div>
                    </div>
                </div>
            `;
            card = div;
        }
        fragment.appendChild(card);
    });
    
    // 3. Clear container and append fragment
    container.innerHTML = '';
    container.appendChild(fragment);
}

function searchStaff(input, stageId) {
    const query = input.value.toLowerCase();
    const results = document.querySelector(`.staff-results-${stageId}`);
    if (!query) { results.style.display = 'none'; return; }
    
    const filtered = allStaff.filter(s => 
        s.name.toLowerCase().includes(query) || 
        (s.skill_names && s.skill_names.toLowerCase().includes(query))
    );
    
    results.innerHTML = filtered.map(s => {
        const avatar = s.profile_picture 
            ? `<img src="${s.profile_picture}" style="width: 24px; height: 24px; border-radius: 50%; object-fit: cover;">`
            : `<div class="user-avatar" style="width: 24px; height: 24px; font-size: 0.7rem;">${s.name.charAt(0)}</div>`;
            
        return `
            <div class="search-result-item" style="display: flex; align-items: center; gap: 0.75rem;" onclick="allocateStaff(${stageId}, ${s.id}, '${s.name.replace(/'/g, "\\'")}', '${s.profile_picture || ''}')">
                ${avatar}
                <div style="flex: 1;">
                    <div style="font-weight: 600; color: var(--text-main); font-size: 0.85rem;">${s.name}</div>
                    <div style="font-size: 0.65rem; color: var(--text-muted);">${s.skill_names || 'No skills'}</div>
                </div>
            </div>
        `;
    }).join('');
    results.style.display = 'block';
}

function allocateStaff(stageId, staffId, staffName, profilePic) {
    const list = document.querySelector(`.staff-list-${stageId}`);
    if (list.querySelector(`[data-staff-id="${staffId}"]`)) return;
    
    const avatar = profilePic 
        ? `<img src="${profilePic}" style="width: 18px; height: 18px; border-radius: 50%; object-fit: cover;">`
        : `<i class="fas fa-user" style="font-size: 0.7rem; opacity: 0.5;"></i>`;

    const tag = document.createElement('div');
    tag.className = 'resource-tag';
    tag.dataset.staffId = staffId;
    tag.innerHTML = `
        ${avatar}
        <span>${staffName}</span>
        <i class="fas fa-times" onclick="this.parentElement.remove()" style="margin-left: 0.3rem;"></i>
    `;
    list.appendChild(tag);
    document.querySelector(`.staff-results-${stageId}`).style.display = 'none';
    document.querySelector(`.staff-results-${stageId}`).previousElementSibling.value = '';
}

function searchMachinery(input, stageId) {
    const query = input.value.toLowerCase();
    const results = document.querySelector(`.machine-results-${stageId}`);
    if (!query) { results.style.display = 'none'; return; }
    
    const filtered = allMachinery.filter(m => m.name.toLowerCase().includes(query));
    
    results.innerHTML = filtered.map(m => `
        <div class="search-result-item" onclick="allocateMachine(${stageId}, ${m.id}, '${m.name.replace(/'/g, "\\'")}')">
            <div style="font-weight: 600; color: var(--text-main);">${m.name}</div>
            <div style="font-size: 0.7rem; color: var(--text-muted);">${m.model_no || 'N/A'}</div>
        </div>
    `).join('');
    results.style.display = 'block';
}

function allocateMachine(stageId, machineId, machineName) {
    const list = document.querySelector(`.machine-list-${stageId}`);
    if (list.querySelector(`[data-machine-id="${machineId}"]`)) return;
    
    const tag = document.createElement('div');
    tag.className = 'resource-tag machine';
    tag.dataset.machineId = machineId;
    tag.innerHTML = `
        <i class="fas fa-cog" style="font-size: 0.7rem; opacity: 0.5;"></i>
        <span>${machineName}</span>
        <i class="fas fa-times" onclick="this.parentElement.remove()" style="margin-left: 0.3rem;"></i>
    `;
    list.appendChild(tag);
    document.querySelector(`.machine-results-${stageId}`).style.display = 'none';
    document.querySelector(`.machine-results-${stageId}`).previousElementSibling.value = '';
}

function toggleStageSelection(el) {
    const stageId = el.dataset.id;
    const isSelected = el.closest('#selected-stages-list');
    
    if (isSelected) {
        el.remove();
    } else {
        const clone = el.cloneNode(true);
        clone.innerHTML += `
            <div style="margin-left: auto; display: flex; gap: 0.5rem;">
                <button type="button" class="btn" style="padding: 0.2rem 0.4rem; background: var(--bg-dark);" onclick="event.stopPropagation(); moveStage(this, -1)"><i class="fas fa-chevron-up"></i></button>
                <button type="button" class="btn" style="padding: 0.2rem 0.4rem; background: var(--bg-dark);" onclick="event.stopPropagation(); moveStage(this, 1)"><i class="fas fa-chevron-down"></i></button>
                <button type="button" class="btn" style="padding: 0.2rem 0.4rem; background: rgba(239, 68, 68, 0.1); color: var(--danger);" onclick="event.stopPropagation(); this.closest('.stage-item').remove(); updateStagesCount()"><i class="fas fa-trash"></i></button>
            </div>
        `;
        clone.onclick = null;
        document.getElementById('selected-stages-list').appendChild(clone);
    }
    
    updateStagesCount();
}

function moveStage(btn, direction) {
    const item = btn.closest('.stage-item');
    if (direction === -1 && item.previousElementSibling && !item.previousElementSibling.id) {
        item.parentNode.insertBefore(item, item.previousElementSibling);
    } else if (direction === 1 && item.nextElementSibling) {
        item.parentNode.insertBefore(item.nextElementSibling, item);
    }
}

function updateStagesCount() {
    const list = document.getElementById('selected-stages-list');
    const count = list.querySelectorAll('.stage-item').length;
    document.getElementById('selected-stages-count').innerText = count;
    document.getElementById('no-stages-msg').style.display = count > 0 ? 'none' : 'block';
}

let isStockSufficient = true;
async function calculateMaterialRequirement() {
    const list = document.querySelectorAll('#selected-products-list .product-item');
    const products = Array.from(list).map(p => ({
        id: p.dataset.id,
        quantity: p.querySelector('.product-qty').value
    }));

    if (products.length === 0) {
        document.getElementById('material-check-section').style.display = 'none';
        isStockSufficient = true;
        return;
    }

    const section = document.getElementById('material-check-section');
    const listContainer = document.getElementById('material-status-list');
    const statusHeader = document.getElementById('stock-overall-status');
    
    section.style.display = 'block';
    listContainer.innerHTML = '<div style="text-align: center; color: var(--text-muted);"><i class="fas fa-spinner fa-spin"></i> Checking inventory...</div>';

    try {
        const result = await apiCall('production-lines', { action: 'check-stock', products: products });
        if (result.success) {
            isStockSufficient = result.sufficient;
            
            // Update header status
            statusHeader.innerHTML = result.sufficient 
                ? '<span style="color: var(--success); font-size: 0.7rem; font-weight: 800;"><i class="fas fa-check-circle"></i> STOCK AVAILABLE</span>'
                : '<span style="color: var(--danger); font-size: 0.7rem; font-weight: 800;"><i class="fas fa-exclamation-triangle"></i> INSUFFICIENT STOCK</span>';

            // Update list
            if (result.materials.length === 0) {
                listContainer.innerHTML = '<div style="text-align: center; color: var(--text-muted); font-size: 0.8rem;">No material requirements defined for selected products.</div>';
            } else {
                listContainer.innerHTML = result.materials.map(m => {
                    const isShort = m.shortage > 0;
                    return `
                        <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.5rem 0; border-bottom: 1px solid rgba(255,255,255,0.05);">
                            <div style="flex: 1;">
                                <div style="font-size: 0.85rem; font-weight: 600; color: ${isShort ? 'var(--danger)' : 'var(--text-main)'};">${m.name}</div>
                                <div style="font-size: 0.7rem; color: var(--text-muted);">Required: ${m.required.toFixed(2)} ${m.unit} | Available: ${m.available.toFixed(2)} ${m.unit}</div>
                            </div>
                            ${isShort ? `
                                <div style="text-align: right;">
                                    <div style="color: var(--danger); font-weight: 800; font-size: 0.85rem;">- ${m.shortage.toFixed(2)} ${m.unit}</div>
                                    <div style="font-size: 0.6rem; color: var(--text-muted); text-transform: uppercase;">Shortage</div>
                                </div>
                            ` : `
                                <div style="color: var(--success); font-size: 1rem;"><i class="fas fa-check"></i></div>
                            `}
                        </div>
                    `;
                }).join('');
            }
        }
    } catch (error) {
        console.error('Stock check failed:', error);
        listContainer.innerHTML = '<div style="color: var(--danger); font-size: 0.8rem;">Failed to verify stock.</div>';
    }
}

function filterAvailableStages(query) {
    const items = document.querySelectorAll('#available-stages-list .stage-item');
    items.forEach(item => {
        const text = item.innerText.toLowerCase();
        item.style.display = text.includes(query.toLowerCase()) ? 'block' : 'none';
    });
}

function toggleProductSelection(el) {
    const productId = el.dataset.id;
    const productName = el.dataset.name;
    const productSku = el.dataset.sku;
    const isSelected = el.closest('#selected-products-list');
    
    if (isSelected) {
        // Remove from selected
        const originalItem = document.querySelector(`#available-products-list .product-item[data-id="${productId}"]`);
        if (originalItem) originalItem.style.display = 'block';
        el.remove();
    } else {
        // Add to selected
        const clone = el.cloneNode(false);
        clone.onclick = null;
        clone.innerHTML = `
            <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                <div style="flex: 1;">
                    <div style="font-weight: 600;">${productName}</div>
                    <div style="font-size: 0.7rem; color: var(--text-muted);">${productSku}</div>
                </div>
                <div style="display: flex; align-items: center; gap: 0.5rem;">
                    <input type="number" class="form-control product-qty" data-product-id="${productId}" oninput="calculateMaterialRequirement()" placeholder="Qty" style="width: 80px; padding: 0.2rem 0.5rem; font-size: 0.8rem; background: var(--bg-dark);" min="1" value="100">
                    <button type="button" class="btn" style="padding: 0.2rem 0.4rem; color: var(--danger);" onclick="toggleProductSelection(this.closest('.product-item'))"><i class="fas fa-trash"></i></button>
                </div>
            </div>
        `;
        document.getElementById('selected-products-list').appendChild(clone);
        el.style.display = 'none';
    }
    
    updateSelectedCount();
    calculateMaterialRequirement();
}

function updateSelectedCount() {
    const list = document.getElementById('selected-products-list');
    const count = list.querySelectorAll('.product-item').length;
    document.getElementById('selected-count').innerText = count;
    document.getElementById('no-products-msg').style.display = count > 0 ? 'none' : 'block';
}

function filterAvailableProducts(query) {
    const items = document.querySelectorAll('#available-products-list .product-item');
    items.forEach(item => {
        const text = item.innerText.toLowerCase();
        item.style.display = text.includes(query.toLowerCase()) ? 'block' : 'none';
    });
}

function openAddLineModal() {
    document.getElementById('dashboard-view').style.display = 'none';
    document.getElementById('setup-view').style.display = 'block';
    
    currentStep = 1;
    document.getElementById('modalTitle').innerText = 'Initialize Production Line';
    document.getElementById('lineForm').reset();
    document.getElementById('line_id').value = '';
    
    // Reset products
    document.getElementById('selected-products-list').innerHTML = `
        <div id="no-products-msg" style="padding: 2rem; text-align: center; color: var(--text-muted); font-size: 0.875rem;">
            <i class="fas fa-shopping-bag" style="display: block; margin-bottom: 0.5rem; opacity: 0.3; font-size: 1.5rem;"></i>
            Click products on the left to add
        </div>`;
    document.querySelectorAll('#available-products-list .product-item').forEach(item => item.style.display = 'block');
    updateSelectedCount();
    
    // Reset stages
    document.getElementById('selected-stages-list').innerHTML = `
        <div id="no-stages-msg" style="padding: 2rem; text-align: center; color: var(--text-muted); font-size: 0.875rem;">
            <i class="fas fa-layer-group" style="display: block; margin-bottom: 0.5rem; opacity: 0.3; font-size: 1.5rem;"></i>
            Click stages on the left to build sequence
        </div>`;
    
    // Reset steps
    for (let i = 1; i <= 4; i++) {
        document.getElementById(`step-${i}`).style.display = i === 1 ? 'block' : 'none';
        document.getElementById(`step-idx-${i}`).classList.toggle('active', i === 1);
    }
    
    document.getElementById('prevBtn').style.display = 'none';
    document.getElementById('nextBtn').style.display = 'block';
    document.getElementById('finishBtn').style.display = 'none';
}

function closeSetupView() {
    document.getElementById('setup-view').style.display = 'none';
    document.getElementById('dashboard-view').style.display = 'block';
}

function editProductionLine(line) {
    openAddLineModal(); // Reuse reset logic
    document.getElementById('modalTitle').innerText = 'Edit Production Line';
    document.getElementById('line_id').value = line.id;
    document.getElementById('line_name').value = line.name;
    document.getElementById('line_start_date').value = line.start_date || '';
    document.getElementById('line_end_date').value = line.end_date || '';
    
    // Pre-populate products
    if (line.product_ids) {
        line.product_ids.forEach(pid => {
            const el = document.querySelector(`#available-products-list .product-item[data-id="${pid}"]`);
            if (el) toggleProductSelection(el);
        });
    }
}

function formatDateSimple(dateString) {
    if (!dateString) return 'N/A';
    const date = new Date(dateString);
    return date.toLocaleDateString([], { month: 'short', day: '2-digit' }) + ', ' + 
           date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true });
}


function finishSetup() {
    submitLineForm();
}

async function toggleLineStatus(id, currentStatus) {
    const actionName = currentStatus ? 'Deactivate' : 'Activate';
    const message = currentStatus 
        ? 'Are you sure you want to deactivate this line? This will prevent workers from logging time on all linked tasks.'
        : 'Are you sure you want to activate this production line?';

    if (await confirmAction({ 
        title: `${actionName} Production Line`, 
        message: message,
        confirmText: `${actionName} Line`,
        confirmColor: currentStatus ? 'var(--danger)' : 'var(--success)'
    })) {
        const newStatus = currentStatus ? 0 : 1;
        const result = await apiCall('production-lines', { 
            action: 'toggle-status', 
            id: id, 
            status: newStatus 
        });
        
        if (result.success) {
            notify(result.message, 'success');
            setTimeout(() => location.reload(), 800);
        } else {
            notify(result.error || 'Failed to update status', 'error');
        }
    }
}

async function submitLineForm() {
    const form = document.getElementById('lineForm');
    const btn = document.getElementById('finishBtn');
    const originalHtml = btn.innerHTML;
    
    setLoading(btn, true);
    
    const formData = new FormData(form);
    const data = Object.fromEntries(formData.entries());
    
    // Collect selected products with quantities
    data.products = Array.from(document.querySelectorAll('#selected-products-list .product-item'))
        .map(item => {
            const qtyInput = item.querySelector('.product-qty');
            return {
                id: item.dataset.id,
                quantity: qtyInput ? qtyInput.value : 0
            };
        });
        
    // Collect selected stages (only if they exist in DOM)
    data.stages = Array.from(document.querySelectorAll('.resource-stage-card')).map(card => {
        const stageId = card.dataset.stageId;
        return {
            workflow_stage_id: stageId,
            start_date: card.querySelector('.stage-start-date').value,
            end_date: card.querySelector('.stage-end_date')?.value || card.querySelector('.stage-end-date').value,
            quantity: card.querySelector('.stage-units').value,
            remarks: card.querySelector('.stage-remarks').value,
            staff_ids: Array.from(card.querySelectorAll(`.staff-list-${stageId} .resource-tag`)).map(t => t.dataset.staffId),
            machine_ids: Array.from(card.querySelectorAll(`.machine-list-${stageId} .resource-tag`)).map(t => t.dataset.machineId)
        };
    });

    // Fallback for stage IDs if resource cards haven't been generated yet (Step 2 but not Step 3)
    if (data.stages.length === 0) {
        data.stage_ids = Array.from(document.querySelectorAll('#selected-stages-list .stage-item'))
            .map(item => item.dataset.id);
    }
    
    try {
        const result = await apiCall('production-lines', { action: 'save', line: data });
        if (result.success) {
            notify(result.message);
            setTimeout(() => location.reload(), 1000);
        } else {
            notify(result.message, 'error');
            setLoading(btn, false);
        }
    } catch (error) {
        notify('Failed to save production line', 'error');
        setLoading(btn, false);
    }
}

function viewLine(line) {
    document.getElementById('view-summary-name').innerText = line.name;
    document.getElementById('view-summary-start').innerText = formatDate(line.start_date);
    document.getElementById('view-summary-end').innerText = formatDate(line.end_date);
    
    const productsHtml = (line.products || []).map(p => `
        <div style="background: var(--bg-card); padding: 0.4rem 0.8rem; border-radius: 12px; border: 1px solid var(--border); display: flex; align-items: center; gap: 0.5rem; min-width: max-content;">
            <i class="fas fa-shopping-bag" style="color: var(--primary); font-size: 0.8rem;"></i>
            <span onclick="viewProductDetails(${p.id})" style="cursor: pointer; font-size: 0.85rem; font-weight: 700; color: var(--text-main); white-space: nowrap;">${p.name} - <span style="color: var(--primary);">${p.quantity} units</span></span>
        </div>
    `).join('');
    document.getElementById('view-summary-products').innerHTML = productsHtml || '<span style="color: var(--text-muted);">No products assigned</span>';
    document.getElementById('view-summary-products').style.display = 'flex';
    document.getElementById('view-summary-products').style.flexWrap = 'wrap';
    document.getElementById('view-summary-products').style.gap = '0.5rem';

    let tableHtml = `
        <style>
            .mobile-scroll-container { width: 100%; overflow-x: auto; -webkit-overflow-scrolling: touch; margin-bottom: 1rem; border-radius: 12px; }
            @media (max-width: 768px) {
                .details-grid { grid-template-columns: 1fr !important; gap: 1.5rem !important; }
            }
        </style>
        <div class="mobile-scroll-container">
            <table style="width: 100%; min-width: 800px; border-collapse: separate; border-spacing: 0 0.5rem; margin-top: -0.5rem;">
                <thead>
                    <tr style="text-align: left; font-size: 0.65rem; text-transform: uppercase; color: var(--text-muted); letter-spacing: 1px;">
                        <th style="padding: 0.5rem 1rem;">Stage</th>
                        <th style="padding: 0.5rem 1rem;">Resources</th>
                        <th style="padding: 0.5rem 1rem;">Schedule</th>
                        <th style="padding: 0.5rem 1rem;">Time Spent</th>
                        <th style="padding: 0.5rem 1rem; text-align: right;">Progress</th>
                    </tr>
                </thead>
                <tbody>
    `;

    (line.full_stages || []).forEach((ls, idx) => {
        const staffHtml = (ls.staff || []).map(s => `
            <div style="display: flex; align-items: center; gap: 0.4rem; font-size: 0.75rem; color: var(--text-main); font-weight: 500; margin-bottom: 0.15rem;">
                ${s.profile_picture ? `<img src="${s.profile_picture}" style="width: 16px; height: 16px; border-radius: 50%; object-fit: cover;">` : `<div style="width: 16px; height: 16px; background: var(--primary); color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 0.5rem;">${s.name.charAt(0)}</div>`}
                <span>${s.name}</span>
            </div>
        `).join('');

        const machineryHtml = (ls.machinery || []).map(m => `
            <div style="display: flex; align-items: center; gap: 0.4rem; font-size: 0.7rem; color: var(--accent); font-weight: 500; opacity: 0.8;">
                <i class="fas fa-cog" style="font-size: 0.6rem;"></i> <span>${m.name}</span>
            </div>
        `).join('');

        const percent = ((ls.completed_units / (ls.quantity || 1)) * 100).toFixed(1);
        const hours = parseFloat(ls.total_hours || 0).toFixed(1);

        const timelogsHtml = (ls.timelogs || []).map(tl => `
            <div style="padding: 0.75rem; background: var(--bg-dark); border-radius: 8px; border: 1px solid var(--border); margin-bottom: 0.5rem; border-left: 3px solid var(--accent);">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.25rem;">
                    <span style="font-weight: 700; font-size: 0.7rem; color: var(--text-main);">${tl.employee_name}</span>
                    <span style="font-size: 0.6rem; color: var(--text-muted); font-weight: 600;">${formatDateSimple(tl.log_date)}</span>
                </div>
                <div style="font-size: 0.75rem; color: var(--text-muted); line-height: 1.4; margin-bottom: 0.4rem;">${tl.comments || 'No comments'}</div>
                <div style="display: flex; gap: 0.4rem; flex-wrap: wrap;">
                    ${(tl.attachments || []).map(a => `
                        <a href="${a.file_path}" target="_blank" style="font-size: 0.6rem; color: var(--primary); text-decoration: none; display: flex; align-items: center; gap: 0.2rem; background: rgba(124, 58, 237, 0.05); padding: 0.15rem 0.4rem; border-radius: 4px; border: 1px solid var(--primary)30;">
                            <i class="fas fa-paperclip"></i> ${a.file_name}
                        </a>
                    `).join('')}
                </div>
            </div>
        `).join('');

        const updatesHtml = (ls.updates || []).map(upd => `
            <div style="padding: 0.75rem; background: var(--bg-dark); border-radius: 8px; border: 1px solid var(--border); margin-bottom: 0.5rem; border-left: 3px solid var(--primary);">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.25rem;">
                    <span style="font-weight: 700; font-size: 0.7rem; color: var(--text-main);">Manager: ${upd.manager_name}</span>
                    <span style="font-size: 0.6rem; color: var(--text-muted); font-weight: 600;">${formatDateSimple(upd.created_at)}</span>
                </div>
                <div style="font-size: 0.75rem; color: var(--text-muted); line-height: 1.4; margin-bottom: 0.4rem;">${upd.comments || 'No comments'}</div>
                <div style="display: flex; gap: 0.4rem; flex-wrap: wrap;">
                    ${(upd.attachments || []).map(a => `
                        <a href="${a.file_path}" target="_blank" style="font-size: 0.6rem; color: var(--primary); text-decoration: none; display: flex; align-items: center; gap: 0.2rem; background: rgba(124, 58, 237, 0.05); padding: 0.15rem 0.4rem; border-radius: 4px; border: 1px solid var(--primary)30;">
                            <i class="fas fa-paperclip"></i> ${a.file_name}
                        </a>
                    `).join('')}
                </div>
            </div>
        `).join('');

        const detailsId = `stage-details-${ls.id}`;
        tableHtml += `
            <tr style="background: rgba(255,255,255,0.02); cursor: pointer;" onclick="toggleStageDetails('${detailsId}')">
                <td style="padding: 0.75rem 1rem; border-radius: 8px 0 0 8px;">
                    <div style="display: flex; align-items: center; gap: 0.75rem;">
                        <div style="width: 24px; height: 24px; background: ${ls.color_code}20; color: ${ls.color_code}; border-radius: 6px; display: flex; align-items: center; justify-content: center; font-size: 0.7rem; font-weight: 800; border: 1px solid ${ls.color_code}40;">${idx + 1}</div>
                        <div>
                            <div style="font-weight: 700; font-size: 0.85rem; color: var(--text-main);">${ls.stage_name}</div>
                            <div style="font-size: 0.6rem; font-weight: 800; color: ${
                                ls.status === 'Blocked' ? 'var(--danger)' : 
                                (ls.status === 'Completed' || parseFloat(ls.completed_units) >= parseFloat(ls.quantity) ? 'var(--primary)' : 
                                (ls.status === 'WIP' || ls.status === 'Active' || !ls.status ? 'var(--success)' : 'var(--text-muted)'))
                            }; text-transform: uppercase; letter-spacing: 0.5px; margin-top: 0.1rem;">
                                <i class="fas ${
                                    ls.status === 'Blocked' ? 'fa-ban' : 
                                    (ls.status === 'Completed' || parseFloat(ls.completed_units) >= parseFloat(ls.quantity) ? 'fa-flag-checkered' : 
                                    (ls.status === 'WIP' || ls.status === 'Active' || !ls.status ? 'fa-spinner fa-spin' : 'fa-clock'))
                                }"></i> 
                                ${
                                    ls.status === 'Blocked' ? 'Blocked' : 
                                    (ls.status === 'Completed' || parseFloat(ls.completed_units) >= parseFloat(ls.quantity) ? 'Completed' : 
                                    (ls.status === 'WIP' || ls.status === 'Active' || !ls.status ? 'Active' : ls.status))
                                }
                            </div>
                        </div>
                    </div>
                </td>
                <td style="padding: 0.75rem 1rem;">
                    <div style="display: flex; flex-direction: column;">
                        ${staffHtml || machineryHtml ? staffHtml + machineryHtml : '<span style="font-size: 0.7rem; color: var(--text-muted);">Unassigned</span>'}
                    </div>
                </td>
                <td style="padding: 0.75rem 1rem; font-size: 0.75rem; font-weight: 600;">
                    ${formatDateSimple(ls.start_date)} - ${formatDateSimple(ls.end_date)}
                </td>
                <td style="padding: 0.75rem 1rem;">
                    <div style="display: flex; align-items: center; gap: 0.4rem; color: var(--primary); font-weight: 700; font-size: 0.85rem;">
                        <i class="far fa-clock"></i> <span>${hours} <small>h</small></span>
                    </div>
                </td>
                <td style="padding: 0.75rem 1rem; text-align: right; border-radius: 0 8px 8px 0;">
                    <div style="display: flex; align-items: center; justify-content: flex-end; gap: 1rem;">
                        <div style="text-align: right;">
                            <div style="font-weight: 700; font-size: 0.85rem; color: ${percent >= 100 ? 'var(--success)' : 'var(--text-main)'};">${ls.completed_units}/${ls.quantity}</div>
                            <div style="font-size: 0.65rem; font-weight: 800; color: ${percent >= 100 ? 'var(--success)' : 'var(--primary)'};">${percent}%</div>
                        </div>
                        <i class="fas fa-chevron-up" id="chevron-${detailsId}" style="color: var(--text-muted); transition: transform 0.3s;"></i>
                    </div>
                </td>
            </tr>
            <tr id="${detailsId}" style="display: table-row;">
                <td colspan="5" style="padding: 0 1rem 1rem 1rem;">
                    <div style="background: rgba(0,0,0,0.02); border-radius: 12px; padding: 1rem; border: 1px solid var(--border);">
                        ${ls.status === 'Blocked' ? `
                            <div style="background: rgba(239, 68, 68, 0.08); border: 1px solid rgba(239, 68, 68, 0.2); border-radius: 10px; padding: 1rem; margin-bottom: 1.25rem; display: flex; align-items: center; gap: 1rem;">
                                <div style="width: 36px; height: 36px; background: var(--danger); color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; flex-shrink: 0; box-shadow: 0 4px 6px -1px rgba(239, 68, 68, 0.2);">
                                    <i class="fas fa-exclamation-triangle"></i>
                                </div>
                                <div>
                                    <div style="font-size: 0.6rem; color: var(--danger); text-transform: uppercase; font-weight: 900; letter-spacing: 0.5px; margin-bottom: 0.2rem;">Stage Bottleneck Identified</div>
                                    <div style="font-size: 0.9rem; font-weight: 700; color: var(--text-main); font-style: italic; line-height: 1.4;">"${ls.current_status_note || 'No reason specified'}"</div>
                                </div>
                            </div>
                        ` : ''}
                        <div class="details-grid" style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem;">
                            <div>
                                <div style="font-size: 0.6rem; color: var(--text-muted); text-transform: uppercase; font-weight: 800; margin-bottom: 0.75rem; display: flex; align-items: center; gap: 0.4rem;">
                                    <i class="fas fa-user-clock"></i> Employee Time Logs
                                </div>
                                ${timelogsHtml || '<div style="font-size: 0.7rem; color: var(--text-muted); font-style: italic; padding: 0.5rem; background: var(--bg-dark); border-radius: 8px;">No activity logged yet</div>'}
                            </div>
                            <div>
                                <div style="font-size: 0.6rem; color: var(--text-muted); text-transform: uppercase; font-weight: 800; margin-bottom: 0.75rem; display: flex; align-items: center; gap: 0.4rem;">
                                    <i class="fas fa-user-shield"></i> Manager Progress Updates
                                </div>
                                ${updatesHtml || '<div style="font-size: 0.7rem; color: var(--text-muted); font-style: italic; padding: 0.5rem; background: var(--bg-dark); border-radius: 8px;">No updates logged yet</div>'}
                            </div>
                        </div>
                    </div>
                </td>
            </tr>
        `;
    });

    tableHtml += `</tbody></table></div>`;
    document.getElementById('view-summary-workflow-detailed').innerHTML = tableHtml;
    openModal('viewLineModal');
}

function toggleStageDetails(id) {
    const row = document.getElementById(id);
    const chevron = document.getElementById('chevron-' + id);
    if (row.style.display === 'none') {
        row.style.display = 'table-row';
        chevron.style.transform = 'rotate(0deg)';
    } else {
        row.style.display = 'none';
        chevron.style.transform = 'rotate(-180deg)';
    }
}

let currentProductionData = null;
let currentActiveStepIndex = 0;

async function openUpdateWorkspace(id) {
    document.getElementById('update-workspace').dataset.lineId = id;
    document.getElementById('dashboard-view').style.display = 'none';
    document.getElementById('update-workspace').style.display = 'block';
    
    const container = document.getElementById('stages-update-container');
    container.innerHTML = '<div style="text-align: center; padding: 4rem; color: var(--text-muted);"><i class="fas fa-spinner fa-spin fa-2x"></i><br><br>Loading production data...</div>';

    try {
        const result = await apiCall('production-lines', { action: 'get-update-data', id: id });
        if (result.success) {
            currentProductionData = result.data;
            document.getElementById('update-line-name').innerText = 'Line Update: ' + result.data.line.name;
            document.getElementById('update-line-period').innerText = 'Production Period: ' + formatDate(result.data.line.start_date) + ' → ' + formatDate(result.data.line.end_date);
            
            const productsHtml = (result.data.line.products || []).map(p => `
                <span class="resource-tag" style="cursor: pointer; background: var(--bg-dark); border: 1px solid var(--border); padding: 0.3rem 0.6rem; border-radius: 8px; display: flex; align-items: center; gap: 0.4rem; font-size: 0.75rem;" onclick="viewProductDetails(${p.id})">
                    <i class="fas fa-shopping-bag" style="font-size: 0.7rem; color: var(--primary);"></i>
                    <span style="font-weight: 700; color: var(--text-main);">${p.name}</span>
                    <span style="color: var(--primary); font-weight: 800;">(${p.quantity} units)</span>
                </span>
            `).join('');
            document.getElementById('update-line-products').innerHTML = productsHtml || '<span style="color: var(--text-muted);">No products assigned</span>';
            
            // Find the current active stage (WIP, Blocked, or first Pending)
            const activeIndex = result.data.stages.findIndex(s => s.status === 'WIP' || s.status === 'Blocked');
            if (activeIndex !== -1) {
                currentActiveStepIndex = activeIndex;
            } else {
                const firstPending = result.data.stages.findIndex(s => s.status === 'Pending');
                currentActiveStepIndex = firstPending !== -1 ? firstPending : result.data.stages.length; // length means Final Review
            }
            
            renderUpdateWorkspace();
        } else {
            notify(result.message, 'error');
            closeUpdateWorkspace();
        }
    } catch (error) {
        notify('Failed to load production data', 'error');
        closeUpdateWorkspace();
    }
}

function renderUpdateWorkspace() {
    renderStepIndicator();
    if (currentActiveStepIndex < currentProductionData.stages.length) {
        renderStageContent(currentActiveStepIndex);
    } else {
        renderFinalReview();
    }
}

function renderStepIndicator() {
    const indicator = document.getElementById('update-step-indicator');
    const stages = currentProductionData.stages;
    
    let html = stages.map((stage, idx) => {
        const isCompleted = stage.status === 'Completed';
        const isWIP = stage.status === 'WIP';
        const isCurrent = currentActiveStepIndex === idx;
        const isDisabled = !isCompleted && !isWIP && idx > stages.findIndex(s => s.status === 'Pending' || s.status === 'WIP');

        return `
            <div class="step-item ${isCurrent ? 'active' : ''} ${isCompleted ? 'completed' : ''} ${isDisabled ? 'disabled' : ''}" 
                 onclick="${!isDisabled ? `goToStep(${idx})` : ''}"
                 style="cursor: ${isDisabled ? 'not-allowed' : 'pointer'}; opacity: ${isDisabled ? '0.4' : '1'}; flex: 1;">
                <div class="step-num" style="background: ${isCompleted ? 'var(--success)' : (isCurrent ? 'var(--primary)' : 'var(--bg-dark)')};">
                    ${isCompleted ? '<i class="fas fa-check"></i>' : (idx + 1)}
                </div>
                <div class="step-label" style="font-size: 0.95rem; font-weight: 700;">${stage.stage_name}</div>
            </div>
            ${idx < stages.length - 1 ? '<div class="step-line" style="margin-top: 18px; opacity: 0.3;"></div>' : ''}
        `;
    }).join('');

    // Add Final Review Step
    const allCompleted = stages.every(s => s.status === 'Completed');
    html += `
        <div class="step-line" style="margin-top: 18px; opacity: 0.3;"></div>
        <div class="step-item ${currentActiveStepIndex === stages.length ? 'active' : ''} ${allCompleted ? '' : 'disabled'}" 
             onclick="${allCompleted || currentActiveStepIndex === stages.length ? `goToStep(${stages.length})` : ''}"
             style="cursor: ${!allCompleted ? 'not-allowed' : 'pointer'}; opacity: ${!allCompleted ? '0.4' : '1'}; flex: 1;">
            <div class="step-num" style="background: ${currentActiveStepIndex === stages.length ? 'var(--primary)' : 'var(--bg-dark)'};">
                <i class="fas fa-flag-checkered"></i>
            </div>
            <div class="step-label" style="font-size: 0.95rem; font-weight: 700;">Final Review</div>
        </div>
    `;

    indicator.innerHTML = html;
}

function goToStep(idx) {
    currentActiveStepIndex = idx;
    renderUpdateWorkspace();
}

function renderStageContent(idx) {
    const container = document.getElementById('stages-update-container');
    const stage = currentProductionData.stages[idx];
    const isCompleted = stage.status === 'Completed';
    const lineCompleted = currentProductionData.line.status === 'Completed';
    const isActive = !lineCompleted && (stage.status === 'WIP' || stage.status === 'Blocked' || (stage.status === 'Pending' && (idx === 0 || currentProductionData.stages[idx-1].status === 'Completed')));

    container.innerHTML = `
        <div class="animate-fade-in">
            <style>
                .stage-header-flex { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 2rem; gap: 1.5rem; }
                @media (max-width: 1024px) {
                    .stage-header-flex { flex-direction: column; align-items: stretch; }
                    .stage-header-flex .btn { width: 100%; }
                }
            </style>
            <style>
                .update-main-layout { display: grid; grid-template-columns: 1.2fr 1fr; gap: 3rem; }
                .stage-header-wrap { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 2rem; gap: 1.5rem; }
                @media (max-width: 1024px) {
                    .update-main-layout { grid-template-columns: 1fr; gap: 2rem; }
                    .stage-header-wrap { flex-direction: column; align-items: stretch; }
                    .stage-header-wrap .btn { width: 100%; }
                    #update-step-indicator { 
                        overflow-x: auto; 
                        padding-bottom: 1.5rem; 
                        justify-content: flex-start !important; 
                        gap: 2rem;
                        -webkit-overflow-scrolling: touch;
                    }
                    .step-item { min-width: 140px; flex: 0 0 auto !important; }
                    .step-line { min-width: 30px; }
                }
            </style>
            
            <div class="stage-header-wrap">
                <div>
                    <h3 style="font-size: 1.75rem; font-weight: 700; color: var(--text-main);">${stage.stage_name}</h3>
                    <div style="display: flex; align-items: center; gap: 1rem; margin-top: 0.5rem; font-size: 0.9rem; color: var(--text-muted); flex-wrap: wrap;">
                        <span><i class="far fa-calendar-alt"></i> ${formatDate(stage.start_date)} - ${formatDate(stage.end_date)}</span>
                        <span><i class="fas fa-check-circle"></i> Completed: <strong style="color: var(--success);">${stage.completed_units || 0}</strong></span>
                        <span><i class="fas fa-bullseye"></i> Target: <strong style="color: var(--primary);">${stage.quantity || 0} units</strong></span>
                        <span class="badge" style="background: ${(stage.completed_units / (stage.quantity || 1)) * 100 >= 100 ? 'var(--success)' : 'rgba(79, 70, 229, 0.1)'}; color: ${(stage.completed_units / (stage.quantity || 1)) * 100 >= 100 ? 'white' : 'var(--primary)'}; font-weight: 800; border-radius: 6px; padding: 0.3rem 0.6rem;">
                            ${((stage.completed_units / (stage.quantity || 1)) * 100).toFixed(1)}% COMPLETED
                        </span>
                    </div>
                    <div style="margin-top: 1rem; display: flex; flex-wrap: wrap; gap: 0.5rem;">
                        <span style="font-size: 0.65rem; color: var(--text-muted); text-transform: uppercase; font-weight: 800; display: block; width: 100%; margin-bottom: 0.25rem;">Target Products</span>
                        ${(currentProductionData.line.products || []).map(p => `
                            <span class="resource-tag" style="cursor: pointer; background: var(--bg-dark); border: 1px solid var(--border); font-size: 0.75rem;" onclick="viewProductDetails(${p.id})">
                                <i class="fas fa-shopping-bag" style="font-size: 0.6rem; opacity: 0.5;"></i> ${p.name}
                            </span>
                        `).join('')}
                    </div>
                    ${stage.current_status_note ? `
                        <div style="margin-top: 0.75rem; padding: 0.75rem 1rem; background: rgba(79, 70, 229, 0.05); border-left: 3px solid var(--primary); border-radius: 4px; font-size: 0.85rem; color: var(--text-muted); font-style: italic;">
                            <i class="fas fa-info-circle"></i> "${stage.current_status_note}"
                        </div>
                    ` : ''}
                </div>
                
                ${isActive && !isCompleted ? `
                    <button class="btn btn-primary" 
                            onclick="${stage.status === 'Blocked' ? 'notify(\'Stage is blocked. Please resolve it first.\', \'warning\')' : `confirmCompleteStage(${stage.id}, '${stage.stage_name}')`}" 
                            style="padding: 0.85rem 2rem; border-radius: 14px; font-size: 1rem; ${stage.status === 'Blocked' ? 'opacity: 0.6; cursor: not-allowed; background: var(--border); color: var(--text-muted);' : ''}">
                        <i class="fas ${stage.status === 'Blocked' ? 'fa-exclamation-triangle' : 'fa-check-double'}"></i> 
                        ${stage.status === 'Blocked' ? 'Stage Blocked' : 'Complete Stage'}
                    </button>
                ` : (isCompleted ? `
                    <div style="padding: 0.75rem 1.5rem; background: rgba(16, 185, 129, 0.1); color: var(--success); border-radius: 12px; font-weight: 700; display: flex; align-items: center; justify-content: center; gap: 0.5rem;">
                        <i class="fas fa-check-circle"></i> COMPLETED
                    </div>
                ` : '')}
            </div>

            <div class="update-main-layout">
                <!-- Left Side: Resources & History -->
                <div>
                    <div style="margin-bottom: 2.5rem;">
                        <h4 style="font-size: 0.8rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase; margin-bottom: 1.25rem;">Staff & Effort Logs</h4>
                        <div style="display: flex; flex-direction: column; gap: 1rem;">
                            ${stage.staff.map(s => `
                                <div class="employee-effort-card" style="background: var(--bg-dark); border-radius: 16px; border: 1px solid var(--border); overflow: hidden;">
                                    <div style="display: flex; align-items: center; justify-content: space-between; padding: 1.25rem; cursor: pointer;" onclick="toggleEmployeeLogs(this)">
                                        <div style="display: flex; align-items: center; gap: 1rem;">
                                            ${s.profile_picture ? `<img src="${s.profile_picture}" style="width: 45px; height: 45px; border-radius: 50%; object-fit: cover; border: 2px solid var(--border);">` : `<div class="user-avatar" style="width: 45px; height: 45px; font-size: 1.2rem;">${s.name.charAt(0)}</div>`}
                                            <div>
                                                <div style="font-weight: 700; color: var(--text-main); font-size: 1rem;">${s.name}</div>
                                                <div style="font-size: 0.75rem; color: var(--text-muted);">Assigned Personnel</div>
                                            </div>
                                        </div>
                                        <div style="display: flex; align-items: center; gap: 1.5rem;">
                                            <div style="text-align: right;">
                                                <div style="font-size: 1.25rem; font-weight: 800; color: var(--primary);">${parseFloat(s.total_hours || 0).toFixed(1)} <span style="font-size: 0.7rem; font-weight: 600;">HRS</span></div>
                                                <div style="font-size: 0.6rem; color: var(--text-muted); text-transform: uppercase;">Total Effort</div>
                                            </div>
                                            <i class="fas fa-chevron-down log-toggle-icon" style="color: var(--text-muted); transition: transform 0.3s; transform: rotate(180deg);"></i>
                                        </div>
                                    </div>
                                    <div class="employee-detailed-logs" style="display: block; padding: 0 1.25rem 1.25rem; border-top: 1px solid rgba(255,255,255,0.05); background: rgba(0,0,0,0.15);">
                                        <div style="margin-top: 1rem;">
                                            <h5 style="font-size: 0.7rem; color: var(--text-muted); text-transform: uppercase; margin-bottom: 0.75rem;">Recent Activity</h5>
                                            ${(s.logs && s.logs.length > 0) ? s.logs.map(log => `
                                                <div style="padding: 0.75rem; border-bottom: 1px solid rgba(255,255,255,0.05); font-size: 0.8rem;">
                                                    <div style="display: flex; justify-content: space-between; margin-bottom: 0.35rem; align-items: center;">
                                                        <div style="display: flex; align-items: center; gap: 0.75rem;">
                                                            <span style="font-weight: 700; color: var(--text-main);">${formatDate(log.log_date)}</span>
                                                            <span style="font-size: 0.6rem; padding: 0.15rem 0.5rem; border-radius: 50px; background: ${log.status_color || 'var(--border)'}20; color: ${log.status_color || 'var(--text-muted)'}; border: 1px solid ${log.status_color || 'var(--border)'}40; font-weight: 800; text-transform: uppercase;">
                                                                ${log.status_name || 'N/A'}
                                                            </span>
                                                        </div>
                                                        <span style="color: var(--primary); font-weight: 800; font-size: 0.9rem;">${log.hours_spent} hrs</span>
                                                    </div>
                                                    <p style="color: var(--text-muted); margin: 0; line-height: 1.4;">${log.comments || 'No log details provided'}</p>
                                                    ${(log.attachments && log.attachments.length > 0) ? `
                                                        <div style="display: flex; gap: 0.4rem; flex-wrap: wrap; margin-top: 0.5rem;">
                                                            ${log.attachments.map(a => `
                                                                <a href="${a.file_path}" target="_blank" style="font-size: 0.7rem; color: var(--primary); text-decoration: none; display: flex; align-items: center; gap: 0.2rem;">
                                                                    <i class="fas fa-paperclip"></i> ${a.file_name.length > 15 ? a.file_name.substring(0, 12) + '...' : a.file_name}
                                                                </a>
                                                            `).join('')}
                                                        </div>
                                                    ` : ''}
                                                </div>
                                            `).join('') : '<div style="color: var(--text-muted); font-size: 0.8rem; font-style: italic;">No detailed time logs found for this stage.</div>'}
                                        </div>
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    </div>

                    <div>
                        <h4 style="font-size: 0.8rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase; margin-bottom: 1.25rem;">Machinery Allocated</h4>
                        <div style="display: flex; flex-wrap: wrap; gap: 0.75rem;">
                            ${stage.machinery.map(m => `
                                <div class="resource-tag machine" style="padding: 0.6rem 1rem; font-size: 0.8rem; background: var(--bg-dark); border: 1px solid var(--border);">
                                    <i class="fas fa-cog" style="color: var(--primary);"></i> ${m.name} <span style="opacity: 0.5; margin-left: 0.4rem;">${m.model_no || ''}</span>
                                </div>
                            `).join('')}
                        </div>
                    </div>

                    <div style="margin-top: 2.5rem;">
                        <h4 style="font-size: 0.8rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase; margin-bottom: 1rem;">Progress History</h4>
                        <div style="display: flex; flex-direction: column; gap: 0.5rem;">
                            ${stage.updates.length === 0 ? '<div style="padding: 1.5rem; text-align: center; background: var(--bg-dark); border-radius: 12px; color: var(--text-muted); font-style: italic; font-size: 0.85rem; border: 1px dashed var(--border);">No progress reports yet.</div>' : stage.updates.map(upd => {
                                const isToday = new Date(upd.created_at).toDateString() === new Date().toDateString();
                                return `
                                <div style="padding: 0.75rem 1rem; background: var(--bg-dark); border-radius: 12px; border: 1px solid ${upd.status === 'Blocked' ? 'rgba(239, 68, 68, 0.3)' : (upd.is_status_change == 1 ? 'rgba(16, 185, 129, 0.3)' : 'var(--border)')}; display: flex; align-items: flex-start; justify-content: space-between; gap: 1rem; position: relative;">
                                    <div style="flex: 1;">
                                        <div style="display: flex; align-items: center; gap: 0.75rem; margin-bottom: 0.4rem;">
                                            <span style="font-weight: 800; color: var(--success); font-size: 0.9rem;">+ ${upd.completed_units} <span style="font-size: 0.75rem; font-weight: 600;">units</span></span>
                                            <span style="font-size: 0.7rem; color: var(--text-muted);">${new Date(upd.created_at).toLocaleDateString([], {month: 'short', day: '2-digit'})}, ${new Date(upd.created_at).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit', hour12: true})}</span>
                                            ${upd.status === 'Blocked' ? 
                                                '<span style="font-size: 0.6rem; padding: 0.1rem 0.4rem; background: rgba(239, 68, 68, 0.15); color: var(--danger); border-radius: 4px; font-weight: 800; border: 1px solid rgba(239, 68, 68, 0.3);">BLOCKED</span>' : 
                                                (upd.is_status_change == 1 ? '<span style="font-size: 0.6rem; padding: 0.1rem 0.4rem; background: rgba(16, 185, 129, 0.15); color: var(--success); border-radius: 4px; font-weight: 800; border: 1px solid rgba(16, 185, 129, 0.3);">UNBLOCKED</span>' : '')
                                            }
                                            ${isToday && upd.is_status_change == 0 ? '<span style="font-size: 0.6rem; padding: 0.1rem 0.4rem; background: rgba(16, 185, 129, 0.1); color: var(--text-muted); border-radius: 4px; font-weight: 700;">TODAY</span>' : ''}
                                        </div>
                                        <p style="color: var(--text-muted); font-size: 0.8rem; margin: 0; line-height: 1.4;">${upd.comments || '<span style="opacity: 0.5;">No comments</span>'}</p>
                                        ${upd.attachments.length > 0 ? `
                                            <div style="display: flex; gap: 0.4rem; flex-wrap: wrap; margin-top: 0.5rem;">
                                                ${upd.attachments.map(a => `
                                                    <a href="${a.file_path}" target="_blank" style="font-size: 0.7rem; color: var(--primary); text-decoration: none; display: flex; align-items: center; gap: 0.2rem;">
                                                        <i class="fas fa-paperclip"></i> ${a.file_name.length > 15 ? a.file_name.substring(0, 12) + '...' : a.file_name}
                                                    </a>
                                                `).join('')}
                                            </div>
                                        ` : ''}
                                    </div>
                                    <div style="display: flex; flex-direction: column; align-items: flex-end; gap: 0.5rem;">
                                        ${!isCompleted && isToday && !upd.is_status_change ? `
                                            <button onclick="deleteStageUpdate(${upd.id})" style="background: none; border: none; color: var(--danger); opacity: 0.6; cursor: pointer; padding: 0.2rem;" title="Delete Log">
                                                <i class="fas fa-trash-alt" style="font-size: 0.85rem;"></i>
                                            </button>
                                        ` : (isCompleted || upd.is_status_change ? '<i class="fas fa-shield-alt" style="font-size: 0.75rem; color: var(--text-muted); opacity: 0.4;" title="Audit-Protected Record"></i>' : '')}
                                        <div style="display: flex; align-items: center; gap: 0.5rem; margin-top: 0.5rem;">
                                            ${upd.manager_avatar ? `<img src="${upd.manager_avatar}" style="width: 20px; height: 20px; border-radius: 50%; object-fit: cover;">` : `<div style="width: 20px; height: 20px; border-radius: 50%; background: var(--primary); color: white; display: flex; align-items: center; justify-content: center; font-size: 0.5rem; font-weight: 800;">${(upd.manager_name || 'S').charAt(0)}</div>`}
                                            <div style="font-size: 0.65rem; color: var(--text-muted); line-height: 1.2;">
                                                <div style="font-weight: 700; color: var(--text-main);">${upd.manager_name || 'System'}</div>
                                                <div style="font-size: 0.55rem; opacity: 0.7;">${upd.manager_role || 'Manager'}</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            `; }).join('')}
                        </div>
                    </div>
                </div>

                <!-- Right Side: Action Form -->
                <div>
                    <style>
                        .workspace-form-sticky { position: sticky; top: 100px; }
                        @media (max-width: 1024px) {
                            .workspace-form-sticky { position: relative; top: 0; }
                        }
                    </style>
                    ${!isCompleted && isActive ? `
                        <form onsubmit="submitStageUpdate(event, ${stage.id})" data-current-status="${stage.status}" class="card workspace-form-sticky" style="background: var(--bg-dark); padding: 2rem; border-radius: 24px; border: 1px solid var(--border);">
                            <h4 style="font-size: 1.1rem; font-weight: 700; color: var(--text-main); margin-bottom: 1.5rem;">Add Progress Update</h4>
                            
                            <div class="form-group" style="margin-bottom: 1.5rem;">
                                <label class="form-label">Current Status <span class="required-mark">*</span></label>
                                <select name="status" class="form-control" required onchange="toggleCommentRequirement(this)" style="padding: 0.85rem; font-size: 1rem; background: var(--bg-card);">
                                    <option value="" disabled>Select Current Status</option>
                                    ${currentProductionData.statuses.map(s => `
                                        <option value="${s.internal_value}" ${stage.status === s.internal_value ? 'selected' : ''}>${s.name}</option>
                                    `).join('')}
                                </select>
                            </div>

                            <div class="form-group">
                                <label class="form-label">Units Completed <span id="units-required-mark" class="required-mark">*</span></label>
                                <input type="number" name="completed_units" class="form-control" placeholder="Enter units" value="0" style="font-size: 1.1rem; padding: 0.85rem;">
                            </div>

                            <div class="form-group" style="margin-top: 1.5rem;">
                                <label class="form-label">Manager Comments <span class="required-mark">*</span></label>
                                <textarea name="comments" class="form-control" rows="4" placeholder="Mention any blockers or batch details..." style="padding: 0.85rem;" required></textarea>
                            </div>
                            
                            <div class="form-group" style="margin-top: 1.5rem;">
                                <label class="form-label">Evidence / Photos</label>
                                <div style="border: 2px dashed var(--border); padding: 1.5rem; border-radius: 20px; text-align: center; background: rgba(0,0,0,0.15);">
                                    <i class="fas fa-images fa-2x" style="color: var(--primary); margin-bottom: 1rem; opacity: 0.5;"></i>
                                    <input type="file" name="attachments[]" id="stage_attachments_${stage.id}" multiple style="display: none;" onchange="updateStageFileNames(this)">
                                    <label for="stage_attachments_${stage.id}" class="btn" style="display: block; cursor: pointer; background: var(--bg-card); font-weight: 700; font-size: 0.85rem; padding: 0.6rem;">
                                        <i class="fas fa-file-upload"></i> Select Files
                                    </label>
                                    <div class="file-status" style="font-size: 0.75rem; color: var(--text-muted); margin-top: 0.5rem;">No files selected</div>
                                </div>
                            </div>
                            <button type="submit" class="btn btn-primary" style="width: 100%; margin-top: 2rem; padding: 1rem; font-size: 1.1rem;">
                                <i class="fas fa-save"></i> Submit Update
                            </button>
                        </form>
                    ` : (isCompleted ? `
                        <div class="card workspace-form-sticky" style="background: rgba(16, 185, 129, 0.03); border: 2px solid var(--success); border-radius: 24px; padding: 3rem; text-align: center;">
                            <div style="width: 80px; height: 80px; background: var(--success); color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 1.5rem; font-size: 2rem; box-shadow: 0 10px 20px rgba(16, 185, 129, 0.3);">
                                <i class="fas fa-check"></i>
                            </div>
                            <h3 style="color: var(--success); font-weight: 800; font-size: 1.5rem;">Stage Completed</h3>
                            <p style="color: var(--text-muted); margin-top: 1rem; font-size: 1rem; line-height: 1.6;">
                                This stage has been finalized with <strong>${stage.completed_units}</strong> units produced.<br>
                                Click the next step in the flow to continue.
                            </p>
                        </div>
                    ` : `
                        <div class="card workspace-form-sticky" style="background: var(--bg-dark); border: 2px dashed var(--border); border-radius: 24px; padding: 4rem; text-align: center; opacity: 0.6;">
                            <i class="fas fa-lock fa-3x" style="color: var(--text-muted); margin-bottom: 1.5rem;"></i>
                            <h4 style="color: var(--text-muted); font-weight: 700;">Stage Locked</h4>
                            <p style="color: var(--text-muted); font-size: 0.9rem; margin-top: 0.5rem;">Finish previous stages to unlock this phase.</p>
                        </div>
                    `)}
                </div>
            </div>
        </div>
    `;
}

function toggleEmployeeLogs(header) {
    const card = header.parentElement;
    const logs = card.querySelector('.employee-detailed-logs');
    const icon = card.querySelector('.log-toggle-icon');
    const isHidden = logs.style.display === 'none';
    
    logs.style.display = isHidden ? 'block' : 'none';
    icon.style.transform = isHidden ? 'rotate(180deg)' : 'rotate(0deg)';
}


function renderFinalReview() {
    const container = document.getElementById('stages-update-container');
    const data = currentProductionData;
    
    let html = `
        <div class="animate-fade-in">
            <div style="text-align: center; margin-bottom: 3rem;">
                <div style="width: 100px; height: 100px; background: var(--primary); color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 1.5rem; font-size: 2.5rem; box-shadow: 0 15px 30px rgba(79, 70, 229, 0.4);">
                    <i class="fas fa-flag-checkered"></i>
                </div>
                <h2 style="font-size: 2rem; font-weight: 800; color: var(--text-main);">Final Production Review</h2>
                <p style="color: var(--text-muted); font-size: 1.1rem; margin-top: 0.5rem;">Review all stage details and performance metrics below.</p>
            </div>


            <div style="display: flex; flex-direction: column; gap: 1rem;">
                ${data.stages.map((stage, idx) => `
                    <div class="collapsible-section" style="border: 1px solid var(--border); border-radius: 16px; background: var(--bg-card); overflow: hidden;">
                        <div onclick="toggleCollapse(this)" style="padding: 1.5rem; display: flex; justify-content: space-between; align-items: center; cursor: pointer; background: ${idx % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent'};">
                            <div style="display: flex; align-items: center; gap: 1.5rem;">
                                <div style="width: 35px; height: 35px; background: ${stage.color_code}; color: white; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-weight: 800;">${idx + 1}</div>
                                <div>
                                    <div style="font-weight: 700; font-size: 1.1rem; color: var(--text-main);">${stage.stage_name}</div>
                                    <div style="font-size: 0.8rem; color: var(--text-muted);">${formatDate(stage.start_date)} - ${formatDate(stage.end_date)}</div>
                                </div>
                            </div>

                            <div style="display: flex; align-items: center; gap: 2rem; font-size: 0.9rem;">
                                <div style="color: var(--text-muted);">
                                    <i class="fas fa-check-circle" style="color: var(--success); opacity: 0.7;"></i> Completed: <strong style="color: var(--text-main);">${stage.completed_units || 0}</strong>
                                </div>
                                <div style="color: var(--text-muted);">
                                    <i class="fas fa-bullseye" style="color: var(--primary); opacity: 0.7;"></i> Target: <strong style="color: var(--text-main);">${stage.quantity || 0} units</strong>
                                </div>
                            </div>
                            <div style="display: flex; align-items: center; gap: 2rem;">
                                <div style="text-align: right;">
                                    <div style="font-size: 1rem; font-weight: 700; color: var(--text-main);">${stage.completed_units} / ${stage.quantity} Units</div>
                                    <div style="font-size: 0.65rem; color: var(--success); font-weight: 800; text-transform: uppercase;">
                                        ${((stage.completed_units / (stage.quantity || 1)) * 100).toFixed(1)}% COMPLETED
                                    </div>
                                </div>
                                <i class="fas fa-chevron-down collapse-icon" style="transition: transform 0.3s;"></i>
                            </div>
                        </div>
                        <div class="collapse-content" style="display: none; padding: 2rem; border-top: 1px solid var(--border); background: var(--bg-dark);">
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 3rem;">
                                <div>
                                    <h5 style="font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; margin-bottom: 1rem;">Resource Utilization</h5>
                                    <div style="display: flex; flex-direction: column; gap: 0.75rem;">
                                        ${stage.staff.map(s => `
                                            <div style="margin-bottom: 0.75rem; border: 1px solid rgba(255,255,255,0.05); border-radius: 12px; overflow: hidden; background: rgba(0,0,0,0.1);">
                                                <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.75rem 1rem; cursor: pointer;" onclick="toggleCollapse(this)">
                                                    <div style="display: flex; align-items: center; gap: 0.75rem;">
                                                        ${s.profile_picture ? `<img src="${s.profile_picture}" style="width: 30px; height: 30px; border-radius: 50%;">` : `<div class="user-avatar" style="width: 30px; height: 30px; font-size: 0.7rem;">${s.name.charAt(0)}</div>`}
                                                        <span style="font-size: 0.9rem; color: var(--text-main); font-weight: 600;">${s.name}</span>
                                                    </div>
                                                    <div style="display: flex; align-items: center; gap: 1rem;">
                                                        <span style="font-weight: 700; color: var(--primary); font-size: 0.9rem;">${parseFloat(s.total_hours || 0).toFixed(1)} Hrs</span>
                                                        <i class="fas fa-chevron-down collapse-icon" style="font-size: 0.8rem; opacity: 0.5;"></i>
                                                    </div>
                                                </div>
                                                <div class="collapse-content" style="display: none; padding: 1rem; border-top: 1px solid rgba(255,255,255,0.05); background: rgba(0,0,0,0.1);">
                                                    ${(s.logs && s.logs.length > 0) ? s.logs.map(log => `
                                                        <div style="padding-bottom: 0.75rem; margin-bottom: 0.75rem; border-bottom: 1px solid rgba(255,255,255,0.03); last-child { border-bottom: none; margin-bottom: 0; }">
                                                            <div style="display: flex; justify-content: space-between; margin-bottom: 0.35rem; align-items: center;">
                                                                <div style="display: flex; align-items: center; gap: 0.75rem;">
                                                                    <span style="font-weight: 700; font-size: 0.8rem; color: var(--text-main);">${new Date(log.log_date).toLocaleDateString()}</span>
                                                                    <span style="font-size: 0.55rem; padding: 0.1rem 0.4rem; border-radius: 50px; background: ${log.status_color || 'var(--border)'}20; color: ${log.status_color || 'var(--text-muted)'}; border: 1px solid ${log.status_color || 'var(--border)'}40; font-weight: 800; text-transform: uppercase;">
                                                                        ${log.status_name || 'N/A'}
                                                                    </span>
                                                                </div>
                                                                <span style="font-weight: 700; color: var(--primary); font-size: 0.85rem;">${log.hours_spent} hrs</span>
                                                            </div>
                                                            <p style="font-size: 0.75rem; color: var(--text-muted); margin: 0;">${log.comments || 'No details'}</p>
                                                            ${(log.attachments && log.attachments.length > 0) ? `
                                                                <div style="display: flex; gap: 0.4rem; flex-wrap: wrap; margin-top: 0.4rem;">
                                                                    ${log.attachments.map(a => `
                                                                        <a href="${a.file_path}" target="_blank" style="font-size: 0.65rem; color: var(--primary); text-decoration: none; display: flex; align-items: center; gap: 0.2rem;">
                                                                            <i class="fas fa-paperclip"></i> ${a.file_name}
                                                                        </a>
                                                                    `).join('')}
                                                                </div>
                                                            ` : ''}
                                                        </div>
                                                    `).join('') : '<div style="font-size: 0.75rem; color: var(--text-muted); font-style: italic;">No detailed logs available.</div>'}
                                                </div>
                                            </div>
                                        `).join('')}
                                    </div>
                                    <div style="margin-top: 1.5rem; display: flex; flex-wrap: wrap; gap: 0.5rem;">
                                        ${stage.machinery.map(m => `
                                            <span class="resource-tag" style="font-size: 0.7rem;"><i class="fas fa-cog"></i> ${m.name}</span>
                                        `).join('')}
                                    </div>
                                </div>
                                <div>
                                    <h5 style="font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; margin-bottom: 1rem;">Progress Logs</h5>
                                    <div style="display: flex; flex-direction: column; gap: 0.75rem;">
                                        ${stage.updates.map(upd => `
                                            <div style="padding: 0.75rem 1rem; background: var(--bg-card); border-radius: 12px; border: 1px solid var(--border); font-size: 0.85rem; margin-bottom: 0.5rem;">
                                                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.75rem; padding-bottom: 0.5rem; border-bottom: 1px solid rgba(255,255,255,0.03);">
                                                    <div style="display: flex; align-items: center; gap: 0.75rem;">
                                                        ${upd.manager_avatar ? 
                                                            `<img src="${upd.manager_avatar}" style="width: 28px; height: 28px; border-radius: 50%; object-fit: cover;">` : 
                                                            `<div style="width: 28px; height: 28px; border-radius: 50%; background: var(--bg-dark); border: 1px solid var(--border); display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: 0.7rem; color: var(--primary);">${upd.manager_name.charAt(0)}</div>`
                                                        }
                                                        <div>
                                                            <div style="font-weight: 700; color: var(--text-main); font-size: 0.8rem; line-height: 1;">${upd.manager_name}</div>
                                                            <div style="font-size: 0.6rem; color: var(--text-muted); opacity: 0.7;">${upd.manager_role || 'Manager'}</div>
                                                        </div>
                                                    </div>
                                                    <div style="text-align: right;">
                                                        <div style="font-weight: 800; color: var(--success); font-size: 0.85rem; line-height: 1;">+ ${upd.completed_units} Units</div>
                                                        <div style="font-size: 0.65rem; color: var(--text-muted); margin-top: 0.2rem;">${new Date(upd.created_at).toLocaleDateString()}</div>
                                                    </div>
                                                </div>
                                                <p style="color: var(--text-muted); font-size: 0.8rem; margin: 0 0 0.5rem 0; line-height: 1.4;">${upd.comments || 'No comments provided'}</p>
                                                ${(upd.attachments && upd.attachments.length > 0) ? `
                                                    <div style="display: flex; gap: 0.4rem; flex-wrap: wrap;">
                                                        ${upd.attachments.map(a => `
                                                            <a href="${a.file_path}" target="_blank" style="font-size: 0.65rem; color: var(--primary); text-decoration: none; display: flex; align-items: center; gap: 0.2rem; background: rgba(79, 70, 229, 0.05); padding: 0.2rem 0.5rem; border-radius: 4px;">
                                                                <i class="fas fa-paperclip"></i> ${a.file_name.length > 15 ? a.file_name.substring(0, 12) + '...' : a.file_name}
                                                            </a>
                                                        `).join('')}
                                                    </div>
                                                ` : ''}
                                            </div>
                                        `).join('')}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                `).join('')}
            </div>

            <!-- Final Stock Deduction Preview -->
            <div style="margin-top: 3rem; background: rgba(79, 70, 229, 0.03); border: 2px dashed var(--primary); border-radius: 24px; padding: 2rem;">
                <div style="display: flex; align-items: center; gap: 1rem; margin-bottom: 1.5rem;">
                    <div style="width: 40px; height: 40px; background: var(--primary); color: white; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 1.2rem;">
                        <i class="fas fa-calculator"></i>
                    </div>
                    <div>
                        <h4 style="font-size: 1.1rem; font-weight: 700; color: var(--text-main);">Stock Deduction Preview</h4>
                        <p style="font-size: 0.8rem; color: var(--text-muted);">Based on Stage 1 completion of <strong>${((data.stages[0].completed_units / (data.stages[0].quantity || 1)) * 100).toFixed(1)}%</strong></p>
                    </div>
                </div>
                
                <div id="final-deduction-list" style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem;">
                    <!-- Will be populated by JS -->
                    <div style="grid-column: 1 / -1; text-align: center; color: var(--text-muted); font-style: italic;">
                        Calculating material impact...
                    </div>
                </div>

                <div style="margin-top: 2rem; padding: 1rem; background: rgba(239, 68, 68, 0.05); border-radius: 12px; border: 1px solid rgba(239, 68, 68, 0.1); display: flex; gap: 1rem; align-items: center;">
                    <i class="fas fa-exclamation-circle" style="color: var(--danger);"></i>
                    <p style="font-size: 0.8rem; color: var(--text-muted); margin: 0;">
                        <strong>Note:</strong> Materials will be deducted from inventory proportional to Stage 1 output. 
                        This action is <strong>irreversible</strong> and will finalize all performance records for this production line.
                    </p>
                </div>
            </div>

            <div style="margin-top: 4rem; text-align: center; padding-bottom: 4rem;">
                ${currentProductionData.line.status !== 'Completed' ? `
                    <button class="btn" onclick="finishProduction()" 
                            style="padding: 1.5rem 5rem; font-size: 1.3rem; font-weight: 800; border-radius: 24px; background: var(--primary); color: white; border: none; cursor: pointer; transition: all 0.3s; box-shadow: 0 15px 40px rgba(79, 70, 229, 0.5); display: inline-flex; align-items: center; gap: 1rem;">
                        <i class="fas fa-check-circle" style="font-size: 1.8rem;"></i> FINISH PRODUCTION & DEDUCT STOCK
                    </button>
                    <p style="margin-top: 1rem; color: var(--text-muted); font-size: 0.9rem; font-weight: 500;">
                        Clicking this will close the workspace and update the inventory levels globally.
                    </p>
                ` : `
                    <div style="background: rgba(16, 185, 129, 0.1); color: var(--success); padding: 1.5rem 4rem; border-radius: 20px; font-weight: 800; display: inline-flex; align-items: center; gap: 1rem; border: 2px solid rgba(16, 185, 129, 0.3); font-size: 1.4rem; box-shadow: 0 10px 30px rgba(16, 185, 129, 0.2);">
                        <i class="fas fa-check-double" style="font-size: 2rem;"></i> PRODUCTION COMPLETED & ARCHIVED
                    </div>
                `}
            </div>
        </div>
    `;
    container.innerHTML = html;
    calculateFinalDeductionImpact();
}

async function calculateFinalDeductionImpact() {
    const data = currentProductionData;
    const stage1 = data.stages[0];
    const completedUnits = stage1.completed_units || 0;
    const targetUnits = data.stages.reduce((sum, s) => sum + (s.quantity || 0), 0) / data.stages.length; // Approximate line total
    
    // In a real app, I'd call an API. Here I'll simulate based on the check-stock logic but proportional
    // Actually, I'll just call the check-stock API and then scale the results locally for the preview
    
    const products = data.line.products || []; // We need products list
    if (products.length === 0) return;

    try {
        const result = await apiCall('production-lines', { action: 'check-stock', products: products.map(p => ({id: p.id, quantity: p.quantity})) });
        if (result.success) {
            const totalQty = parseFloat(data.line.total_quantity || 0);
            const completionFactor = totalQty > 0 ? (completedUnits / totalQty) : 0;
            const container = document.getElementById('final-deduction-list');
            
            container.innerHTML = result.materials.map(m => {
                const toDeduct = m.required * completionFactor;
                return `
                    <div style="background: var(--bg-dark); padding: 1rem 1.25rem; border-radius: 16px; border: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <div style="font-size: 0.85rem; font-weight: 700; color: var(--text-main);">${m.name}</div>
                            <div style="font-size: 0.7rem; color: var(--text-muted);">${m.unit}</div>
                        </div>
                        <div style="text-align: right;">
                            <div style="font-size: 1.1rem; font-weight: 800; color: var(--danger);">- ${toDeduct.toFixed(4)}</div>
                            <div style="font-size: 0.6rem; color: var(--text-muted); text-transform: uppercase;">TO BE DEDUCTED</div>
                        </div>
                    </div>
                `;
            }).join('');
        }
    } catch (e) {
        console.error('Impact calculation failed', e);
    }
}

function switchTab(btn, tabId) {
    // Update button states
    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    
    // Update content visibility
    document.querySelectorAll('.production-tab-content').forEach(c => c.classList.remove('active'));
    document.getElementById(tabId + '-content').classList.add('active');
}

function toggleCollapse(el) {
    const content = el.nextElementSibling;
    const icon = el.querySelector('.collapse-icon');
    const isHidden = content.style.display === 'none';
    
    content.style.display = isHidden ? 'block' : 'none';
    icon.style.transform = isHidden ? 'rotate(180deg)' : 'rotate(0deg)';
}

function updateStageFileNames(input) {
    const status = input.parentNode.querySelector('.file-status');
    status.innerText = input.files.length > 0 ? `${input.files.length} files selected` : 'No files selected';
    status.style.color = input.files.length > 0 ? 'var(--primary)' : 'var(--text-muted)';
    status.style.fontWeight = input.files.length > 0 ? '700' : '400';
}

async function submitStageUpdate(event, lineStageId) {
    event.preventDefault();
    const form = event.target;
    const btn = form.querySelector('button[type="submit"]');
    const originalHtml = btn.innerHTML;
    
    setLoading(btn, true);
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';

    try {
        const formData = new FormData(form);
        
        // Handle Image Compression (Parallel)
        const fileInput = document.getElementById(`stage_attachments_${lineStageId}`);
        if (fileInput && fileInput.files.length > 0) {
            btn.innerHTML = '<i class="fas fa-compress-arrows-alt fa-spin"></i> Optimizing Images...';
            formData.delete('attachments[]'); // Clear original
            
            const compressionPromises = Array.from(fileInput.files).map(file => compressImage(file));
            const compressedFiles = await Promise.all(compressionPromises);
            
            compressedFiles.forEach(file => {
                formData.append('attachments[]', file);
            });
        }

        formData.append('action', 'save-stage-update');
        formData.append('line_stage_id', lineStageId);

        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Uploading...';
        const result = await apiCall('production-lines', formData);
        
        if (result.success) {
            notify(result.message, 'success');
            await openUpdateWorkspace(currentProductionData.line.id);
        } else {
            notify(result.message, 'error');
            setLoading(btn, false);
            btn.innerHTML = originalHtml;
        }
    } catch (error) {
        console.error('Error saving update:', error);
        notify('Failed to save update', 'error');
        setLoading(btn, false);
        btn.innerHTML = originalHtml;
    }
}

function toggleCommentRequirement(select) {
    const form = select.closest('form');
    const currentStatus = form.dataset.currentStatus;
    const newStatus = select.value;
    
    const isBlocking = newStatus === 'Blocked';
    const isUnblocking = currentStatus === 'Blocked' && newStatus === 'Operational';
    const requiresComments = isBlocking || isUnblocking;
    
    // Units are required only for standard Operational updates (not unblocking)
    const requiresUnits = newStatus === 'Operational' && !isUnblocking;

    const unitsMark = document.getElementById('units-required-mark');
    if (unitsMark) unitsMark.style.display = requiresUnits ? 'inline' : 'none';
    
    const textarea = form.querySelector('textarea[name="comments"]');
    if (textarea) {
        textarea.required = true;
        if (isBlocking) {
            textarea.placeholder = 'MANDATORY: Describe the reason for blocking...';
        } else if (isUnblocking) {
            textarea.placeholder = 'MANDATORY: Describe how the issue was resolved to unblock...';
        } else {
            textarea.placeholder = 'Mention any blockers or batch details...';
        }
    }

    const unitsInput = form.querySelector('input[name="completed_units"]');
    if (unitsInput) {
        unitsInput.required = requiresUnits;
    }
}

async function deleteStageUpdate(id) {
    const confirmed = await confirmAction({
        title: 'Delete Progress Log',
        message: 'Are you sure you want to delete this log entry? The completed units will be subtracted from the stage total.',
        confirmText: 'Delete Log',
        confirmClass: 'var(--danger)'
    });

    if (confirmed) {
        try {
            const result = await apiCall('production-lines', { action: 'delete-stage-update', id: id });
            if (result.success) {
                notify(result.message);
                // Refresh the update workspace data
                await openUpdateWorkspace(currentProductionData.line.id);
            } else {
                notify(result.message, 'error');
            }
        } catch (error) {
            console.error('Error deleting update:', error);
            notify('Failed to delete log entry', 'error');
        }
    }
}

async function confirmCompleteStage(id, name) {
    if (await confirmAction({
        title: 'Complete Stage',
        message: `Are you sure you want to mark "${name}" as completed? This will trigger the next stage and notify relevant staff.`,
        confirmText: 'Complete Stage',
        confirmColor: 'var(--success)'
    })) {
        const result = await apiCall('production-lines', { action: 'complete-stage', line_stage_id: id });
        if (result.success) {
            notify(result.message, 'success');
            const lineId = document.getElementById('update-workspace').dataset.lineId;
            openUpdateWorkspace(lineId);
        } else {
            notify(result.message, 'error');
        }
    }
}

function closeUpdateWorkspace() {
    document.getElementById('update-workspace').style.display = 'none';
    document.getElementById('dashboard-view').style.display = 'block';
    location.reload();
}

async function finishProduction() {
    const lineId = currentProductionData.line.id;
    const confirmed = await confirmAction({
        title: 'Finish Production',
        message: 'This will finalize the production line, deduct materials from inventory based on Stage 1 completion, and close the workspace. Proceed?',
        confirmText: 'Finish Production',
        confirmColor: 'var(--primary)'
    });

    if (confirmed) {
        // Show loading state on button
        const btn = document.querySelector('button[onclick="finishProduction()"]');
        const originalHtml = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Finalizing...';

        try {
            const result = await apiCall('production-lines', { action: 'finish-line', id: lineId });
            if (result.success) {
                notify(result.message, 'success');
                setTimeout(() => location.reload(), 1500);
            } else {
                notify(result.message, 'error');
                btn.disabled = false;
                btn.innerHTML = originalHtml;
            }
        } catch (error) {
            console.error('Error finishing production:', error);
            notify('Failed to finish production', 'error');
            btn.disabled = false;
            btn.innerHTML = originalHtml;
        }
    }
}

async function openUpdateModal(id) {
    openUpdateWorkspace(id);
}


async function deleteProductionLine(id, name) {
    if (await confirmAction({
        title: 'Delete Production Line',
        message: `Are you sure you want to delete "${name}"? This will permanently remove all associated stages, staff assignments, tasks, and production logs. This action cannot be undone.`,
        confirmText: 'Delete Everything',
        confirmColor: 'var(--danger)'
    })) {
        const result = await apiCall('production-lines', { action: 'delete', id: id });
        if (result.success) {
            notify(result.message, 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            notify(result.message, 'error');
        }
    }
}
async function viewProductDetails(productId) {
    const body = document.getElementById('product-view-body');
    body.innerHTML = '<div style="text-align: center; padding: 3rem;"><i class="fas fa-spinner fa-spin fa-2x"></i></div>';
    openModal('productViewModal');

    try {
        const result = await apiCall('products', { action: 'get', id: productId });
        if (result.success) {
            const p = result.product;
            window.currentProductSamples = p.samples || [];
            window.currentSlideIndex = 0;
            const isImg = (path) => path && path.match(/\.(jpg|jpeg|png|gif|webp)$/i);

            body.innerHTML = `
                <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 2.5rem;">
                    <div>
                        <div style="font-size: 0.7rem; color: var(--text-muted); text-transform: uppercase; font-weight: 800; margin-bottom: 1rem; letter-spacing: 0.05em; display: flex; align-items: center; justify-content: space-between;">
                            <div style="display: flex; align-items: center; gap: 0.5rem;">
                                <i class="fas fa-images" style="color: var(--primary);"></i>
                                Product Samples
                            </div>
                            <div id="slide-counter" style="background: var(--bg-dark); padding: 0.2rem 0.6rem; border-radius: 20px; font-size: 0.6rem; color: var(--primary); border: 1px solid var(--border);">1 / ${window.currentProductSamples.length || 1}</div>
                        </div>
                        
                        <!-- Slideshow Container -->
                        <div style="position: relative; width: 100%; aspect-ratio: 1; background: var(--bg-dark); border-radius: 24px; border: 1px solid var(--border); box-shadow: var(--shadow-lg); overflow: hidden;">
                            <div id="slides-wrapper" style="width: 100%; height: 100%; display: flex; align-items: center; justify-content: center;">
                                ${window.currentProductSamples.length > 0 ? (isImg(window.currentProductSamples[0].file_path) 
                                    ? `<img src="${window.currentProductSamples[0].file_path}" style="width: 100%; height: 100%; object-fit: contain;">`
                                    : `<div style="text-align: center; color: var(--text-muted); padding: 2rem;"><i class="fas fa-file-alt fa-5x" style="margin-bottom: 1.5rem; opacity: 0.5;"></i><div style="font-size: 1rem; font-weight: 800; color: var(--text-main);">${window.currentProductSamples[0].file_name}</div></div>`)
                                    : (p.image 
                                        ? `<img src="${p.image}" style="width: 100%; height: 100%; object-fit: contain;">`
                                        : `<div style="text-align: center; color: var(--text-muted); opacity: 0.3;"><i class="fas fa-image fa-5x"></i><br><br>No Samples</div>`)
                                }
                            </div>

                            ${window.currentProductSamples.length > 1 ? `
                                <button onclick="changeSlide(-1)" style="position: absolute; left: 1rem; top: 50%; transform: translateY(-50%); width: 40px; height: 40px; border-radius: 50%; background: rgba(0,0,0,0.5); color: white; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; backdrop-filter: blur(4px); transition: all 0.2s;" onmouseover="this.style.background='var(--primary)'" onmouseout="this.style.background='rgba(0,0,0,0.5)'">
                                    <i class="fas fa-chevron-left"></i>
                                </button>
                                <button onclick="changeSlide(1)" style="position: absolute; right: 1rem; top: 50%; transform: translateY(-50%); width: 40px; height: 40px; border-radius: 50%; background: rgba(0,0,0,0.5); color: white; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; backdrop-filter: blur(4px); transition: all 0.2s;" onmouseover="this.style.background='var(--primary)'" onmouseout="this.style.background='rgba(0,0,0,0.5)'">
                                    <i class="fas fa-chevron-right"></i>
                                </button>
                            ` : ''}

                            ${window.currentProductSamples.length > 0 ? `
                                <div style="position: absolute; bottom: 1rem; right: 1rem; z-index: 5;">
                                    <button class="btn-icon" onclick="window.open(window.currentProductSamples[window.currentSlideIndex].file_path, '_blank')" style="background: rgba(255,255,255,0.1); backdrop-filter: blur(8px); color: white; border-radius: 10px; width: 36px; height: 36px;">
                                        <i class="fas fa-expand"></i>
                                    </button>
                                </div>
                            ` : ''}
                        </div>

                        <!-- Thumbnail Strip -->
                        <div style="display: flex; gap: 0.75rem; margin-top: 1rem; overflow-x: auto; padding-bottom: 0.5rem;" class="custom-scrollbar">
                            ${window.currentProductSamples.map((s, idx) => `
                                <div onclick="goToSlide(${idx})" style="flex: 0 0 60px; aspect-ratio: 1; border-radius: 12px; border: 2px solid ${idx === 0 ? 'var(--primary)' : 'var(--border)'}; overflow: hidden; background: var(--bg-dark); cursor: pointer; transition: all 0.2s;" class="slide-thumb" data-index="${idx}">
                                    ${isImg(s.file_path) ? `<img src="${s.file_path}" style="width: 100%; height: 100%; object-fit: cover;">` : `<div style="width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; color: var(--text-muted); font-size: 0.8rem;"><i class="fas fa-file"></i></div>`}
                                </div>
                            `).join('')}
                        </div>
                    </div>
                    <div>
                        <div style="margin-bottom: 2rem;">
                            <div style="font-size: 0.65rem; color: var(--text-muted); text-transform: uppercase; font-weight: 800; margin-bottom: 0.4rem; letter-spacing: 0.05em;">Product Information</div>
                            <div style="font-size: 1.75rem; font-weight: 900; color: var(--text-main); line-height: 1.2;">${p.name}</div>
                            <div style="display: flex; gap: 1rem; margin-top: 0.75rem;">
                                <span style="background: rgba(79, 70, 229, 0.1); color: var(--primary); padding: 0.2rem 0.6rem; border-radius: 6px; font-size: 0.75rem; font-weight: 800;">SKU: ${p.sku}</span>
                                <span style="background: var(--bg-dark); color: var(--text-muted); padding: 0.2rem 0.6rem; border-radius: 6px; font-size: 0.75rem; font-weight: 700;">${p.buyer_name || 'Generic Product'}</span>
                            </div>
                        </div>
                        
                        <div style="margin-bottom: 2rem;">
                            <div style="font-size: 0.65rem; color: var(--text-muted); text-transform: uppercase; font-weight: 800; margin-bottom: 0.6rem; letter-spacing: 0.05em;">Description</div>
                            <div style="font-size: 0.95rem; color: var(--text-muted); line-height: 1.6; background: var(--bg-dark); padding: 1rem; border-radius: 12px; border: 1px solid var(--border);">${p.description || 'No detailed description available for this product style.'}</div>
                        </div>

                        <div>
                            <div style="font-size: 0.65rem; color: var(--text-muted); text-transform: uppercase; font-weight: 800; margin-bottom: 0.8rem; letter-spacing: 0.05em;">Bill of Materials (BOM)</div>
                            <div style="background: var(--bg-dark); border-radius: 16px; border: 1px solid var(--border); overflow: hidden;">
                                ${(p.materials || []).map(m => `
                                    <div style="padding: 1rem; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; transition: background 0.2s;">
                                        <div style="display: flex; align-items: center; gap: 1rem;">
                                            <div style="width: 32px; height: 32px; background: var(--bg-card); border-radius: 8px; display: flex; align-items: center; justify-content: center; border: 1px solid var(--border);"><i class="fas fa-boxes" style="font-size: 0.8rem; color: var(--text-muted);"></i></div>
                                            <div>
                                                <div style="font-size: 0.9rem; font-weight: 700; color: var(--text-main);">${m.name}</div>
                                                <div style="font-size: 0.7rem; color: var(--text-muted); font-family: monospace;">${m.sku}</div>
                                            </div>
                                        </div>
                                        <div style="text-align: right;">
                                            <div style="font-size: 1rem; font-weight: 900; color: var(--primary);">${m.quantity} <span style="font-size: 0.7rem; color: var(--text-muted); font-weight: 500;">${m.unit}</span></div>
                                            <div style="font-size: 0.6rem; color: var(--text-muted); text-transform: uppercase; font-weight: 700;">Required</div>
                                        </div>
                                    </div>
                                `).join('') || '<div style="padding: 2rem; text-align: center; color: var(--text-muted); font-style: italic; font-size: 0.9rem;">No material requirements defined.</div>'}
                            </div>
                        </div>
                    </div>
                </div>
            `;
        } else {
            body.innerHTML = `<div style="text-align: center; padding: 4rem; color: var(--danger);"><i class="fas fa-exclamation-circle fa-3x"></i><br><br><div style="font-weight: 700;">${result.message}</div></div>`;
        }
    } catch (error) {
        body.innerHTML = '<div style="text-align: center; padding: 4rem; color: var(--danger);"><i class="fas fa-exclamation-circle fa-3x"></i><br><br><div style="font-weight: 700;">Failed to load product details. Please try again.</div></div>';
    }
}
function updateProductPreview(path, name, isImage) {
    const preview = document.getElementById('product-main-preview');
    if (isImage) {
        preview.innerHTML = `<img id="main-product-img" src="${path}" style="width: 100%; height: 100%; object-fit: cover; animation: fadeIn 0.3s;">`;
    } else {
        preview.innerHTML = `<div style="text-align: center; color: var(--text-muted); padding: 1.5rem; animation: fadeIn 0.3s;"><i class="fas fa-file-alt fa-4x" style="margin-bottom: 1rem; opacity: 0.5;"></i><div style="font-size: 0.8rem; font-weight: 700;">${name}</div></div>`;
    }
}
function changeSlide(direction) {
    const total = window.currentProductSamples.length;
    if (total <= 1) return;
    window.currentSlideIndex = (window.currentSlideIndex + direction + total) % total;
    updateSlideshowUI();
}

function goToSlide(index) {
    window.currentSlideIndex = index;
    updateSlideshowUI();
}

function updateSlideshowUI() {
    const s = window.currentProductSamples[window.currentSlideIndex];
    const wrapper = document.getElementById('slides-wrapper');
    const isImg = s.file_path.match(/\.(jpg|jpeg|png|gif|webp)$/i);
    
    wrapper.style.opacity = '0';
    setTimeout(() => {
        if (isImg) {
            wrapper.innerHTML = `<img src="${s.file_path}" style="width: 100%; height: 100%; object-fit: contain; animation: fadeIn 0.3s;">`;
        } else {
            wrapper.innerHTML = `<div style="text-align: center; color: var(--text-muted); padding: 2rem; animation: fadeIn 0.3s;"><i class="fas fa-file-alt fa-5x" style="margin-bottom: 1.5rem; opacity: 0.5;"></i><div style="font-size: 1rem; font-weight: 800; color: var(--text-main);">${s.file_name}</div></div>`;
        }
        wrapper.style.opacity = '1';
        document.getElementById('slide-counter').innerText = `${window.currentSlideIndex + 1} / ${window.currentProductSamples.length}`;
        
        // Update thumbnails
        document.querySelectorAll('.slide-thumb').forEach((thumb, idx) => {
            if (idx === window.currentSlideIndex) {
                thumb.style.borderColor = 'var(--primary)';
                thumb.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
            } else {
                thumb.style.borderColor = 'var(--border)';
            }
        });
    }, 200);
}
</script>
