<?php $__env->startSection('content'); ?>
<?php if(session('trigger_reload')): ?>
<script>
    localStorage.setItem('force_anomaly_rebuild', Date.now());
</script>
<?php endif; ?>
<div class="container-fluid py-3">
    <?php if(session('success')): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php echo e(session('success')); ?>

            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    <?php if(session('error')): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?php echo e(session('error')); ?>

            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

  <div class="row mb-4">
    <div class="col-12">
        <div class="position-relative text-center text-white rounded-3 shadow-sm overflow-hidden" style="height: 180px;">
            <!-- Background image -->
            <div class="position-absolute top-0 start-0 w-100 h-100"
                 style="background: url('/images/backgroundpelindo.jpg') center/cover no-repeat;">
            </div>

            <!-- Overlay biru transparan -->
            <div class="position-absolute top-0 start-0 w-100 h-100"
                 style="background: rgba(13, 110, 253, 0.7);">
            </div>

            <!-- Content -->
            <div class="position-relative d-flex flex-column justify-content-center align-items-center h-100">
                <h2 class="h4 fw-bold mb-1">BAPLIE MANAGEMENT</h2>
                <p class="mb-0 small">Manage container stowage, reefer settings, and more</p>
            </div>
        </div>
    </div>
</div>

<?php if(!empty($containers) && is_array($containers) && count($containers) > 0): ?>

    <?php
        // HELPER FUNCTION untuk safe count
        $safeCount = function($var) {
            return (is_array($var) && $var !== null) ? count($var) : 0;
        };

        // PERBAIKAN: NULL PROTECTION untuk semua variabel dengan validasi ketat
        $containers = $containers ?? [];
        $jenisCounts = $jenisCounts ?? [];
        $sizeBreakdown = $sizeBreakdown ?? [];
        $filteredSizeCounts = $filteredSizeCounts ?? [];
        $voyage = $voyage ?? [];

        // VALIDASI TIPE DATA yang lebih ketat
        $containers = (is_array($containers) && $containers !== null) ? $containers : [];
        $jenisCounts = (is_array($jenisCounts) && $jenisCounts !== null) ? $jenisCounts : [];
        $sizeBreakdown = (is_array($sizeBreakdown) && $sizeBreakdown !== null) ? $sizeBreakdown : [];
        $voyage = (is_array($voyage) && $voyage !== null) ? $voyage : [];

        $totalContainers = $safeCount($containers); // Gunakan safe count
        $totalWeight = 0;

        // PERBAIKAN: Gabungkan loop untuk efisiensi dengan NULL PROTECTION
        $containersWithPosition = 0;
        $containersWithoutPosition = 0;

        if (!empty($containers) && is_array($containers)) {
            foreach($containers as $container) {
                // VALIDASI: Pastikan $container adalah array
                if (!is_array($container)) {
                    continue;
                }

                // Hitung weight
                if (isset($container['weight_kg']) && is_numeric($container['weight_kg'])) {
                    $totalWeight += (float) $container['weight_kg'];
                }

                // Hitung posisi dalam loop yang sama
                $bay = $container['bay'] ?? '';
                $row = $container['row'] ?? '';
                $tier = $container['tier'] ?? '';

                if (!empty($bay) && !empty($row) && !empty($tier) && $bay !== '0' && $row !== '0' && $tier !== '0') {
                    $containersWithPosition++;
                } else {
                    $containersWithoutPosition++;
                }
            }
        }
    ?>

    <div class="row g-3">
        
        <div class="col-lg-6">
            <div class="card h-100 shadow-sm border-0 rounded-3 overflow-hidden">
                <!-- Header -->
                <div class="card-header text-white py-3"
                    style="background: linear-gradient(90deg, #0d6efd 0%, #0a58ca 100%);">
                    <h6 class="card-title mb-0 d-flex align-items-center fw-semibold">
                        <i class="bi bi-ship me-2 fs-5"></i> Voyage Details
                    </h6>
                </div>
                <div class="card-body p-3">
                    <?php if(!empty($voyage)): ?>
                        
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <div>
                                <h5 class="mb-1 text-primary fw-bold"><?php echo e($voyage['vessel_name'] ?? 'N/A'); ?></h5>
                                <small class="text-muted">
                                    Voyage: <strong><?php echo e($voyage['voyage_no'] ?? 'N/A'); ?></strong>
                                    <?php if(!empty($voyage['call_sign'])): ?>
                                        | Call: <strong><?php echo e($voyage['call_sign']); ?></strong>
                                    <?php endif; ?>
                                </small>
                            </div>
                        </div>


                        
                        <div class="row text-center mb-2 g-2">
                            <div class="col-6">
                                <h4 class="text-info mb-1" id="totalContainersDisplay"><?php echo e($totalContainers); ?></h4>
                                <small class="text-muted">Containers</small>
                            </div>
                            <div class="col-6">
                                <h4 class="text-success mb-1" id="totalWeightDisplay"><?php echo e($totalWeight > 0 ? number_format($totalWeight / 1000, 1) : '0.0'); ?></h4>
                                <small class="text-muted">Weight (tons)</small>
                            </div>
                        </div>

                        <hr class="my-2">

                        
                        <div class="table-responsive">
                            <table class="table table-sm mb-0" style="font-size: 0.8rem;">
                                <tbody>
                                    
                                    

                                    <?php if(isset($voyage['carrier_code']) && !empty($voyage['carrier_code'])): ?>
                                        <tr>
                                            <th class="w-50">Vessel Code:</th>
                                            <td><span class="badge bg-secondary fs-6"><?php echo e($voyage['carrier_code']); ?></span></td>
                                        </tr>
                                    <?php endif; ?>
                                    <?php if(isset($voyage['port_of_loading'])): ?>
                                        <tr>
                                            <th>PoL:</th>
                                            <td><span class="badge bg-info fs-6"><?php echo e($voyage['port_of_loading']); ?></span></td>
                                        </tr>
                                    <?php endif; ?>
                                    <?php if(isset($voyage['departure_date'])): ?>
                                        <tr>
                                            <th>Departure:</th>
                                            <td class="text-nowrap"><?php echo e($voyage['departure_date']); ?></td>
                                        </tr>
                                    <?php endif; ?>
                                    <?php if(isset($voyage['arrival_date'])): ?>
                                        <tr>
                                            <th>Arrival:</th>
                                            <td class="text-nowrap"><?php echo e($voyage['arrival_date']); ?></td>
                                        </tr>
                                    <?php endif; ?>
                                    <?php if(isset($voyage['actual_arrival_date'])): ?>
                                        <tr>
                                            <th>Actual:</th>
                                            <td class="text-nowrap"><?php echo e($voyage['actual_arrival_date']); ?></td>
                                        </tr>
                                    <?php endif; ?>
                                    <?php if(isset($voyage['sender'])): ?>
                                        <tr>
                                            <th>Sender:</th>
                                            <td><small class="text-muted"><?php echo e($voyage['sender']); ?></small></td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="text-center text-muted py-3">
                            <i class="bi bi-ship" style="font-size: 2rem; opacity: 0.3;"></i>
                            <h6 class="mt-2">No Voyage Data</h6>
                            <small class="mb-0">Upload BAPLIE file to view</small>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        
        <div class="col-lg-6">
            <div class="card h-100 shadow-sm border-0 rounded-3 overflow-hidden">
                <!-- Header -->
                <div class="card-header text-white py-3"
                    style="background: linear-gradient(90deg, #0d6efd 0%, #0a58ca 100%);">
                    <h6 class="card-title mb-0 d-flex align-items-center fw-semibold">
                        <i class="bi bi-geo-alt me-1 fs-6"></i> Port Summary
                    </h6>
                </div>
                <div class="card-body p-3">
                    <?php
                        $portSummary = [];
                        // NULL PROTECTION dan validasi array
                        if (!empty($containers) && is_array($containers)) {
                            foreach($containers as $c) {
                                // VALIDASI: Pastikan $c adalah array
                                if (!is_array($c)) {
                                    continue;
                                }

                                if(!empty($c['pod_locode'])) {
                                    if(!isset($portSummary[$c['pod_locode']])) {
                                        $portSummary[$c['pod_locode']] = ['count' => 0, 'weight' => 0];
                                    }
                                    $portSummary[$c['pod_locode']]['count']++;
                                    if (isset($c['weight_kg']) && is_numeric($c['weight_kg'])) {
                                        $portSummary[$c['pod_locode']]['weight'] += (float) $c['weight_kg'];
                                    }
                                }
                            }
                        }

                        // Sort by count (descending) dengan safe check
                        if (!empty($portSummary) && is_array($portSummary)) {
                            arsort($portSummary);
                        }
                    ?>

                    <?php if(!empty($portSummary) && is_array($portSummary) && $safeCount($portSummary) > 0): ?>
                        <div class="table-responsive" style="max-height: 300px;">
                            <table class="table table-sm table-striped mb-0" style="font-size: 0.8rem;">
                                <thead class="table-dark">
                                    <tr>
                                        <th style="width: 40%;">Port</th>
                                        <th class="text-center" style="width: 30%;">Containers</th>
                                        <th class="text-end" style="width: 30%;">Weight (t)</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php $__currentLoopData = $portSummary; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $port => $data): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <tr>
                                            <td><strong class="text-uppercase"><?php echo e($port); ?></strong></td>
                                            <td class="text-center">
                                                <span class="badge bg-primary fs-6"><?php echo e($data['count'] ?? 0); ?></span>
                                            </td>
                                            <td class="text-end"><?php echo e(($data['weight'] ?? 0) > 0 ? number_format(($data['weight'] ?? 0) / 1000, 1) : '0.0'); ?></td>
                                        </tr>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="text-center text-muted py-3">
                            <i class="bi bi-geo-alt" style="font-size: 2rem; opacity: 0.3;"></i>
                            <h6 class="mt-2">No Port Data</h6>
                            <small class="mb-0">Upload BAPLIE file to view</small>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <div class="card mt-3 shadow-sm border-0 rounded-3 overflow-hidden">
    <div class="card-header text-white py-3"
    style="background: linear-gradient(90deg, #0d6efd 0%, #0a58ca 100%);">
    <div class="d-flex justify-content-between align-items-center">
        <h6 class="card-title mb-0 fw-semibold d-flex align-items-center">
            <i class="bi bi-box-seam me-2 fs-5"></i> Container List
        </h6>
        <div class="d-flex align-items-center gap-2">
        <?php
        $totalAnomalies = $containerAnomalies['summary']['total_anomalies'] ?? 0;
        $criticalCount = $containerAnomalies['severity_classification']['critical_count'] ?? 0;
        $warningCount = $containerAnomalies['severity_classification']['warning_count'] ?? 0;

        // Button color based on severity
        if ($criticalCount > 0) {
            $badgeClass = 'btn-danger';
            $iconClass = 'exclamation-octagon';
            $buttonText = "🔴 Critical: $criticalCount | ⚠️ Warning: $warningCount";
        } elseif ($warningCount > 0) {
            $badgeClass = 'btn-warning';
            $iconClass = 'exclamation-triangle';
            $buttonText = "⚠️ Warnings: $warningCount";
        } else {
            $badgeClass = 'btn-success';
            $iconClass = 'check-circle';
            $buttonText = "✅ No Issues";
        }
    ?>

    <button id="btnFilterAnomaly" type="button" class="btn btn-sm <?php echo e($badgeClass); ?>"
            title="Critical blocks export, Warnings allow export">
        <i class="bi bi-<?php echo e($iconClass); ?>-fill me-1"></i>
        <?php echo e($buttonText); ?>

    </button>


            
            <span class="badge bg-light text-dark px-3 py-2 rounded-pill shadow-sm">
                <?php echo e(count($containers)); ?> containers
            </span>
        </div>
    </div>
