<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
    <title>QualityFlow - Endline Defect Selection</title>
    <link rel="icon" type="image/png" href="<?php echo e(asset('gplogofinal.png')); ?>">
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
    
    <!-- final_selectionstyles -->
    <style>
        body {
            font-family: 'Roboto', sans-serif;
            background-color: #f5f6f8; /* Light gray background */
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        /* Hide specific navbar elements for this view */
        #navScanNext {
            display: none !important;
        }

        /* Large selection cards container */
        .selection-cards-container {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 2rem;
            max-width: 1800px;
            flex-grow: 1;
            padding: 2rem 1rem 4rem 1rem;
            flex-wrap: wrap; 
        }

        /* Shared Card Styling */
        .final-card {
            flex: 1;
            min-width: 320px;
            max-width: 750px;
            height: 800px;
            border-radius: 28px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 3rem;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
            text-decoration: none;
            box-shadow: 0 4px 15px rgba(0,0,0,0.03);
        }

        .final-card:hover {
            transform: translateY(-8px);
        }
        
        /* Rework Card Specifics (Blue) */
        .card-rework {
            background-color: #f0f7ff; /* Brand light blue tint */
            border: 4px solid #bfdbfe;
        }

        .card-rework:hover {
            box-shadow: 0 20px 40px rgba(37, 99, 235, 0.12);
            border-color: #93c5fd;
        }

        .icon-rework-circle {
            background-color: #2563eb; /* Brand blue */
            width: 140px;
            height: 140px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 2.5rem;
            box-shadow: 0 10px 25px rgba(37, 99, 235, 0.3);
        }

        .title-rework {
            color: #1d4ed8;
            font-size: 3.2rem;
            font-weight: 900;
            margin: 0;
            text-align: center;
            line-height: 1.1;
        }

        .subtitle-rework {
            color: #3b82f6;
            font-size: 1rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 1.2px;
            margin-top: 1rem;
        }

        /* Confirmation Card Specifics (Red) */
        .card-confirm {
            background-color: #fff1f2; /* Brand light red tint */
            border: 4px solid #fecaca;
        }

        .card-confirm:hover {
            box-shadow: 0 20px 40px rgba(220, 38, 38, 0.12);
            border-color: #fca5a5;
        }

        .icon-confirm-circle {
            background-color: #dc2626; /* Brand red */
            width: 140px;
            height: 140px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 2.5rem;
            box-shadow: 0 10px 25px rgba(220, 38, 38, 0.3);
        }

        .title-confirm {
            color: #991b1b;
            font-size: 3.2rem;
            font-weight: 900;
            margin: 0;
            text-align: center;
            line-height: 1.1;
        }

        .subtitle-confirm {
            color: #ef4444;
            font-size: 1rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 1.2px;
            margin-top: 1rem;
        }

        /* Icons */
        .final-icon {
            color: white;
            font-size: 5rem;
        }

    </style>

    <style>
        body {
            font-family: 'Roboto', sans-serif;
            background-color: #f5f6f8; /* Light gray background */
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            overflow: hidden; /* Prevent full page scrolling to keep navbar fixed if needed, but we can just let it scroll normally. Let's make main container fill screen */
        }

        /* Hide specific navbar elements for this view */
        #navScanNext {
            display: none !important;
        }

        /* Main layout container */
        .main-container {
            display: flex;
            flex-direction: column;
            flex-grow: 1;
            padding: 1.5rem 1rem;
            max-width: 1400px;
            margin: 0 auto;
            width: 100%;
            height: calc(100vh - 60px); /* Adjust based on navbar height */
        }

        /* Container Card */
        .workspace-card {
            background-color: white;
            border-radius: 12px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.03);
            border: 1px solid rgba(0,0,0,0.05);
            display: flex;
            flex-direction: column;
            flex-grow: 1;
            padding: 1.5rem;
            overflow: hidden; /* Contains the internal scroll */
        }

        /* Top Action Bar */
        .top-action-bar {
            display: flex;
            gap: 1rem;
            margin-bottom: 1.5rem;
            flex-wrap: wrap;
        }

        .btn-reject {
            background-color: #ef4444; /* High contrast red */
            color: white;
            font-weight: 700;
            border: none;
            border-radius: 6px;
            padding: 0.8rem 2rem;
            letter-spacing: 1px;
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            transition: all 0.2s;
        }

        .btn-reject.inactive {
            background-color: #fca5a5; /* Pale red */
            pointer-events: none;
        }
        
        .btn-reject:not(.inactive):hover {
            background-color: #dc2626;
            color: white;
            box-shadow: 0 4px 8px rgba(220, 38, 38, 0.2);
        }

        .search-container {
            flex: 2;
            position: relative;
        }

        .search-container i {
            position: absolute;
            left: 1rem;
            top: 50%;
            transform: translateY(-50%);
            color: #8c98a4;
        }

        .defect-search-input {
            width: 100%;
            background-color: #f8f9fa;
            border: 1px solid #e1e4e8;
            border-radius: 6px;
            padding: 0.8rem 1rem 0.8rem 2.5rem;
            color: #495057;
            font-size: 0.9rem;
        }

        .defect-search-input:focus {
            outline: none;
            border-color: #2b4cc4;
            background-color: white;
        }

        .btn-review {
            background-color: white;
            color: #1a1e23;
            font-weight: 700;
            border: 1px solid #e1e4e8;
            border-radius: 6px;
            padding: 0.8rem 1.5rem;
            letter-spacing: 1px;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .btn-review:hover {
            background-color: #f8f9fa;
        }

        .btn-rework {
            background-color: #3b82f6; /* High contrast blue */
            color: white;
            font-weight: 700;
            border: none;
            border-radius: 6px;
            padding: 0.8rem 2rem;
            letter-spacing: 1px;
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            transition: all 0.2s;
        }

        .btn-rework.inactive {
            background-color: #93c5fd; /* Pale blue */
            pointer-events: none;
        }
        
        .btn-rework:not(.inactive):hover {
            background-color: #2563eb;
            color: white;
            box-shadow: 0 4px 8px rgba(37, 99, 235, 0.2);
        }

        /* Language Toggle Styling */
        .lang-switch-wrapper {
            display: flex;
            align-items: center;
            background-color: #f1f5f9;
            border: 1px solid #e2e8f0;
            border-radius: 50px;
            padding: 4px;
            height: 48px;
            width: 140px;
            position: relative;
            cursor: pointer;
            user-select: none;
            transition: all 0.3s ease;
        }

        .lang-option {
            flex: 1;
            text-align: center;
            font-size: 0.75rem;
            font-weight: 800;
            color: #64748b;
            z-index: 2;
            transition: color 0.3s ease;
            letter-spacing: 0.5px;
        }

        .lang-option.active {
            color: #1e293b;
        }

        .lang-slider {
            position: absolute;
            left: 4px;
            top: 4px;
            width: calc(50% - 4px);
            height: calc(100% - 8px);
            background-color: white;
            border-radius: 50px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.06);
            transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            z-index: 1;
        }

        .lang-switch-wrapper.local .lang-slider {
            transform: translateX(100%);
        }

        .lang-switch-wrapper.local .lang-option-eng { color: #64748b; }
        .lang-switch-wrapper.local .lang-option-local { color: #1e293b; }
        .lang-switch-wrapper:not(.local) .lang-option-eng { color: #1e293b; }
        .lang-switch-wrapper:not(.local) .lang-option-local { color: #64748b; }

        /* Defects Grid Area (Scrollable) */
        .defects-scroll-area {
            flex-grow: 1;
            overflow-y: auto;
            border: 1px solid #e1e4e8;
            border-radius: 8px;
            padding: 1.5rem;
            background-color: #ffffff;
            margin-bottom: 1.5rem;
            
            /* Custom Scrollbar */
            scrollbar-width: thin;
            scrollbar-color: #cbd5e1 transparent;
        }
        
        .defects-scroll-area::-webkit-scrollbar {
            width: 8px;
        }
        .defects-scroll-area::-webkit-scrollbar-track {
            background: transparent;
        }
        .defects-scroll-area::-webkit-scrollbar-thumb {
            background-color: #cbd5e1;
            border-radius: 10px;
        }

        .defects-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 1rem;
        }

        /* Defect Card Styling */
        .defect-card {
            background-color: #fcfcfd;
            border: 1px solid #e2e6f0;
            border-radius: 8px;
            padding: 1.5rem 1rem;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s;
            user-select: none;
        }

        .defect-card:hover {
            border-color: #cdd5df;
            background-color: #f8f9fa;
        }

        .defect-card.selected {
            border-color: #2b4cc4;
            background-color: #2b4cc4;
            box-shadow: 0 4px 10px rgba(43, 76, 196, 0.3);
            color: white;
        }

        .defect-number {
            font-size: 1.1rem;
            font-weight: 700;
            color: #8c98a4;
            margin-bottom: 0.3rem;
            transition: color 0.2s;
        }

        .defect-card.selected .defect-number {
            color: white;
        }

        .defect-name {
            font-size: 1rem;
            font-weight: 800;
            color: #1a1e23;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            transition: color 0.2s;
        }

        .defect-card.selected .defect-name {
            color: white;
        }

        /* Bottom Severity Buttons */
        .severity-bar {
            display: flex;
            gap: 1rem;
        }

        .btn-severity {
            flex: 1;
            background-color: #fcfcfd;
            border: 1px solid #e2e6f0;
            color: #8c98a4;
            font-weight: 700;
            border-radius: 8px;
            padding: 1rem;
            letter-spacing: 1px;
            text-transform: uppercase;
            transition: all 0.2s;
        }

        .btn-severity:hover {
            background-color: #f8f9fa;
            color: #495057;
        }

        /* Specific Button Colors (Only applied when active class is added) */
        .btn-minor.active {
            background-color: #eab308; /* Yellow/Gold */
            color: white;
            border-color: #eab308;
        }
        .btn-minor.active:hover { background-color: #ca8a04; }

        .btn-major.active {
            background-color: #f97316; /* Orange */
            color: white;
            border-color: #f97316;
        }
        .btn-major.active:hover { background-color: #ea580c; }

        .btn-critical.active {
            background-color: #dc2626; /* Red */
            color: white;
            border-color: #dc2626;
        }
        .btn-critical.active:hover { background-color: #b91c1c; }

        /* Media Queries for Responsiveness */
        @media (max-width: 992px) {
            .btn-reject, .btn-rework {
                flex: none;
                width: 100%;
            }
            .search-container {
                flex: none;
                width: 100%;
            }
            .btn-review {
                width: 100%;
                justify-content: center;
            }
        }
    </style>
</head>
<body>

    <?php
        $emp_checker = session('endline_checker');
        $emp_id_from_session = $emp_checker ? $emp_checker['employee_id'] : '';
    ?>

    <!-- Injecting the navigation bar blade components -->
    <?php echo $__env->make('Quality.Endline_nav', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

       <!-- Main Workspace Area -->
    <div class="main-container" id="defectSelectionContainer">
        <div class="workspace-card">
            
            <!-- Top Actions -->
            <div class="top-action-bar">
                <button id="rejectButton" type="button" class="btn btn-reject inactive text-white fs-5">
                    <i class="bi bi-x pb-1" style="font-size: 1.2rem;"></i> REJECT
                </button>
                
                <div class="search-container">
                    <i class="bi bi-search"></i>
                    <input type="text" id="defect-search-input" class="defect-search-input shadow-none" placeholder="Search defects or code...">
                </div>
                
                <button id="reviewButton" type="button" class="btn btn-review fs-6 position-relative" data-bs-toggle="offcanvas" data-bs-target="#reviewSidebar" aria-controls="reviewSidebar">
                    <i class="bi bi-filter-left fs-5"></i> REVIEW
                    <span id="reviewBadge" class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger" style="display: none; padding: 0.35em 0.6em; border: 2px solid #f5f6f8;">
                        0
                    </span>
                </button>
                
                <button id="reworkButton" type="button" class="btn btn-rework inactive text-white fs-5">
                    <i class="bi bi-arrow-return-left pb-1" style="font-size: 1.1rem;"></i> REWORK
                </button>

                <!-- Language Toggle -->
                <div id="languageToggle" class="lang-switch-wrapper" title="Switch Language">
                    <div class="lang-slider"></div>
                    <div id="english" class="lang-option lang-option-eng active">ENGLISH</div>
                    <div id="tamil" class="lang-option lang-option-local">TAMIL</div>
                </div>
            </div>

            <!-- Defects Grid container -->
            <div id="defects-scroll-area" class="defects-scroll-area">
                <div id="defects-grid" class="defects-grid">
                    <?php $__currentLoopData = $deflist; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $defect): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <?php
                            $rowId = is_array($defect) ? ($defect['Rowid'] ?? '') : ($defect->Rowid ?? '');
                            $rejType = is_array($defect) ? ($defect['Rej_Type'] ?? '') : ($defect->Rej_Type ?? '');
                        ?>
                        <div id="defectCard" class="defect-card" tabindex="0">
                            <span class="defect-number">#<?php echo e($rowId); ?></span>
                            <span class="defect-name"><?php echo e($rejType); ?></span>
                        </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </div>
            </div>

            <!-- Bottom Severity Buttons -->
            <div id="severity-bar" class="severity-bar d-none">
                <button id="minorButton" type="button" class="btn btn-severity btn-minor fs-6">MINOR</button>
                <button id="majorButton" type="button" class="btn btn-severity btn-major fs-6">MAJOR</button>
                <button id="criticalButton" type="button" class="btn btn-severity btn-critical fs-6">CRITICAL</button>
            </div>

        </div>
    </div>

    <!-- Review Sidebar (Offcanvas) -->
    <div class="offcanvas offcanvas-end" tabindex="-1" id="reviewSidebar" aria-labelledby="reviewSidebarLabel" style="width: 450px; border-left: none; box-shadow: -5px 0 25px rgba(0,0,0,0.08);">
        <div class="offcanvas-header pt-4 px-4 pb-0 align-items-center mt-2">
            <h5 class="offcanvas-title fw-bold m-0" id="reviewSidebarLabel" style="color: #1a1e23; font-size: 1.25rem; letter-spacing: 0.5px;">LOGGED DEFECTS</h5>
            <button type="button" class="btn rounded-circle d-flex align-items-center justify-content-center p-0 ms-auto" data-bs-dismiss="offcanvas" aria-label="Close" style="width: 42px; height: 42px; border: 2px solid #aebce1; color: #879bce; background-color: transparent;">
                <i class="bi bi-x fs-4"></i>
            </button>
        </div>
        <div class="offcanvas-body d-flex flex-column" style="background-color: #fafbfc;">
            <!-- Empty State -->
            <div id="emptyState" class="text-center d-flex flex-column align-items-center justify-content-center h-100" style="color: #cbd5e1;">
                <i class="bi bi-patch-exclamation" style="font-size: 6.5rem; line-height: 1;"></i>
                <p class="mt-4" style="font-size: 0.85rem; font-weight: 700; letter-spacing: 1.2px; text-transform: uppercase;">NO DEFECTS LOGGED</p>
            </div>
            
            <!-- Logged Items Container -->
            <div id="loggedDefectsContainer" style="display: none; gap: 0.75rem; flex-direction: column;">
                <!-- Items will be injected here via JS -->
            </div>
        </div>
    </div>


        <!-- final_Selection Cards -->
    <div class="selection-cards-container mx-auto d-none" id="finalSelectionCards">
        
        <!-- Change to Rework Card -->
        <a id="reworkActionCard" class="final-card card-rework">
            <div class="icon-rework-circle">
                <i class="bi bi-arrow-90deg-left final-icon"></i>
            </div>
            <h1 class="title-rework">CHANGE TO REWORK</h1>
            <span class="subtitle-rework">SEND FOR REPAIR INSTEAD</span>
        </a>

        <!-- Confirm Rejection Card -->
        <a id="confirmRejectCard" class="final-card card-confirm">
            <div class="icon-confirm-circle">
                <i class="bi bi-check-circle final-icon"></i>
            </div>
            <h1 class="title-confirm">CONFIRM REJECTION</h1>
            <span class="subtitle-confirm">PROCEED TO NEXT ITEM</span>
        </a>

    </div>

    <!-- External Script Dependencies (jQuery & Bootstrap) -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
    
       <script>
        $(document).ready(function() {
            console.log("Defect Selection page initialized.");
            $('#garmentIdDiv').addClass('d-none');
            $('#homebtn').removeClass('d-none');

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

            console.log('deflist',deflist);

            let loggedDefectsCount = 0;

            let currentLanguage = 'ENGLISH';

            let englishDefects = {};
            let tamilDefects = {};

            if (deflist && deflist.length) {
                deflist.forEach(function(item) {
                    let rowId = item.Rowid;
                    let rejType = item.Rej_Type;
                    let tamName = item.defect_tam || item.Defect_Tam || " ";
                    englishDefects[rowId] = rejType;
                    tamilDefects[rowId] = tamName; 
                });
            }

            const translations = {
                'ENGLISH': {
                    'reject': 'REJECT',
                    'review': 'REVIEW',
                    'rework': 'REWORK',
                    'minor': 'MINOR',
                    'major': 'MAJOR',
                    'critical': 'CRITICAL',
                    'logged_defects': 'LOGGED DEFECTS',
                    'no_defects': 'NO DEFECTS LOGGED',
                    'search_placeholder': 'Search defects or code...',
                    'defects': englishDefects
                },
                'TAMIL': {
                    'reject': 'REJECT',
                    'review': 'REVIEW',
                    'rework': 'REWORK',
                    'minor': 'MINOR',
                    'major': 'MAJOR',
                    'critical': 'CRITICAL',
                    'logged_defects': 'LOGGED DEFECTS',
                    'no_defects': 'NO DEFECTS LOGGED',
                    'search_placeholder': 'Search defects or code...',
                    'defects': tamilDefects
                }
            };

            function applyLanguage(lang) {
                currentLanguage = lang;
                const t = translations[lang];

                // Update Defect Cards
                $('.defect-card').each(function() {
                    const code = $(this).find('.defect-number').text().replace('#', '');
                    $(this).find('.defect-name').text(t.defects[code]);
                });

                // Update Top Buttons
                $('#rejectButton').html(`<i class="bi bi-x pb-1" style="font-size: 1.2rem;"></i> ${t.reject}`);
                $('#reviewButton').html(`<i class="bi bi-filter-left fs-5"></i> ${t.review} <span id="reviewBadge" class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger" style="${loggedDefectsCount > 0 ? '' : 'display: none;'} padding: 0.35em 0.6em; border: 2px solid #f5f6f8;">${loggedDefectsCount}</span>`);
                $('#reworkButton').html(`<i class="bi bi-arrow-return-left pb-1" style="font-size: 1.1rem;"></i> ${t.rework}`);

                // Update Search Placeholder
                $('#defect-search-input').attr('placeholder', t.search_placeholder);
                

                // Update Severity Buttons
                $('#minorButton').text(t.minor);
                $('#majorButton').text(t.major);
                $('#criticalButton').text(t.critical);

                // Update Sidebar
                $('#reviewSidebarLabel').text(t.logged_defects);
                $('#emptyState p').text(t.no_defects);
            }

            // Selection toggle for defect cards (Single Selection turned to Multi Toggle)
            $('.defect-card').on('click', function() {
                const $this = $(this);
                const isAlreadySelected = $this.hasClass('selected');
                
                if (isAlreadySelected) {
                    // Deselect the clicked card
                    $this.removeClass('selected');
                    // Find the corresponding log item and trigger its remove button
                    const defectId = $this.find('.defect-number').text().replace('#', '').trim();
                    $('.defect-log-item[data-log-id="' + defectId + '"] .remove-defect-btn').trigger('click');
                } else {
                    // Select the clicked card
                    $('.defect-card').removeClass('recently-clicked');
                    $this.addClass('selected recently-clicked');
                    // Add active colors to severity buttons
                    $('#minorButton, #majorButton, #criticalButton').addClass('active');
                    $('#majorButton').trigger('click');
                }
            });

            // Handle Severity Button Click
            $('.btn-severity').on('click', function() {
                // Ensure a defect card is actually selected before proceeding
                const $selectedCard = $('.defect-card.recently-clicked');
                if ($selectedCard.length === 0) {
                    return; // Do nothing if no defect is selected
                }

                // Get defect details
                const defectId = $selectedCard.find('.defect-number').text().replace('#', '').trim();
                const defectName = $selectedCard.find('.defect-name').text();
                const severity = $(this).text().trim();
                
                // Determine pill color based on severity
                let badgeBgColor = '';
                
                // Use original English severity for logic check if needed, but here we just use label mapping
                const t = translations[currentLanguage];
                let severityLabel = severity;

                if (severity === t.minor) {
                    badgeBgColor = '#eab308'; // Yellow/Gold
                } else if (severity === t.major) {
                    badgeBgColor = '#f97316'; // Orange
                } else if (severity === t.critical) {
                    badgeBgColor = '#dc2626'; // Red
                }

                // Create the logged item HTML mimicking the design
                const loggedItemId = defectId; // Unique ID for finding in array later
                const loggedItemHtml = `
                    <div class="card border-1 rounded-3 shadow-sm mb-2 defect-log-item" style="border-color: #e2e6f0;" data-log-id="${loggedItemId}">
                        <div class="card-body p-3 d-flex justify-content-between align-items-center bg-white rounded-3">
                            <div>
                                <h6 class="mb-2 fw-bold" style="color: #1a1e23; font-size: 0.85rem;">${defectName}</h6>
                                <span class="badge rounded-pill text-white" style="background-color: ${badgeBgColor}; letter-spacing: 0.5px; font-size: 0.65rem;">${severityLabel}</span>
                            </div>
                            <button type="button" class="btn btn-link text-danger p-0 border-0 text-decoration-none remove-defect-btn">
                                <i class="bi bi-trash fs-5"></i>
                            </button>
                        </div>
                    </div>
                `;

                // Add to array
                loggedDefectsList.push({
                    id: loggedItemId,
                    name: defectName,
                    severity: severityLabel // Depending on language this could be different, usually backend expects English or specific ID
                });

                // Add to container
                $('#loggedDefectsContainer').append(loggedItemHtml);

                // Update UI state
                loggedDefectsCount++;
                updateReviewBadge();
                
                // Manage visual state
                $('#emptyState').hide();
                $('#loggedDefectsContainer').css('display', 'flex');

                // Reset selection cycle
                $('.defect-card').removeClass('recently-clicked');
                $('#minorButton, #majorButton, #criticalButton').removeClass('active');
            });

            // Prevent scroll jumping when pressing space or enter on focused card
            $('.defect-card').on('keydown', function(e) {
                if (e.key === "Enter" || e.key === " ") {
                    e.preventDefault();
                    $(this).click();
                }
            });

            // Basic search functionality
            $('#defect-search-input').on('keyup', function() {
                var value = $(this).val().toLowerCase();
                $('.defect-card').filter(function() {
                    $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
                });
            });

            // Helper to update the red badge on REVIEW button and action buttons state
            function updateReviewBadge() {
                const $badge = $('#reviewBadge');
                if (loggedDefectsCount > 0) {
                    $badge.text(loggedDefectsCount).show();
                    $('#rejectButton, #reworkButton').removeClass('inactive');
                } else {
                    $badge.hide();
                    $('#rejectButton, #reworkButton').addClass('inactive');
                }
            }

            let loggedDefectsList = []; // Array to store {defectName, severity}
            
            // Helper to determine URL parameters
            const urlParams = new URLSearchParams(window.location.search);
            const cc = urlParams.get('cc');
            const color = urlParams.get('color');
            const model = urlParams.get('model');
            const size = urlParams.get('size');
            const garmentId = urlParams.get('garmentId');
            const ean_no = urlParams.get('ean_no');

            // Helper to send data via AJAX
            function saveDefects(type) {
                var lineNo = sessionStorage.getItem('endline_outline');
                var unitNo = sessionStorage.getItem('endline_unit');
                var empNo = sessionStorage.getItem('emp_id');

                $.ajax({
                    url: '/rfid-save',
                    type: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    data: {
                        line: lineNo,
                        unit: unitNo,
                        empno: empNo,
                        garmentId: garmentId,
                        ccno: cc,
                        color: color,
                        model: model,
                        size: size,
                        ean_no: ean_no,
                        type: type, // 2 for Rework, 3 for Reject
                        defects: loggedDefectsList // selected defects
                    },
                    success: function(response) {
                        console.log("Defect data saved successfully");
                       // window.location.href = redirectUrl;
                       window.location.href = "<?php echo e(route('endline.selection')); ?>";
                       toastr.success(response.message);
                    },
                    error: function(xhr) {
                        console.error("Error saving defect data");
                        //alert("Failed to save defect record. Please try again.");
                        toastr.error(response.message);
                        window.location.href = "<?php echo e(route('endline.selection')); ?>";
                    }
                });
            }

            $('#rejectButton').on('click', function() {
                if ($(this).hasClass('inactive')) return;
                $('#defectSelectionContainer').addClass('d-none');
                $('#finalSelectionCards').removeClass('d-none');
            });

           

            $('#reworkButton').on('click', function() {
                if ($(this).hasClass('inactive')) return;
                saveDefects(2);              
            });

            $('#reworkActionCard').on('click', function() {
               saveDefects(2);
            });

            $('#confirmRejectCard').on('click', function() {
               saveDefects(3);
            });

            // Optional: Handle removing defects from the sidebar
            $(document).on('click', '.remove-defect-btn', function() {
                const $card = $(this).closest('.defect-log-item');
                const logId = $card.data('log-id');
                
                // Remove from array
                loggedDefectsList = loggedDefectsList.filter(d => d.id != logId);

                // Deselect in the main grid
                $('.defect-card').each(function() {
                    const defectNumber = $(this).find('.defect-number').text().replace('#', '').trim();
                    if (defectNumber == logId) {
                        $(this).removeClass('selected recently-clicked');
                    }
                });

                $card.remove();
                loggedDefectsCount--;
                updateReviewBadge();

                if (loggedDefectsCount === 0) {
                    $('#loggedDefectsContainer').hide();
                    $('#emptyState').css('display', 'flex'); // flex needed for centering centering
                }
            });

            // Language Toggle Switch Handler
            $('#languageToggle').on('click', function() {
                $(this).toggleClass('local');
                const isLocal = $(this).hasClass('local');
                
                if (isLocal) {
                    applyLanguage('TAMIL');
                    console.log("Language switched to TAMIL");
                } else {
                    applyLanguage('ENGLISH');
                    console.log("Language switched to ENGLISH");
                }
            });
        });
        
    </script>
</body>
</html>
<?php /**PATH C:\Apache24\htdocs\Quality_Endline\Endline\resources\views/Quality/Endline_defectselection.blade.php ENDPATH**/ ?>