</div>
        <div class="card-body p-0">
            <div class="mb-3 px-3 pt-3">
                <div class="row align-items-end g-2">
                    <div class="col-md-3 mb-2">
                        <label for="searchField" class="form-label small">Search In:</label>
                        <select id="searchField" class="form-select form-select-sm">
                            <option value="all">All Columns</option>
                            <option value="container_no">Container No</option>
                            <option value="iso_type">ISO Type</option>
                            <option value="size">Size</option>
                            <option value="jenis">Jenis</option>
                            <option value="status">Status</option>
                            <option value="position">Position</option>
                            <option value="pol_locode">Port of Loading</option>
                            <option value="pod_locode">Port of Discharge</option>
                            <option value="delivery_locode">Delivery Port</option>
                            <option value="operator_code">Operator</option>
                            <option value="handling_instruction">Handling</option>
                        </select>
                    </div>
                    <div class="col-md-6 mb-2">
                        <label for="searchInput" class="form-label small">Search Term:</label>
                        <div class="input-group">
                            <input type="text" id="searchInput" class="form-control form-control-sm"
                                   placeholder="Enter search term...">
                            <button class="btn btn-outline-secondary btn-sm" type="button" id="clearSearch">
                                <i class="bi bi-x"></i>
                            </button>
                        </div>
                    </div>
                    <div class="col-md-3 mb-2">
                        <div class="d-flex gap-1">
                            <button id="searchBtn" class="btn btn-primary btn-sm">
                                <i class="bi bi-search"></i> Search
                            </button>
                        </div>
                    </div>
                </div>

                
                <div class="collapse mt-2" id="advancedFilters">
                    <div class="card card-body py-2">
                        <div class="row g-2">
                            <div class="col-md-2">
                                <label class="form-label small">Status:</label>
                                <select id="filterStatus" class="form-select form-select-sm">
                                    <option value="">All Status</option>
                                    <option value="Full">Full</option>
                                    <option value="Empty">Empty</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label small">Size:</label>
                                <select id="filterSize" class="form-select form-select-sm">
                                    <option value="">All Sizes</option>
                                    <option value="20'">20'</option>
                                    <option value="40'">40'</option>
                                    <option value="45'">45'</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label small">Jenis:</label>
                                <select id="filterJenis" class="form-select form-select-sm">
                                    <option value="">All Jenis</option>
                                    <option value="dry">Dry</option>
                                    <option value="reefer">Reefer</option>
                                    <option value="tank">Tank</option>
                                    <option value="flat">Flat Rack</option>
                                    <option value="empty">Empty</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label small">Position Issues:</label>
                                <select id="filterPosition" class="form-select form-select-sm">
                                    <option value="">All Positions</option>
                                    <option value="missing">Missing Position</option>
                                    <option value="assigned">With Position</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label small">Reefer:</label>
                                <select id="filterReefer" class="form-select form-select-sm">
                                    <option value="">All Types</option>
                                    <option value="reefer">Reefer Only</option>
                                    <option value="non-reefer">Non-Reefer Only</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="mt-2">
                    <button class="btn btn-link btn-sm p-0" type="button" data-bs-toggle="collapse"
                            data-bs-target="#advancedFilters" aria-expanded="false">
                        <i class="bi bi-funnel"></i> Advanced Filters
                    </button>
                    <span id="activeFilters" class="badge bg-info ms-2" style="display: none;">0 filters active</span>
                </div>
            </div>

            <div class="table-responsive px-3 pb-3">
                <table class="table table-striped table-hover table-sm mb-0" style="font-size: 0.8rem;">
                    <thead class="table-dark">
                        <tr>
                            <th style="width: 35px;">No</th>
                            <th style="width: 120px;">Container No</th>
                            <th style="width: 70px;">ISO</th>
                            <th style="width: 45px;">Size</th>
                            <th style="width: 70px;">Group</th>
                            <th style="width: 60px;">Jenis</th>
                            <th class="text-end" style="width: 80px;">Weight (kg)</th>
                            <th style="width: 80px;">Position</th>
                            <th style="width: 50px;">PoL</th>
                            <th style="width: 50px;">PoD</th>
                            <th style="width: 55px;">Del</th>
                            <th style="width: 60px;">Operator</th>
                            <th style="width: 70px;">Handling</th>
                            <th style="width: 60px;">Status</th>
                            <th style="width: 70px;">Temp</th>
                            <th style="width: 85px;">Actions</th>
                        </tr>
                    </thead>
                    <tbody id="containerTableBody">
                        
                    </tbody>
                </table>
            </div>

            
            <div class="d-flex justify-content-between align-items-center px-3 pb-3">
                <div>
                    <button id="prevPage" class="btn btn-outline-primary btn-sm" disabled>Previous</button>
                    <button id="nextPage" class="btn btn-outline-primary btn-sm" disabled>Next</button>
                </div>
                <span id="pageInfo" class="fw-semibold" style="font-size: 0.85rem;"></span>
                <div>
                    <select id="rowsPerPageSelect" class="form-select form-select-sm" style="width: auto; font-size: 0.8rem;">
                        <option value="5" selected>5 per page</option>
                        <option value="10">10 per page</option>
                        <option value="25">25 per page</option>
                        <option value="50">50 per page</option>
                        <option value="100">100 per page</option>
                    </select>
                </div>
            </div>
        </div>
    </div>


<?php
    // ✅ TRUST BACKEND DATA - Jangan re-calculate
    $containers = session('containers', []);
    $statusBreakdown = session('status_breakdown', []);
    $jenisBreakdown = session('jenis_breakdown', []);
    $sizeBreakdown = session('size_breakdown', []);
    $weightDebug = session('weight_debug', []);
    $containerAnomalies = session('container_anomalies', []);

    // ✅ Extract counts from backend calculations
    $countFull = $statusBreakdown['5']['count'] ?? 0;
    $countEmpty = $statusBreakdown['4']['count'] ?? 0;
    $countUnknown = $statusBreakdown['U']['count'] ?? 0;
    $totalContainers = count($containers);

    // ✅ Use pre-calculated values from backend
    $containersWithPosition = $weightDebug['containers_with_position'] ?? 0;
    $containersWithoutPosition = $weightDebug['containers_without_position'] ?? 0;
    $totalWeightTons = $weightDebug['total_weight_tons'] ?? 0;
    $containersWithWeight = $weightDebug['containers_with_weight'] ?? 0;

    // ✅ Anomaly counts
    $totalAnomalies = $containerAnomalies['summary']['total_anomalies'] ?? 0;
    $duplicatePositions = $containerAnomalies['summary']['duplicate_positions_count'] ?? 0;
    $fullOverload = $containerAnomalies['summary']['full_overload_count'] ?? 0;

    // ✅ Validate data consistency (optional, for debugging)
    if (($countFull + $countEmpty + $countUnknown) !== $totalContainers && $totalContainers > 0) {
        \Log::warning('Blade: Status breakdown count mismatch', [
            'total' => $totalContainers,
            'full' => $countFull,
            'empty' => $countEmpty,
            'unknown' => $countUnknown,
            'sum' => $countFull + $countEmpty + $countUnknown
        ]);
    }
?>

<?php
    // Hitung breakdown per PoL dari data container yang sebenarnya
    $polBreakdown = [];
    foreach($containers as $container) {
        // Ambil PoL dari container, fallback ke 'Unknown' jika tidak ada
        $pol = $container['pol_locode'] ?? $container['pol'] ?? $container['POL'] ?? 'Unknown';
        $pol = strtoupper(trim($pol)); // Normalisasi

        if (!isset($polBreakdown[$pol])) {
            $polBreakdown[$pol] = [
                'total' => 0,
                'full' => 0,
                'empty' => 0,
                'unknown' => 0,
                'with_position' => 0,
                'size_20' => 0,
                'size_40' => 0,
                'size_45' => 0,
                'size_other' => 0,
                'jenis' => [],
                'reefer_total' => 0,
                'reefer_with_temp' => 0,
                'reefer_temps' => []
            ];
        }

        $polBreakdown[$pol]['total']++;

        // Status
        $statusCode = $container['status_code'] ?? $container['status'] ?? 'U';
        if ($statusCode == '5' || $statusCode == 'F' || $statusCode == 'Full') $polBreakdown[$pol]['full']++;
        elseif ($statusCode == '4' || $statusCode == 'E' || $statusCode == 'Empty') $polBreakdown[$pol]['empty']++;
        else $polBreakdown[$pol]['unknown']++;

        // Position
        if (!empty($container['bay']) && !empty($container['row']) && !empty($container['tier'])) {
            $polBreakdown[$pol]['with_position']++;
        }

        // Size
        $size = $container['size'] ?? $container['iso_type'] ?? '';
        if (strpos($size, '20') !== false) $polBreakdown[$pol]['size_20']++;
        elseif (strpos($size, '40') !== false) $polBreakdown[$pol]['size_40']++;
        elseif (strpos($size, '45') !== false) $polBreakdown[$pol]['size_45']++;
        else $polBreakdown[$pol]['size_other']++;

        // Jenis
        $jenis = strtolower($container['jenis'] ?? 'unknown');
        if (!isset($polBreakdown[$pol]['jenis'][$jenis])) {
            $polBreakdown[$pol]['jenis'][$jenis] = 0;
        }
        $polBreakdown[$pol]['jenis'][$jenis]++;

        // Reefer
        if ($container['is_reefer'] ?? false) {
            $polBreakdown[$pol]['reefer_total']++;
            if (!empty($container['set_temperature'])) {
                $polBreakdown[$pol]['reefer_with_temp']++;
                $polBreakdown[$pol]['reefer_temps'][] = floatval($container['set_temperature']);
            }
        }
    }

    // Sort by PoL name, tapi IDSRG di atas
    // Di bagian sorting:
    uksort($polBreakdown, function($a, $b) {
        $semarangCodes = ['IDSRG', 'SMG', 'IDSMG', 'SEMARANG'];
        if (in_array($a, $semarangCodes)) return -1;
        if (in_array($b, $semarangCodes)) return 1;
        return strcmp($a, $b);
    });
?>

<div class="row mt-4 mb-4">
    <div class="col-lg-12">
        <div class="card shadow-sm border-0 rounded-3 overflow-hidden">
            <!-- Header -->
            <div class="card-header text-white py-3"
                 style="background: linear-gradient(90deg, #198754 0%, #157347 100%);">
                <h6 class="mb-0 fw-semibold d-flex align-items-center">
                    <i class="bi bi-bar-chart-line me-2 fs-5"></i> Container Summary by Port of Loading
                </h6>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-sm mb-0" style="font-size: 0.8rem;">
                        <thead style="background-color: #f8f9fa;">
                            <tr>
                                <th class="text-center" style="border: 1px solid #dee2e6;">PoL</th>
                                <th class="text-center" style="border: 1px solid #dee2e6;">Full</th>
                                <th class="text-center" style="border: 1px solid #dee2e6;">Empty</th>
                                <th class="text-center" style="border: 1px solid #dee2e6;">Unknown</th>
                                <th class="text-center" style="border: 1px solid #dee2e6;">Total</th>
                                <th class="text-center" style="border: 1px solid #dee2e6;">With Pos</th>
                                <th class="text-center" style="border: 1px solid #dee2e6;">No Pos</th>
                                <th class="text-center" style="border: 1px solid #dee2e6;">20'</th>
                                <th class="text-center" style="border: 1px solid #dee2e6;">40'</th>
                                <th class="text-center" style="border: 1px solid #dee2e6;">45'</th>
                                <th class="text-center" style="border: 1px solid #dee2e6;">Others</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $__currentLoopData = $polBreakdown; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $pol => $data): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <tr style="<?php echo e(in_array($pol, ['IDSRG', 'SMG', 'IDSMG', 'SEMARANG']) ? 'background-color: #fff3cd;' : ''); ?>">
                                <td class="text-center fw-bold" style="border: 1px solid #dee2e6;">
                                    <span class="badge bg-primary"><?php echo e($pol); ?></span>
                                </td>
                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php echo e($data['full']); ?>

                                </td>
                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php echo e($data['empty']); ?>

                                </td>
                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php echo e($data['unknown']); ?>

                                </td>
                                <td class="text-center fw-bold" style="border: 1px solid #dee2e6;">
                                    <?php echo e($data['total']); ?>

                                </td>
                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php echo e($data['with_position']); ?>

                                </td>
                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php $noPos = $data['total'] - $data['with_position']; ?>
                                    <?php echo e($noPos > 0 ? $noPos : 0); ?>

                                </td>
                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php echo e($data['size_20']); ?>

                                </td>
                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php echo e($data['size_40']); ?>

                                </td>
                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php echo e($data['size_45']); ?>

                                </td>
                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php echo e($data['size_other']); ?>

                                </td>
                            </tr>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

                            
                            <tr style="background-color: #f8f9fa; font-weight: bold; border-top: 2px solid #dee2e6;">
                                <td class="text-center" style="border: 1px solid #dee2e6;">TOTAL</td>
                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php echo e($countFull); ?>

                                </td>
                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php echo e($countEmpty); ?>

                                </td>
                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php echo e($countUnknown); ?>

                                </td>
                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php echo e($totalContainers); ?>

                                </td>
                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php echo e($containersWithPosition); ?>

                                </td>
                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php echo e($containersWithoutPosition > 0 ? $containersWithoutPosition : 0); ?>

                                </td>
                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php echo e($sizeBreakdown["20'"]["count"] ?? 0); ?>

                                </td>
                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php echo e($sizeBreakdown["40'"]["count"] ?? 0); ?>

                                </td>
                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php echo e($sizeBreakdown["45'"]["count"] ?? 0); ?>

                                </td>
                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php
                                        $otherSizes = 0;
                                        foreach($sizeBreakdown as $size => $count) {
                                            if (!in_array($size, ["20'", "40'", "45'"])) {
                                                $otherSizes += is_array($count) ? ($count['count'] ?? 0) : $count;
                                            }
                                        }
                                    ?>
                                    <?php echo e($otherSizes); ?>

                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>


<div class="row mb-4">
    <div class="col-lg-12">
        <div class="card shadow-sm border-0 rounded-3 overflow-hidden">
            <div class="card-header text-white py-3"
                 style="background: linear-gradient(90deg, #0dcaf0 0%, #0aa2c0 100%);">
                <h6 class="mb-0 fw-semibold d-flex align-items-center">
                    <i class="bi bi-boxes me-2 fs-5"></i> Container Type & Reefer Analysis by Port of Loading
                </h6>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-sm mb-0" style="font-size: 0.8rem;">
                        <thead style="background-color: #f8f9fa;">
                            <tr>
                                <th class="text-center" style="border: 1px solid #dee2e6;">PoL</th>
                                <?php
                                    // Get all unique jenis from all containers
                                    $allJenis = [];
                                    foreach($containers as $c) {
                                        $j = strtolower($c['jenis'] ?? 'unknown');
                                        if (!in_array($j, $allJenis)) {
                                            $allJenis[] = $j;
                                        }
                                    }
                                    sort($allJenis);
                                ?>

                                <?php $__currentLoopData = $allJenis; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $jenis): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <th class="text-center" style="border: 1px solid #dee2e6;"><?php echo e(ucfirst($jenis)); ?></th>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

                                <th class="text-center fw-bold" style="border: 1px solid #dee2e6;">Total Type</th>
                                <th class="text-center" style="border: 1px solid #dee2e6; border-left: 2px solid #0dcaf0;">Reefer</th>
                                <th class="text-center" style="border: 1px solid #dee2e6;">With Temp</th>
                                <th class="text-center" style="border: 1px solid #dee2e6;">Avg Temp</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $__currentLoopData = $polBreakdown; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $pol => $data): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <tr style="<?php echo e(in_array($pol, ['IDSRG', 'SMG', 'IDSMG', 'SEMARANG']) ? 'background-color: #fff3cd;' : ''); ?>">
                                <td class="text-center fw-bold" style="border: 1px solid #dee2e6;">
                                    <span class="badge bg-primary"><?php echo e($pol); ?></span>
                                </td>

                                <?php $totalJenisPerPol = 0; ?>
                                <?php $__currentLoopData = $allJenis; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $jenis): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <?php
                                        $jenisCount = $data['jenis'][$jenis] ?? 0;
                                        $totalJenisPerPol += $jenisCount;
                                    ?>
                                    <td class="text-center" style="border: 1px solid #dee2e6;">
                                        <?php if($jenisCount > 0): ?>
                                            <div><?php echo e($jenisCount); ?></div>
                                            <small class="text-muted">
                                                (<?php echo e($data['total'] > 0 ? round(($jenisCount / $data['total']) * 100, 1) : 0); ?>%)
                                            </small>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

                                <td class="text-center fw-bold" style="background-color: #f8f9fa; border: 1px solid #dee2e6;">
                                    <?php echo e($totalJenisPerPol); ?>

                                </td>

                                <td class="text-center" style="border: 1px solid #dee2e6; border-left: 2px solid #0dcaf0;">
                                    <?php echo e($data['reefer_total'] > 0 ? $data['reefer_total'] : '-'); ?>

                                </td>

                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php if($data['reefer_with_temp'] > 0): ?>
                                        <div><?php echo e($data['reefer_with_temp']); ?></div>
                                        <small class="text-muted">
                                            (<?php echo e($data['reefer_total'] > 0 ? round(($data['reefer_with_temp'] / $data['reefer_total']) * 100, 1) : 0); ?>%)
                                        </small>
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>

                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php if(!empty($data['reefer_temps'])): ?>
                                        <?php $avgTempPol = array_sum($data['reefer_temps']) / count($data['reefer_temps']); ?>
                                        <?php echo e(number_format($avgTempPol, 1)); ?>°C
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

                            
                            <tr style="background-color: #f8f9fa; font-weight: bold; border-top: 2px solid #dee2e6;">
                                <td class="text-center" style="border: 1px solid #dee2e6;">TOTAL</td>

                                <?php $__currentLoopData = $allJenis; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $jenis): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <?php
                                        $totalPerJenis = 0;
                                        foreach($polBreakdown as $polData) {
                                            $totalPerJenis += $polData['jenis'][$jenis] ?? 0;
                                        }
                                    ?>
                                    <td class="text-center" style="border: 1px solid #dee2e6;">
                                        <div><?php echo e($totalPerJenis); ?></div>
                                        <small class="text-muted">
                                            (<?php echo e($totalContainers > 0 ? round(($totalPerJenis / $totalContainers) * 100, 1) : 0); ?>%)
                                        </small>
                                    </td>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php echo e($totalContainers); ?>

                                </td>

                                <?php
                                    $totalReefer = 0;
                                    $totalReeferWithTemp = 0;
                                    $allReeferTemps = [];
                                    foreach($polBreakdown as $polData) {
                                        $totalReefer += $polData['reefer_total'];
                                        $totalReeferWithTemp += $polData['reefer_with_temp'];
                                        $allReeferTemps = array_merge($allReeferTemps, $polData['reefer_temps']);
                                    }
                                ?>

                                <td class="text-center" style="border: 1px solid #dee2e6; border-left: 2px solid #0dcaf0;">
                                    <?php echo e($totalReefer); ?>

                                </td>

                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php if($totalReeferWithTemp > 0): ?>
                                        <div><?php echo e($totalReeferWithTemp); ?></div>
                                        <small class="text-muted">
                                            (<?php echo e($totalReefer > 0 ? round(($totalReeferWithTemp / $totalReefer) * 100, 1) : 0); ?>%)
                                        </small>
                                    <?php else: ?>
                                        -
                                    <?php endif; ?>
                                </td>

                                <td class="text-center" style="border: 1px solid #dee2e6;">
                                    <?php if(!empty($allReeferTemps)): ?>
                                        <?php echo e(number_format(array_sum($allReeferTemps) / count($allReeferTemps), 1)); ?>°C
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <?php if($containersWithoutPosition > 0): ?>
    <div class="col-lg-6 mb-3">
        <div class="alert alert-warning mb-0">
            <h6><i class="bi bi-exclamation-triangle"></i> Position Data Warning</h6>
            <p class="mb-1"><?php echo e($containersWithoutPosition); ?> containers missing position data (Bay-Row-Tier).</p>
            <?php if($totalContainers > 0 && ($containersWithoutPosition / $totalContainers) > 0.5): ?>
            <small class="text-muted">Consider checking BAPLIE file format with LOC+147 segments.</small>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php if($countUnknown > 0): ?>
    <div class="col-lg-6 mb-3">
        <div class="alert alert-info mb-0">
            <h6><i class="bi bi-info-circle"></i> Status Information</h6>
            <p class="mb-1"><?php echo e($countUnknown); ?> containers have unknown status.</p>
            <small class="text-muted">Verify status codes in BAPLIE EQD segments.</small>
        </div>
    </div>
    <?php endif; ?>
    <?php else: ?>
</div>
       
        <div class="row">
            <div class="col-12">
                <div class="card border-0 shadow-sm">
                    <div class="card-body text-center py-5">
                        <i class="bi bi-cloud-upload" style="font-size: 5rem; color: #0d6efd; opacity: 0.5;"></i>
                        <h3 class="mt-4 mb-3">Welcome to BAPLIE Management</h3>
                        <p class="text-muted mb-4">Upload a BAPLIE file to start managing your container stowage data</p>

                        <div class="row mt-5 text-start">
                            <div class="col-md-4">
                                <div class="p-3">
                                    <div class="text-primary mb-2">
                                        <i class="bi bi-file-earmark-text" style="font-size: 2rem;"></i>
                                    </div>
                                    <h6>1. Upload File</h6>
                                    <small class="text-muted">Upload your BAPLIE EDI file in standard format</small>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="p-3">
                                    <div class="text-success mb-2">
                                        <i class="bi bi-check-circle" style="font-size: 2rem;"></i>
                                    </div>
                                    <h6>2. Auto Parse</h6>
                                    <small class="text-muted">System automatically parses container data and positions</small>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="p-3">
                                    <div class="text-info mb-2">
                                        <i class="bi bi-bar-chart" style="font-size: 2rem;"></i>
                                    </div>
                                    <h6>3. Manage & Analyze</h6>
                                    <small class="text-muted">View statistics, edit containers, and detect anomalies</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>

</div>
<?php $__env->stopSection(); ?>
<style>
.table th, .table td {
    vertical-align: middle;
    border: 1px solid #dee2e6;
    padding: 0.4rem 0.3rem;
}
.table thead th {
    font-weight: 600;
    border-bottom: 2px solid #dee2e6;
    font-size: 0.8rem;
}
.badge {
    font-size: 0.7rem;
}

/* ✅ CRITICAL FIX: Override Bootstrap table-striped untuk anomaly rows */
.table-striped tbody tr.table-danger,
.table tbody tr.table-danger {
    background-color: #f8d7da !important;
    border-left: 4px solid #dc3545 !important;
}

.table-striped tbody tr.table-danger:hover,
.table tbody tr.table-danger:hover {
    background-color: #f1aeb5 !important;
}

.table-striped tbody tr.table-danger td,
.table tbody tr.table-danger td {
    background-color: transparent !important;
}

/* ✅ CRITICAL FIX: Warning rows KUNING - override striped */
.table-striped tbody tr.table-warning,
.table tbody tr.table-warning {
    background-color: #fff3cd !important;
    border-left: 4px solid #ffc107 !important;
}

.table-striped tbody tr.table-warning:hover,
.table tbody tr.table-warning:hover {
    background-color: #ffe69c !important;
}

.table-striped tbody tr.table-warning td,
.table tbody tr.table-warning td {
    background-color: transparent !important;
}

.table-info-new {
    background-color: #e6f7ff !important;
    transition: background-color 1s ease-out;
}

.spinner-border-sm {
    width: 1rem;
    height: 1rem;
    border-width: 0.15em;
}

.form-select-sm, .form-control-sm {
    font-size: 0.8rem;
}

.table thead th {
    font-size: 0.8rem;
    font-weight: 600;
    padding: 0.5rem 0.25rem;
}

.table tbody td {
    font-size: 0.8rem;
    padding: 0.4rem 0.25rem;
    vertical-align: middle;
}

/* ✅ Override table-striped saat anomaly filter aktif */
tbody.anomaly-filtered-view tr.table-danger {
    background-color: #f8d7da !important;
}

tbody.anomaly-filtered-view tr.table-warning {
    background-color: #fff3cd !important;
}

tbody.anomaly-filtered-view tr.table-danger:hover {
    background-color: #f1aeb5 !important;
}

tbody.anomaly-filtered-view tr.table-warning:hover {
    background-color: #ffe69c !important;
}

tbody.anomaly-filtered-view tr.table-danger td,
tbody.anomaly-filtered-view tr.table-warning td {
    background-color: transparent !important;
}
</style>

<?php
    $containerAnomalies = $containerAnomalies ?? session('container_anomalies', []);
?>

<script>
document.addEventListener('DOMContentLoaded', function () {
    // ✅ FIX 1: DECLARE SEMUA VARIABLE DI PALING ATAS
    let containers = <?php echo json_encode($containers ?? [], 15, 512) ?>;
    let containerAnomalies = <?php echo json_encode($containerAnomalies ?? [], 15, 512) ?>;
    let isAnomalyFilterActive = false;

    // ✅ CRITICAL: Declare state variables SEBELUM digunakan
    let anomalyMap = {}; // ← DECLARE DI SINI
    let filteredContainers = []; // ← DECLARE DI SINI (sebelum force reload handler)
    let rowsPerPage = 5;
    let currentPage = 1;

    // ✅ VALIDATE DATA
    console.log('=== ANOMALY DEBUG START ===');
    console.log('Total containers:', containers.length);
    console.log('Anomalies object:', containerAnomalies);
    console.log('Backend reported total anomalies:', containerAnomalies?.summary?.total_anomalies || 0);

    // Ensure containerAnomalies is valid object
    if (!containerAnomalies || typeof containerAnomalies !== 'object') {
        console.error('⚠️ CRITICAL: Invalid containerAnomalies data!');
        containerAnomalies = {
            summary: { total_anomalies: 0 },
            duplicate_positions: [],
            duplicate_container_ids: [],
            full_overload: [],
            empty_overweight: [],
            status_weight_mismatch: [],
            empty_underweight: [],
            unknown_status_heavy: [],
            missing_container_id: [],
            missing_position: [],
            invalid_position: []
        };
    }

    // Validate containers array
    if (!Array.isArray(containers) || containers.length === 0) {
        console.error('No containers data available');
        const tbody = document.getElementById('containerTableBody');
        if (tbody) {
            tbody.innerHTML = '<tr><td colspan="16" class="text-center text-muted">No containers data available.</td></tr>';
        }
        return;
    }

    console.log('✅ Data validation passed');

    // ===== UPDATE STATISTICS DISPLAY (REALTIME) =====
    function updateStatisticsDisplay() {
        // Calculate total containers
        const totalCount = containers.length;

        // Calculate total weight
        let totalWeightKg = 0;
        containers.forEach(container => {
            if (container.weight_kg && !isNaN(container.weight_kg)) {
                totalWeightKg += parseFloat(container.weight_kg);
            }
        });

        // Convert to tons
        const totalWeightTons = totalWeightKg / 1000;

        // Update DOM
        const totalContainersEl = document.getElementById('totalContainersDisplay');
        const totalWeightEl = document.getElementById('totalWeightDisplay');

        if (totalContainersEl) {
            totalContainersEl.textContent = totalCount;
        }

        if (totalWeightEl) {
            totalWeightEl.textContent = totalWeightTons > 0 ? totalWeightTons.toFixed(1) : '0.0';
        }

        console.log('📊 Statistics updated:', {
            containers: totalCount,
            weight_tons: totalWeightTons.toFixed(1)
        });
    }

    // ===== ANOMALY MAP BUILDER =====
    function rebuildAnomalyMap() {
        console.log('🔄 Rebuilding anomaly map...');

        anomalyMap = {};
        let totalAnomaliesBuilt = 0;

        const anomalyTypes = [
            'duplicate_positions',
            'duplicate_container_ids',
            'full_overload',
            'empty_overweight',
            'status_weight_mismatch',
            'empty_underweight',
            'unknown_status_heavy',
            'missing_container_id',
            'missing_position',
            'invalid_position',
            'missing_weight',
            'invalid_bay_parity'
        ];

        anomalyTypes.forEach(type => {
            const anomalyList = containerAnomalies[type];

            if (!Array.isArray(anomalyList) || anomalyList.length === 0) {
                return;
            }

            console.log(`  📋 Processing ${type}: ${anomalyList.length} items`);

            anomalyList.forEach((anomaly, idx) => {
                try {
                    let containerNo = '';

                    switch(type) {
                        case 'missing_container_id':
                            containerNo = anomaly.container_no || `MISSING_ID_${anomaly.index || idx}`;
                            break;
                        case 'duplicate_positions':
                            containerNo = anomaly.duplicate_container || anomaly.container_no || '';
                            break;
                        default:
                            containerNo = anomaly.container_no || '';
                    }

                    containerNo = String(containerNo).toUpperCase().trim();

                    const isInvalid =
                        !containerNo ||
                        containerNo === 'UNKNOWN' ||
                        containerNo === 'EMPTY' ||
                        (containerNo.length < 4 && !containerNo.startsWith('MISSING_ID'));

                    if (isInvalid) {
                        return;
                    }

                    if (!anomalyMap[containerNo]) {
                        anomalyMap[containerNo] = [];
                    }

                    anomalyMap[containerNo].push({
                        type: type,
                        severity: anomaly.severity || 'medium',
                        issue: anomaly.probable_issue || 'Anomaly detected',
                        details: anomaly,
                        position: anomaly.position || `${anomaly.bay || '?'}-${anomaly.row || '?'}-${anomaly.tier || '?'}`,
                        weight: anomaly.weight_kg || anomaly.weight_ton || null
                    });

                    totalAnomaliesBuilt++;

                } catch (error) {
                    console.error(`❌ Error processing ${type}[${idx}]:`, error);
                }
            });
        });

        console.log('✅ Anomaly map rebuilt:', {
            unique_containers: Object.keys(anomalyMap).length,
            total_anomalies: totalAnomaliesBuilt,
            expected: containerAnomalies?.summary?.total_anomalies || 0
        });

        return anomalyMap;
    }

    // ✅ Initial build saat page load
    rebuildAnomalyMap();

    // ✅ Initialize filteredContainers SETELAH rebuild
    filteredContainers = [...containers];

    // ✅ CHECK localStorage flag for forced rebuild
    const forceRebuildFlag = localStorage.getItem('force_anomaly_rebuild');
    if (forceRebuildFlag) {
        const flagTime = parseInt(forceRebuildFlag);
        const now = Date.now();

        if (now - flagTime < 5000) {
            console.log('🔄 Force rebuild from localStorage detected...');

            containers = <?php echo json_encode($containers ?? [], 15, 512) ?>;
            containerAnomalies = <?php echo json_encode($containerAnomalies ?? [], 15, 512) ?>;

            rebuildAnomalyMap();
            filteredContainers = [...containers];

            console.log('✅ Anomaly map force rebuilt:', {
                containers: containers.length,
                anomalies: containerAnomalies?.summary?.total_anomalies || 0,
                map_size: Object.keys(anomalyMap).length
            });
        }

        localStorage.removeItem('force_anomaly_rebuild');
    }

    // ✅ FORCE RELOAD HANDLER (SEKARANG AMAN karena filteredContainers sudah di-declare)
    <?php if(session('force_reload_anomalies')): ?>
        console.log('⚡ Force reload detected - refreshing anomaly data...');

        containers = <?php echo json_encode($containers ?? [], 15, 512) ?>;
        containerAnomalies = <?php echo json_encode($containerAnomalies ?? [], 15, 512) ?>;

        rebuildAnomalyMap();
        filteredContainers = [...containers];
        isAnomalyFilterActive = false;

        console.log('✅ Anomaly data refreshed:', {
            containers_count: containers.length,
            anomalies_count: containerAnomalies?.summary?.total_anomalies || 0,
            anomaly_map_size: Object.keys(anomalyMap).length
        });
    <?php endif; ?>

    // ===== GET DOM ELEMENTS =====
    const tbody = document.getElementById('containerTableBody');
    const prevBtn = document.getElementById('prevPage');
    const nextBtn = document.getElementById('nextPage');
    const pageInfo = document.getElementById('pageInfo');
    const searchInput = document.getElementById('searchInput');
    const searchField = document.getElementById('searchField');
    const searchBtn = document.getElementById('searchBtn');
    const clearSearch = document.getElementById('clearSearch');
    const rowsPerPageSelect = document.getElementById('rowsPerPageSelect');
    const activeFiltersSpan = document.getElementById('activeFilters');
    const btnFilterAnomaly = document.getElementById('btnFilterAnomaly');

    if (btnFilterAnomaly) {
        const totalAnomalies = containerAnomalies?.summary?.total_anomalies || 0;
        btnFilterAnomaly.innerHTML = `<i class="bi bi-exclamation-triangle-fill me-1"></i>Anomalies: ${totalAnomalies}`;
        btnFilterAnomaly.classList.remove('btn-warning', 'btn-secondary', 'btn-success');
        btnFilterAnomaly.classList.add(totalAnomalies > 0 ? 'btn-danger' : 'btn-success');
        console.log(`Initial anomaly button updated: ${totalAnomalies}`);
    }

    if (!tbody || !prevBtn || !nextBtn || !pageInfo || !searchInput) {
        console.error('⚠️ Required DOM elements not found');
        return;
    }

    // ===== HELPER FUNCTIONS =====
    function simplifySize(sizeRaw) {
        if (!sizeRaw) return 'N/A';
        const size = sizeRaw.toString().trim();
        if (size.includes('20')) return "20'";
        if (size.includes('40')) return "40'";
        if (size.includes('45')) return "45'";
        return size || 'N/A';
    }

    function mapJenis(jenisRaw) {
        if (!jenisRaw) return 'N/A';
        const jenis = jenisRaw.toString().toLowerCase().trim();
        const jenisMap = {
            'dry': 'Dry',
            'reefer': 'Reefer',
            'flat': 'Flat Rack',
            'tank': 'Tank',
            'open_top': 'Open Top',
            'empty': 'Empty',
            'unknown': 'Unknown'
        };
        return jenisMap[jenis] || (jenisRaw.charAt(0).toUpperCase() + jenisRaw.slice(1));
    }


function formatPosition(container) {
    //  Convert to string and trim
    const bay = String(container.bay || '').trim();
    const row = String(container.row || '').trim();
    const tier = String(container.tier || '').trim();

    // ONLY check if completely empty (missing data)
    if (!bay || !row || !tier) {
        return '<span class="badge bg-danger text-white" style="font-size: 0.6rem;" title="Missing position data">NO POS</span>';
    }

    //  Parse as integers for padding
    const bayNum = parseInt(bay) || 0;
    const rowNum = parseInt(row) || 0;
    const tierNum = parseInt(tier) || 0;


    return `<small class="text-dark">${String(bayNum).padStart(3, '0')}-${String(rowNum).padStart(2, '0')}-${String(tierNum).padStart(2, '0')}</small>`;
}

function mapStatus(container) {

    if (container.status_mapped && ['Full', 'Empty', 'Unknown'].includes(container.status_mapped)) {
        return container.status_mapped;
    }

    const statusCode = String(container.status_code || container.status || 'U').trim();


    if (statusCode === '5') return 'Full';
    if (statusCode === '4') return 'Empty';

    return 'Unknown';
}
function getStatusBadgeClass(status) {
    switch(status) {
        case 'Full': return 'bg-success';
        case 'Empty': return 'bg-warning text-dark';
        default: return 'bg-secondary';
    }
}

    function highlight(text, filter) {
        if (!filter || !text) return text || '';
        const regex = new RegExp(`(${filter})`, 'gi');
        return text.toString().replace(regex, `<mark>$1</mark>`);
    }

function createRowHtml(container, globalIndex, displayNo, filter = '', searchField = 'all') {
        const weight = (container.weight_kg && !isNaN(container.weight_kg)) ?
            Number(container.weight_kg).toLocaleString() : '-';

        const position = formatPosition(container);
        const containerNo = container.container_no || 'N/A';

        // ✅ CRITICAL: Use EXACT SAME normalization as anomaly map builder
        const normalizedContainerNo = String(containerNo).toUpperCase().trim();

        const isoType = container.iso_type || 'N/A';
        const operator = container.operator_code || 'N/A';
        const handling = container.handling_instruction || 'N/A';

        const pol = container.pol_locode ?
            `<span class="badge bg-info text-white" style="font-size: 0.65rem;">${container.pol_locode}</span>` :
            '<span class="text-muted small">-</span>';

        const pod = container.pod_locode ?
            `<span class="badge bg-info text-white" style="font-size: 0.65rem;">${container.pod_locode}</span>` :
            '<span class="text-muted small">-</span>';

        const delivery = container.delivery_locode ?
            `<span class="badge bg-info text-white" style="font-size: 0.65rem;">${container.delivery_locode}</span>` :
            '<span class="text-muted small">-</span>';

        //  FIX: Get status and badge class
        const status = mapStatus(container);
        const statusBadgeClass = getStatusBadgeClass(status);

        // Apply highlight
        let highlightedContainerNo = highlight(searchField === 'all' || searchField === 'container_no' ? containerNo : containerNo, filter);
        let highlightedIsoType = highlight(searchField === 'all' || searchField === 'iso_type' ? isoType : isoType, filter);
        let highlightedOperator = highlight(searchField === 'all' || searchField === 'operator_code' ? operator : operator, filter);
        let highlightedHandling = highlight(searchField === 'all' || searchField === 'handling_instruction' ? handling : handling, filter);
        const editUrlTemplate = `<?php echo e(route('containers.edit', ['container' => '__CONTAINER_ID__'])); ?>`;

// Kemudian di JavaScript, ganti placeholder tersebut dengan nilai globalIndex
        const editUrl = editUrlTemplate.replace('__CONTAINER_ID__', globalIndex);
        const rowId = `row-${globalIndex}`;

        const containerAnomalies = anomalyMap[normalizedContainerNo] || [];
        const hasAnomaly = containerAnomalies.length > 0;

        // Check for missing position
        const hasMissingPosition = position.includes('NO POS') || position.includes('000-00-00');

        // Check for missing ID
        const hasMissingId = !normalizedContainerNo ||
                            normalizedContainerNo === 'N/A' ||
                            normalizedContainerNo === 'UNKNOWN' ||
                            normalizedContainerNo.length < 4 ||
                            normalizedContainerNo.startsWith('MISSING_ID');

        // ✅ CRITICAL ANOMALY TYPES (Block Export - RED)
        const criticalAnomalyTypes = [
            'duplicate_positions',
            'duplicate_container_ids',
            'missing_container_id',
            'invalid_bay_parity'
        ];

        // ✅ WARNING ANOMALY TYPES (Allow Export - YELLOW)
        const warningAnomalyTypes = [
            'empty_overweight',
            'empty_underweight',
            'status_weight_mismatch',
            'unknown_status_heavy',
            'full_overload',
            'missing_position',
            'invalid_position',
            'missing_weight'
        ];

        // Classify anomalies
        const criticalAnomalies = containerAnomalies.filter(a =>
            criticalAnomalyTypes.includes(a.type)
        );
        const warningAnomalies = containerAnomalies.filter(a =>
            warningAnomalyTypes.includes(a.type)
        );

        const hasCriticalAnomaly = criticalAnomalies.length > 0 || hasMissingId;
        const hasWarningAnomaly = warningAnomalies.length > 0 || hasMissingPosition;

        /**
         * ✅ PRIORITY-BASED HIGHLIGHTING
         * Priority: Critical Anomaly (RED) > Warning Anomaly (YELLOW) > Normal
         */
        let trClass = '';
        let tooltipParts = [];
        let highlightReason = '';
        let badgeClass = '';
        let badgeText = '';

        // ✅ PRIORITY 1: CRITICAL Anomalies (RED - Block Export)
        if (hasCriticalAnomaly) {
            trClass = 'table-danger';
            highlightReason = 'critical_anomaly';
            badgeClass = 'bg-danger';

            if (hasMissingId) {
                badgeText = '🔴 NO ID';
                tooltipParts.push('⛔ CRITICAL: Missing container ID - Export BLOCKED');
            } else {
                const maxShow = 2;
                const issues = criticalAnomalies.slice(0, maxShow).map(a => a.issue);
                tooltipParts.push(...issues);

                if (criticalAnomalies.length > maxShow) {
                    tooltipParts.push(`... +${criticalAnomalies.length - maxShow} more critical issues`);
                }

                badgeText = `🔴 ${criticalAnomalies.length} CRITICAL`;
                tooltipParts.unshift('⛔ CRITICAL ISSUE - Export BLOCKED');
            }
        }
        // ✅ PRIORITY 2: WARNING Anomalies (YELLOW - Allow Export)
        else if (hasWarningAnomaly) {
            trClass = 'table-warning';
            highlightReason = 'warning_anomaly';
            badgeClass = 'bg-warning text-dark';

            const maxShow = 2;
            const issues = warningAnomalies.slice(0, maxShow).map(a => a.issue);
            tooltipParts.push(...issues);

            if (warningAnomalies.length > maxShow) {
                tooltipParts.push(`... +${warningAnomalies.length - maxShow} more warnings`);
            }

            badgeText = `⚠️ ${warningAnomalies.length} WARNING`;

            if (hasMissingPosition) {
                tooltipParts.unshift('⚠️ Missing position - Export allowed but needs attention');
            } else {
                tooltipParts.unshift('⚠️ WARNING - Export allowed but needs attention');
            }
        }

        // Build tooltip
        const tooltipText = tooltipParts.join(' | ');

        // Build anomaly badge
        let anomalyBadge = '';
        if (badgeText) {
            const allIssues = containerAnomalies.map(a => `[${a.type}] ${a.issue}`).join('; ');
            anomalyBadge = `<span class="badge ${badgeClass} ms-1" style="font-size: 0.55rem; font-weight: bold;" title="${allIssues || tooltipText}">${badgeText}</span>`;
        }

        // ✅ DEBUG: Log classification
        if ((hasCriticalAnomaly || hasWarningAnomaly) && globalIndex < 5) {
            console.log(`🎨 Row ${globalIndex} classified:`, {
                container: normalizedContainerNo,
                severity: hasCriticalAnomaly ? 'CRITICAL (RED)' : 'WARNING (YELLOW)',
                critical_count: criticalAnomalies.length,
                warning_count: warningAnomalies.length,
                badge: badgeText
            });
        }

    // ✅ DEBUG: Log only first 5 highlighted rows
    if ((hasAnomaly || hasMissingPosition || hasMissingId) && globalIndex < 5) {
        console.log(`🎨 Row ${globalIndex} highlighted:`, {
            container: normalizedContainerNo,
            reason: highlightReason,
            anomaly_count: containerAnomalies.length,
            badge: badgeText
        });
    }

        return `
            <tr id="${rowId}"
                class="${trClass}"
                data-container-no="${normalizedContainerNo}"
                data-has-anomaly="${hasAnomaly}"
                data-anomaly-count="${containerAnomalies.length}"
                data-missing-position="${hasMissingPosition}"
                data-missing-id="${hasMissingId}"
                data-highlight-reason="${highlightReason}"
                title="${tooltipText}">
                <td class="text-center">${displayNo}</td>
                <td>
                    <small>${highlightedContainerNo}</small>
                    ${anomalyBadge}
                </td>
                <td><small>${highlightedIsoType}</small></td>
                <td class="text-center"><small>${simplifySize(container.size || isoType)}</small></td>
                <td><small>${container.type_group || 'N/A'}</small></td>
                <td><small>${mapJenis(container.jenis)}</small></td>
                <td class="text-end"><small>${weight}</small></td>
                <td>${position}</td>
                <td class="text-center">${pol}</td>
                <td class="text-center">${pod}</td>
                <td class="text-center">${delivery}</td>
                <td><small>${highlightedOperator}</small></td>
                <td><small>${highlightedHandling}</small></td>
                <td class="text-center">
                    <span class="badge ${statusBadgeClass}" style="font-size: 0.65rem;">
                        ${status}
                    </span>
                </td>
                <td class="text-center">
                    ${container.is_reefer ?
                        `<span class="badge bg-info" style="font-size: 0.6rem;" title="Set Temperature">${container.set_temperature || 'N/A'}°${container.temperature_unit || 'C'}</span>` :
                        '<span class="text-muted small">-</span>'
                    }
                </td>
                <td class="text-center">
                    <div class="btn-group" role="group">
                        <a href="${editUrl}" class="btn btn-sm btn-outline-primary" style="font-size: 0.7rem;" title="Edit">
                            <i class="bi bi-pencil"></i>
                        </a>
                        <button type="button" class="btn btn-sm btn-outline-info btn-duplicate" style="font-size: 0.7rem;"
                                title="Duplicate" data-index="${globalIndex}">
                            <i class="bi bi-files"></i>
                        </button>
                        <button type="button" class="btn btn-sm btn-outline-danger btn-delete" style="font-size: 0.7rem;"
                                title="Delete" data-index="${globalIndex}">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `;
    }

function advancedSearch() {
    // ambil elemen di sini (hindari bergantung pada global variables yang mungkin undefined)
    const searchInputEl = document.getElementById('searchInput');
    const searchFieldEl = document.getElementById('searchField');
    const filterStatusEl = document.getElementById('filterStatus');
    const filterSizeEl = document.getElementById('filterSize');
    const filterJenisEl = document.getElementById('filterJenis');
    const filterWeightMinEl = document.getElementById('filterWeightMin');
    const filterWeightMaxEl = document.getElementById('filterWeightMax');
    const filterPositionEl = document.getElementById('filterPosition');
    const filterReeferEl = document.getElementById('filterReefer');

    // kalau elemen nggak ditemukan, log dan keluar
    if (!searchInputEl || !searchFieldEl) {
        console.error('Search input/field elements not found in DOM.');
        return;
    }

    const searchTerm = (searchInputEl.value || '').trim();
    const selectedField = (searchFieldEl.value || 'all');
    const filterStatus = (filterStatusEl?.value || '');
    const filterSize = (filterSizeEl?.value || '');
    const filterJenis = (filterJenisEl?.value || '').toLowerCase();
    const filterWeightMin = filterWeightMinEl?.value;
    const filterWeightMax = filterWeightMaxEl?.value;
    const filterPosition = (filterPositionEl?.value || '');
    const filterReefer = (filterReeferEl?.value || '');

    // Reset anomaly filter UI (jika ada)
    isAnomalyFilterActive = false;
    if (typeof btnFilterAnomaly !== 'undefined' && btnFilterAnomaly) {
        btnFilterAnomaly.classList.remove('btn-warning');
        btnFilterAnomaly.classList.add('btn-danger');
        btnFilterAnomaly.innerHTML = `<i class="bi bi-exclamation-triangle-fill me-1"></i>Anomalies: ${containerAnomalies?.summary?.total_anomalies || 0}`;
    }

    const searchTermUpper = searchTerm.toUpperCase();

    filteredContainers = (containers || []).filter(container => {
        // defensive: pastikan container ada
        if (!container) return false;

        const containerStatus = typeof mapStatus === 'function' ? mapStatus(container) : (container.status || '');
        const sizeVal = simplifySize ? simplifySize(container.size || container.iso_type) : (container.size || container.iso_type || '');
        const jenisVal = (container.jenis || '').toLowerCase();
        const weight = parseFloat(container.weight_kg || container.weight || 0);

        // TEXT SEARCH
        if (searchTerm) {
            let fieldMatch = false;

            switch (selectedField) {
                case 'all': {
                const positionStr = `${container.bay || ''}-${container.row || ''}-${container.tier || ''}`;
                const fieldsToSearch = [
                    container.container_no,
                    container.iso_type,
                    container.operator_code,
                    container.handling_instruction,
                    container.pol_locode,
                    container.pod_locode,
                    container.delivery_locode,
                    containerStatus,
                    sizeVal,
                    jenisVal,
                    container.description,
                    positionStr
                ];

                    const allFieldsStr = fieldsToSearch
                        .filter(f => f !== null && f !== undefined)
                        .map(f => String(f))
                        .join(' ')
                        .toUpperCase();
                    fieldMatch = allFieldsStr.includes(searchTermUpper);
                    break;
                }
                case 'container_no':
                    fieldMatch = (container.container_no || '').toUpperCase().includes(searchTermUpper);
                    break;
                case 'iso_type':
                    fieldMatch = (container.iso_type || '').toUpperCase().includes(searchTermUpper);
                    break;
                case 'operator_code':
                    fieldMatch = (String(container.operator_code || '')).toUpperCase().includes(searchTermUpper);
                    break;
                case 'status':
                    fieldMatch = (containerStatus || '').toUpperCase().includes(searchTermUpper);
                    break;
                case 'size':
                    fieldMatch = String(sizeVal || '').toUpperCase().includes(searchTermUpper);
                    break;
                case 'jenis':
                    fieldMatch = (jenisVal || '').toUpperCase().includes(searchTermUpper);
                    break;
                    case 'position': {
                    const pos = `${container.bay || ''}-${container.row || ''}-${container.tier || ''}`.toUpperCase();
                    fieldMatch = pos.includes(searchTermUpper);
                    break;
                }
                case 'pol_locode':
                    fieldMatch = (container.pol_locode || '').toUpperCase().includes(searchTermUpper);
                    break;
                case 'pod_locode':
                    fieldMatch = (container.pod_locode || '').toUpperCase().includes(searchTermUpper);
                    break;
                case 'delivery_locode':
                    fieldMatch = (container.delivery_locode || '').toUpperCase().includes(searchTermUpper);
                    break;
                case 'handling_instruction':
                    fieldMatch = (container.handling_instruction || '').toUpperCase().includes(searchTermUpper);
                    break;
                case 'operator_code':
                    fieldMatch = (String(container.operator_code || '')).toUpperCase().includes(searchTermUpper);
                    break;

                default:
                    fieldMatch = true;
            }

            if (!fieldMatch) return false;
        }

        // FILTERS
        if (filterStatus && String(containerStatus) !== String(filterStatus)) return false;
        if (filterSize && String(sizeVal) !== String(filterSize)) return false;
        if (filterJenis && jenisVal !== filterJenis) return false;

        if (filterWeightMin && !isNaN(parseFloat(filterWeightMin)) && weight < parseFloat(filterWeightMin)) return false;
        if (filterWeightMax && !isNaN(parseFloat(filterWeightMax)) && weight > parseFloat(filterWeightMax)) return false;

        if (filterPosition) {
            const hasPosition = !!(container.bay || container.row || container.tier);
            if (filterPosition === 'missing' && hasPosition) return false;
            if (filterPosition === 'assigned' && !hasPosition) return false;
        }

        if (filterReefer) {
            const isReefer = !!(container.is_reefer || (container.jenis || '').toLowerCase() === 'reefer' || (container.iso_type || '').toLowerCase().includes('reefer'));
            if (filterReefer === 'reefer' && !isReefer) return false;
            if (filterReefer === 'non-reefer' && isReefer) return false;
        }

        return true;
    });

    // Count active filters (lebih konsisten)
    let activeFiltersCount = 0;
    if (searchTerm) activeFiltersCount++;
    if (filterStatus) activeFiltersCount++;
    if (filterSize) activeFiltersCount++;
    if (filterJenis) activeFiltersCount++;
    if ((filterWeightMin && filterWeightMin !== '') || (filterWeightMax && filterWeightMax !== '')) activeFiltersCount++;
    if (filterPosition) activeFiltersCount++;
    if (filterReefer) activeFiltersCount++;

    if (activeFiltersCount > 0) {
        activeFiltersSpan.textContent = `${activeFiltersCount} filters active`;
        activeFiltersSpan.style.display = 'inline';
    } else {
        activeFiltersSpan.style.display = 'none';
    }

    currentPage = 1;
    renderTable(currentPage);

}


    function renderTable(page) {
        tbody.innerHTML = '';

        if (filteredContainers.length === 0) {
            tbody.innerHTML = '<tr><td colspan="16" class="text-center text-muted">No containers found.</td></tr>';
            pageInfo.textContent = 'No data';
            prevBtn.disabled = true;
            nextBtn.disabled = true;
            return;
        }

        const start = (page - 1) * rowsPerPage;
        const end = start + rowsPerPage;
        const pageData = filteredContainers.slice(start, end);
        const filter = searchInput.value;
        const selectedField = searchField.value;

        let highlightedCount = 0;

        pageData.forEach((container, indexInPage) => {
            const globalIndex = containers.findIndex(c =>
                c.container_no === container.container_no &&
                c.bay === container.bay &&
                c.row === container.row &&
                c.tier === container.tier
            );

            const displayNo = start + indexInPage + 1;
            const rowHtml = createRowHtml(container, globalIndex, displayNo, filter, selectedField);
            tbody.insertAdjacentHTML('beforeend', rowHtml);

            // Count highlighted rows
            const normalizedNo = String(container.container_no || '').toUpperCase().trim();
            if (anomalyMap[normalizedNo] && anomalyMap[normalizedNo].length > 0) {
                highlightedCount++;
            }
        });

        const totalPages = Math.ceil(filteredContainers.length / rowsPerPage);
        pageInfo.textContent = `Page ${page} of ${totalPages} (${filteredContainers.length} of ${containers.length} total)`;

        if (highlightedCount > 0) {
            pageInfo.textContent += ` - ${highlightedCount} with anomalies on this page`;
        }

        prevBtn.disabled = totalPages <= 1;
        nextBtn.disabled = totalPages <= 1;
    }

    // ===== EVENT LISTENERS =====
    searchBtn.addEventListener('click', advancedSearch);
    searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') advancedSearch();
    });

    clearSearch.addEventListener('click', function() {
        searchInput.value = '';
        searchField.value = 'all';
        document.getElementById('filterStatus').value = '';
        document.getElementById('filterSize').value = '';
        document.getElementById('filterJenis').value = '';
        document.getElementById('filterWeightMin').value = '';
        document.getElementById('filterWeightMax').value = '';
        document.getElementById('filterPosition').value = '';
        document.getElementById('filterReefer').value = '';
        filteredContainers = [...containers];
        activeFiltersSpan.style.display = 'none';
        isAnomalyFilterActive = false;
        if (btnFilterAnomaly) {
            btnFilterAnomaly.classList.remove('btn-warning');
            btnFilterAnomaly.classList.add('btn-danger');
            btnFilterAnomaly.innerHTML = `<i class="bi bi-exclamation-triangle-fill me-1"></i>Anomalies: ${containerAnomalies?.summary?.total_anomalies || 0}`;
        }
        currentPage = 1;
        renderTable(currentPage);
    });

    ['filterStatus', 'filterSize', 'filterJenis', 'filterWeightMin', 'filterWeightMax', 'filterPosition', 'filterReefer'].forEach(filterId => {
        const element = document.getElementById(filterId);
        if (element) {
            element.addEventListener('change', advancedSearch);
        }
    });

    // ✅ FIX 13: Enhanced Anomaly Filter Button
    if (btnFilterAnomaly) {
        btnFilterAnomaly.addEventListener('click', function() {
            if (isAnomalyFilterActive) {
                // Deactivate filter - show all
                filteredContainers = [...containers];
                isAnomalyFilterActive = false;
                tbody.classList.remove('anomaly-filtered-view');
                btnFilterAnomaly.classList.remove('btn-warning');
                btnFilterAnomaly.classList.add('btn-danger');
                btnFilterAnomaly.innerHTML = `<i class="bi bi-exclamation-triangle-fill me-1"></i>Anomalies: ${containerAnomalies?.summary?.total_anomalies || 0}`;
                activeFiltersSpan.style.display = 'none';

                console.log('🔄 Anomaly filter deactivated - showing all containers');
            } else {
                // Activate filter - show only containers with anomalies
                filteredContainers = containers.filter(container => {
                    const containerNo = String(container.container_no || '').toUpperCase().trim();
                    const hasAnomalyInMap = anomalyMap[containerNo] && anomalyMap[containerNo].length > 0;

                    // Also check for missing position/ID directly
                    const bay = String(container.bay || '').trim();
                    const row = String(container.row || '').trim();
                    const tier = String(container.tier || '').trim();

                    const hasMissingPosition = !bay || !row || !tier ||
                                              (bay === '0' && row === '0' && tier === '0');

                    const hasMissingId = !containerNo ||
                                        containerNo === 'N/A' ||
                                        containerNo === 'UNKNOWN' ||
                                        containerNo.length < 4;

                    return hasAnomalyInMap || hasMissingPosition || hasMissingId;
                });

                isAnomalyFilterActive = true;
                 tbody.classList.add('anomaly-filtered-view');
                btnFilterAnomaly.classList.remove('btn-danger');
                btnFilterAnomaly.classList.add('btn-warning');
                btnFilterAnomaly.innerHTML = '<i class="bi bi-arrow-clockwise me-1"></i>Show All';
                activeFiltersSpan.textContent = `1 filter active (${filteredContainers.length} containers with anomalies)`;
                activeFiltersSpan.style.display = 'inline';

                console.log('✅ Anomaly filter activated:', {
                    total_containers: containers.length,
                    filtered_count: filteredContainers.length,
                    anomaly_map_size: Object.keys(anomalyMap).length
                });
            }

            currentPage = 1;
            renderTable(currentPage);
        });
    }

    if (rowsPerPageSelect) {
        rowsPerPageSelect.addEventListener('change', function() {
            rowsPerPage = parseInt(this.value);
            currentPage = 1;
            renderTable(currentPage);
        });
    }

    prevBtn.addEventListener('click', () => {
        const totalPages = Math.ceil(filteredContainers.length / rowsPerPage);
        if (currentPage > 1) {
            currentPage--;
            renderTable(currentPage);
        } else if (totalPages > 1) {
            currentPage = totalPages;
            renderTable(currentPage);
        }
    });

    nextBtn.addEventListener('click', () => {
        const totalPages = Math.ceil(filteredContainers.length / rowsPerPage);
        if (currentPage < totalPages) {
            currentPage++;
            renderTable(currentPage);
        } else {
            currentPage = 1;
            renderTable(currentPage);
        }
    });

document.body.addEventListener('click', function(e) {
    // Handler untuk tombol Duplicate
    if (e.target.closest('.btn-duplicate')) {
        e.preventDefault();
        const button = e.target.closest('.btn-duplicate');
        const indexToDuplicate = button.getAttribute('data-index');

        console.log('🔄 Duplicating container at index:', indexToDuplicate);

        // Disable button dan show loading
        button.disabled = true;
        button.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';

        fetch('<?php echo e(route("baplie.containers.duplicate")); ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                'Accept': 'application/json'
            },
            body: JSON.stringify({ container_index: indexToDuplicate })
        })
        .then(response => {
            console.log('Duplicate response status:', response.status);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('Duplicate response data:', data);

            if (data.success) {
                // ✅ PERBAIKAN: Reload halaman untuk sinkronisasi penuh dengan session
                // Ini memastikan data yang ditampilkan sama persis dengan data di session
                alert(`Container duplicated successfully!\n\nOriginal: ${containers[indexToDuplicate].container_no}\nNew: ${data.new_container_no}\n\nPage will reload to show changes.`);

                // Reload dengan delay kecil agar alert terbaca
                setTimeout(() => {
                    window.location.reload();
                }, 500);
            } else {
                alert('Failed to duplicate: ' + (data.message || 'Server error'));
                button.disabled = false;
                button.innerHTML = '<i class="bi bi-files"></i>';
            }
        })
        .catch(error => {
            console.error('❌ Duplicate error:', error);
            alert('Network error occurred: ' + error.message);
            button.disabled = false;
            button.innerHTML = '<i class="bi bi-files"></i>';
        });
    }

    // ===== IMPROVED DELETE HANDLER =====
    if (e.target.closest('.btn-delete')) {
        e.preventDefault();
        const button = e.target.closest('.btn-delete');
        const indexToDelete = button.getAttribute('data-index');
        const row = button.closest('tr');
        const containerNo = row.querySelector('td:nth-child(2)').textContent.trim();

        console.log('🗑️ Delete request for:', containerNo, 'at index:', indexToDelete);

        // Konfirmasi sebelum delete
        if (!confirm(`⚠️ DELETE CONFIRMATION\n\nAre you sure you want to delete container:\n"${containerNo}"\n\nThis action cannot be undone.`)) {
            return;
        }

        // Disable button dan show loading
        button.disabled = true;
        button.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';

        const deleteUrl = '<?php echo e(url("/baplie/containers")); ?>/' + indexToDelete;

        console.log('Sending DELETE request to:', deleteUrl);

        // Send delete request
        fetch(deleteUrl, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                'Accept': 'application/json'
            }
        })
        .then(response => {
            console.log('Delete response status:', response.status);
            console.log('Delete response URL:', response.url);
            if (!response.ok) {
                // Tambahkan detail error untuk debugging
                return response.text().then(text => {
                    console.error('Error response:', text);
                    throw new Error(`HTTP error! status: ${response.status} - ${response.statusText}`);
                });
            }
            return response.json();
        })
        .then(data => {
            console.log('✅ Delete response data:', data);

            if (data.success) {
                // ✅ PERBAIKAN: Animate removal then reload
                row.style.transition = 'all 0.3s ease-out';
                row.style.backgroundColor = '#f8d7da';
                row.style.opacity = '0';
                row.style.transform = 'translateX(-20px)';

                setTimeout(() => {
                    alert(`✅ Container "${data.deleted_container_no || containerNo}" deleted successfully!\n\nRemaining containers: ${data.remaining_count}\n\nPage will reload to update statistics.`);

                    // Reload untuk sinkronisasi penuh
                    window.location.reload();
                }, 400);

            } else {
                alert('❌ Failed to delete: ' + (data.message || 'Server error'));
                button.disabled = false;
                button.innerHTML = '<i class="bi bi-trash"></i>';
            }
        })
        .catch(error => {
            console.error('❌ Delete error:', error);
            alert('❌ Network error occurred while deleting container:\n' + error.message);
            button.disabled = false;
            button.innerHTML = '<i class="bi bi-trash"></i>';
        });
    }

    });

    // ✅ FIX 15: Initial render with verification
    console.log('\n=== INITIAL RENDER START ===');
    console.log('Rendering page:', currentPage);
    console.log('Containers to render:', filteredContainers.length);
    console.log('Anomaly map ready:', Object.keys(anomalyMap).length, 'containers');

    renderTable(currentPage);

    // Post-render verification
    setTimeout(() => {
        const highlightedRows = document.querySelectorAll('tr.table-danger, tr.table-warning, tr.table-info');
        const rowsWithAnomalyBadge = document.querySelectorAll('td .badge.bg-danger, td .badge.bg-warning, td .badge.bg-info');

        console.log('=== POST-RENDER VERIFICATION ===');
        console.log('Total rows rendered:', document.querySelectorAll('tbody tr').length);
        console.log('Highlighted rows (colored):', highlightedRows.length);
        console.log('Rows with anomaly badges:', rowsWithAnomalyBadge.length);
        console.log('Expected anomalies:', containerAnomalies?.summary?.total_anomalies || 0);
        console.log('Anomaly map size:', Object.keys(anomalyMap).length);

        if (highlightedRows.length === 0 && Object.keys(anomalyMap).length > 0) {
            console.error('❌ WARNING: Anomalies exist but no rows are highlighted!');
            console.log('Debugging first 3 containers:');
            containers.slice(0, 3).forEach((c, i) => {
                const normalized = String(c.container_no || '').toUpperCase().trim();
                console.log(`Container ${i}:`, {
                    original: c.container_no,
                    normalized: normalized,
                    in_anomaly_map: !!anomalyMap[normalized],
                    anomaly_count: anomalyMap[normalized]?.length || 0
                });
            });
        } else {
            console.log('✅ Anomaly highlighting is working');
        }

        console.log('=== INITIAL RENDER COMPLETE ===\n');
    }, 100);

    // Show warning for containers without position
    const containersWithoutPosition = containers.filter(c => {
        const bay = String(c.bay || '').trim();
        const row = String(c.row || '').trim();
        const tier = String(c.tier || '').trim();
        return !bay || !row || !tier;
    }).length;

    if (containersWithoutPosition > 0) {
        console.warn(`⚠️ ${containersWithoutPosition} containers without position data`);
    }
});
</script>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp82\htdocs\baplie-viewer-and-editor\resources\views/baplie_management.blade.php ENDPATH**/ ?>