<?php $__env->startSection('title', __('app.front.title')); ?>

<?php $__env->startSection('content'); ?>
    <div class="row g-4 align-items-stretch">
        <div class="col-lg-8">
            <section class="masbana-card h-100 p-4">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <div>
                        <h2 class="fw-bold display-6 mb-0"><?php echo e(__('app.front.intro')); ?></h2>
                    </div>
                    <span class="badge rounded-pill bg-info-subtle text-info">
                        <i class="bi bi-cloud-lightning me-1"></i> <?php echo e(__('app.front.badge')); ?>

                    </span>
                </div>

                <div class="mb-4">
                    <div class="filters-row d-flex flex-wrap align-items-end gap-3">
                        <div class="flex-grow-1">
                            <p class="heading-label mb-2"><?php echo e(__('app.front.gender_label')); ?></p>
                            <div class="d-flex gap-3 flex-wrap">
                                <button type="button" class="btn btn-primary text-white btn-rounded gender-btn" data-gender="male">
                                    <i class="bi bi-person-standing me-2"></i> <?php echo e(__('app.front.male')); ?>

                                </button>
                                <button type="button" class="btn btn-outline-primary btn-rounded gender-btn" data-gender="female">
                                    <i class="bi bi-person-standing-dress me-2"></i> <?php echo e(__('app.front.female')); ?>

                                </button>
                            </div>
                        </div>
                        <div class="flex-grow-1">
                            <p class="heading-label mb-2"><?php echo e(__('app.front.service_label')); ?></p>
                            <div class="d-flex gap-3 flex-wrap">
                                <button type="button" class="btn btn-primary text-white btn-rounded service-type-btn" data-service-type="ironing">
                                    <i class="bi bi-lightning-charge me-2"></i> <?php echo e(__('app.front.ironing')); ?>

                                </button>
                                <button type="button" class="btn btn-outline-primary btn-rounded service-type-btn" data-service-type="washing">
                                    <i class="bi bi-droplet-half me-2"></i> <?php echo e(__('app.front.washing')); ?>

                                </button>
                            </div>
                        </div>
                        <div class="search-column" style="min-width: 220px;">
                            <p class="heading-label mb-2"><?php echo e(__('app.front.search_items')); ?></p>
                            <div class="input-group search-input-group rounded-pill">
                                <span class="input-group-text">
                                    <i class="bi bi-search"></i>
                                </span>
                                <input type="text" class="form-control" id="itemSearchInput" placeholder="<?php echo e(__('app.front.search_items')); ?>" autocomplete="off">
                                <button type="button" class="btn btn-outline-secondary search-clear-btn" id="clearSearchBtn" disabled>
                                    <i class="bi bi-x-lg"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <div>
                    <p class="heading-label mb-3"><?php echo e(__('app.front.items_label')); ?></p>
                    <div class="items-grid-wrapper">
                        <div class="row g-3" id="itemsGrid">
                        <?php $__currentLoopData = $items; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <div class="col-12 col-sm-6 col-xl-4">
                                <div class="item-card rounded-4 p-3 h-100 d-flex flex-column" data-item-id="<?php echo e($item->id); ?>"
                                     data-name="<?php echo e($item->name); ?>"
                                     data-wash="<?php echo e($item->default_wash_price); ?>"
                                     data-iron="<?php echo e($item->default_iron_price); ?>">
                                    <div class="position-relative text-center mb-3">
                                        <img src="<?php echo e($item->image_url); ?>" alt="<?php echo e($item->name); ?>"
                                             class="rounded-4 img-fluid shadow-sm object-fit-cover" style="height:220px;width:100%;object-fit:cover;">
                                        <div class="price-badge position-absolute top-0 end-0 mt-2 me-2">
                                            <span class="price-currency"><?php echo e($settings['currency']); ?></span>
                                            <span class="price-amount"><?php echo e(number_format($item->default_iron_price, 2)); ?></span>
                                        </div>
                                    </div>
                                    <h5 class="fw-semibold mb-1"><?php echo e($item->name); ?></h5>
                                    <div class="mb-2">
                                        <label class="form-label small mb-1"><?php echo e(__('app.front.color_label')); ?></label>
                                        <div class="color-picker-wrapper">
                                            <button type="button" class="btn btn-outline-secondary btn-sm w-100 color-picker-btn rounded-3 d-flex align-items-center justify-content-between" data-bs-toggle="dropdown" aria-expanded="false">
                                                <span class="d-flex align-items-center gap-2">
                                                    <span class="color-preview" style="width: 18px; height: 18px; border-radius: 50%; border: 1px solid #ddd; background: transparent; display: inline-block;"></span>
                                                    <span class="color-picker-text"><?php echo e(__('app.front.color_placeholder')); ?></span>
                                                </span>
                                                <i class="bi bi-chevron-down"></i>
                                            </button>
                                            <ul class="dropdown-menu color-picker-dropdown p-3">
                                                <div class="color-grid">
                                                    <button type="button" class="color-option" data-color="white" data-value="white" style="background: #ffffff; border: 1px solid #ddd;" title="<?php echo e(__('app.front.colors.white')); ?>">
                                                        <span class="color-name"><?php echo e(__('app.front.colors.white')); ?></span>
                                                    </button>
                                                    <button type="button" class="color-option" data-color="black" data-value="black" style="background: #000000;" title="<?php echo e(__('app.front.colors.black')); ?>">
                                                        <span class="color-name"><?php echo e(__('app.front.colors.black')); ?></span>
                                                    </button>
                                                    <button type="button" class="color-option" data-color="red" data-value="red" style="background: #dc3545;" title="<?php echo e(__('app.front.colors.red')); ?>">
                                                        <span class="color-name"><?php echo e(__('app.front.colors.red')); ?></span>
                                                    </button>
                                                    <button type="button" class="color-option" data-color="blue" data-value="blue" style="background: #0d6efd;" title="<?php echo e(__('app.front.colors.blue')); ?>">
                                                        <span class="color-name"><?php echo e(__('app.front.colors.blue')); ?></span>
                                                    </button>
                                                    <button type="button" class="color-option" data-color="green" data-value="green" style="background: #198754;" title="<?php echo e(__('app.front.colors.green')); ?>">
                                                        <span class="color-name"><?php echo e(__('app.front.colors.green')); ?></span>
                                                    </button>
                                                    <button type="button" class="color-option" data-color="yellow" data-value="yellow" style="background: #ffc107;" title="<?php echo e(__('app.front.colors.yellow')); ?>">
                                                        <span class="color-name"><?php echo e(__('app.front.colors.yellow')); ?></span>
                                                    </button>
                                                    <button type="button" class="color-option" data-color="orange" data-value="orange" style="background: #fd7e14;" title="<?php echo e(__('app.front.colors.orange')); ?>">
                                                        <span class="color-name"><?php echo e(__('app.front.colors.orange')); ?></span>
                                                    </button>
                                                    <button type="button" class="color-option" data-color="purple" data-value="purple" style="background: #6f42c1;" title="<?php echo e(__('app.front.colors.purple')); ?>">
                                                        <span class="color-name"><?php echo e(__('app.front.colors.purple')); ?></span>
                                                    </button>
                                                    <button type="button" class="color-option" data-color="pink" data-value="pink" style="background: #e91e63;" title="<?php echo e(__('app.front.colors.pink')); ?>">
                                                        <span class="color-name"><?php echo e(__('app.front.colors.pink')); ?></span>
                                                    </button>
                                                    <button type="button" class="color-option" data-color="brown" data-value="brown" style="background: #8b4513;" title="<?php echo e(__('app.front.colors.brown')); ?>">
                                                        <span class="color-name"><?php echo e(__('app.front.colors.brown')); ?></span>
                                                    </button>
                                                    <button type="button" class="color-option" data-color="gray" data-value="gray" style="background: #6c757d;" title="<?php echo e(__('app.front.colors.gray')); ?>">
                                                        <span class="color-name"><?php echo e(__('app.front.colors.gray')); ?></span>
                                                    </button>
                                                    <button type="button" class="color-option" data-color="beige" data-value="beige" style="background: #f5f5dc; border: 1px solid #ddd;" title="<?php echo e(__('app.front.colors.beige')); ?>">
                                                        <span class="color-name"><?php echo e(__('app.front.colors.beige')); ?></span>
                                                    </button>
                                                    <button type="button" class="color-option" data-color="navy" data-value="navy" style="background: #001f3f;" title="<?php echo e(__('app.front.colors.navy')); ?>">
                                                        <span class="color-name"><?php echo e(__('app.front.colors.navy')); ?></span>
                                                    </button>
                                                    <button type="button" class="color-option" data-color="other" data-value="other" style="background: #cccccc;" title="<?php echo e(__('app.front.colors.other')); ?>">
                                                        <span class="color-name"><?php echo e(__('app.front.colors.other')); ?></span>
                                                    </button>
                                                </div>
                                            </ul>
                                            <input type="hidden" class="color-input" value="">
                                        </div>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label small mb-2"><?php echo e(__('app.front.quantity')); ?></label>
                                        <div class="d-flex align-items-center gap-2">
                                            <div class="btn-group" role="group">
                                                <button type="button" class="btn btn-light btn-sm qty-btn" data-action="dec">
                                                    <i class="bi bi-dash-lg"></i>
                                                </button>
                                                <input type="text" class="form-control form-control-sm text-center qty-input" value="1" readonly style="width:60px;">
                                                <button type="button" class="btn btn-light btn-sm qty-btn" data-action="inc">
                                                    <i class="bi bi-plus-lg"></i>
                                                </button>
                                            </div>
                                            <button type="button" class="btn btn-primary btn-sm flex-grow-1 add-to-cart-btn rounded-3">
                                                <i class="bi bi-cart-plus me-1"></i><?php echo e(__('app.front.add_to_cart')); ?>

                                            </button>
                                        </div>
                                    </div>
                                    <div class="d-flex justify-content-center">
                                        <span class="badge bg-primary-subtle text-primary fw-semibold px-3 py-2">
                                            <span class="line-total">0</span>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </div>
                    </div>
                </div>
            </section>
        </div>

        <div class="col-lg-4">
            <section class="masbana-card h-100 p-4 position-relative">
                <p class="heading-label mb-2"><?php echo e(__('app.front.summary')); ?></p>
                <div class="mb-3">
                    <label class="form-label fw-semibold"><?php echo e(__('app.front.customer')); ?></label>
                    <input type="text" class="form-control form-control-lg rounded-4" id="customerName" placeholder="<?php echo e(__('app.front.customer')); ?>">
                </div>

                <div class="summary-list mb-3">
                    <table class="table table-borderless align-middle m-0" id="summaryTable">
                        <thead class="table-light">
                            <tr>
                                <th class="small"><?php echo e(__('app.front.receipt.item')); ?></th>
                                <th class="small text-center"><?php echo e(__('app.front.color_label')); ?></th>
                                <th class="small text-center"><?php echo e(__('app.front.receipt.service')); ?></th>
                                <th class="small text-center"><?php echo e(__('app.front.receipt.qty')); ?></th>
                                <th class="small text-end"><?php echo e(__('app.front.receipt.total')); ?></th>
                                <th class="small text-end" style="width: 50px;"></th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>

                <div class="mb-3">
                    <label class="form-label fw-semibold"><?php echo e(__('app.front.discount')); ?></label>
                    <div class="input-group">
                        <span class="input-group-text"><?php echo e($settings['currency']); ?></span>
                        <input type="number" min="0" step="0.5" class="form-control" id="discountInput" value="0">
                    </div>
                </div>

                <div class="d-flex justify-content-between mb-2">
                    <span class="text-muted"><?php echo e(__('app.front.subtotal')); ?></span>
                    <span id="subtotalDisplay"><?php echo e($settings['currency']); ?> 0.00</span>
                </div>

                <div class="d-flex justify-content-between mb-2">
                    <span class="text-muted"><?php echo e(__('app.front.discount')); ?></span>
                    <span id="discountDisplay">- <?php echo e($settings['currency']); ?> 0.00</span>
                </div>

                <div class="d-flex justify-content-between mb-4">
                    <span class="fw-semibold"><?php echo e(__('app.front.total')); ?></span>
                    <span class="fw-bold fs-4 text-primary" id="totalDisplay"><?php echo e($settings['currency']); ?> 0.00</span>
                </div>

                <div class="form-check form-switch mb-4">
                    <input class="form-check-input" type="checkbox" role="switch" id="markPaidSwitch">
                    <label class="form-check-label fw-semibold" for="markPaidSwitch"><?php echo e(__('app.front.mark_paid')); ?></label>
                </div>

                <div class="d-grid gap-2">
                    <button class="btn btn-primary btn-rounded" id="saveOrderBtn">
                        <span class="spinner-border spinner-border-sm me-2 d-none" id="saveSpinner"></span>
                        <?php echo e(__('app.front.save')); ?>

                    </button>
                    <button class="btn btn-outline-primary btn-rounded" id="savePrintBtn">
                        <i class="bi bi-printer me-2"></i> <?php echo e(__('app.front.save_print')); ?>

                    </button>
                </div>

                <div class="d-grid mt-3">
                    <button class="btn btn-outline-danger btn-rounded" id="clearOrderBtn">
                        <i class="bi bi-trash me-2"></i> <?php echo e(__('app.front.clear_order')); ?>

                    </button>
                </div>

                <div class="alert alert-info rounded-4 mt-4 mb-0">
                    <div class="fw-semibold"><?php echo e(__('app.front.receipt_copies')); ?>: <?php echo e($settings['receipt_copies']); ?></div>
                    <small><?php echo e(__('app.front.receipt_hint')); ?></small>
                </div>
            </section>
        </div>
    </div>

    <div class="toast-container position-fixed bottom-0 end-0 p-4"></div>
<?php $__env->stopSection(); ?>

<?php
    $colorTranslations = [
        'white' => __('app.front.colors.white'),
        'black' => __('app.front.colors.black'),
        'red' => __('app.front.colors.red'),
        'blue' => __('app.front.colors.blue'),
        'green' => __('app.front.colors.green'),
        'yellow' => __('app.front.colors.yellow'),
        'orange' => __('app.front.colors.orange'),
        'purple' => __('app.front.colors.purple'),
        'pink' => __('app.front.colors.pink'),
        'brown' => __('app.front.colors.brown'),
        'gray' => __('app.front.colors.gray'),
        'beige' => __('app.front.colors.beige'),
        'navy' => __('app.front.colors.navy'),
        'other' => __('app.front.colors.other'),
    ];
?>

<?php $__env->startPush('styles'); ?>
    <style>
        .price-badge {
            background: linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(255, 255, 255, 0.9) 100%);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            border-radius: 12px;
            padding: 8px 12px;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15), 0 2px 8px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.8);
            display: inline-flex;
            align-items: center;
            gap: 4px;
            z-index: 10;
            transition: all 0.3s ease;
        }
        
        .price-badge:hover {
            transform: translateY(-2px) scale(1.05);
            box-shadow: 0 6px 20px rgba(92, 185, 255, 0.3), 0 4px 12px rgba(0, 0, 0, 0.15);
        }
        
        .price-currency {
            font-size: 0.75rem;
            font-weight: 600;
            color: var(--masbana-sky-dark);
            opacity: 0.9;
            letter-spacing: 0.5px;
        }
        
        .price-amount {
            font-size: 1.1rem;
            font-weight: 700;
            color: var(--masbana-text);
            line-height: 1;
            letter-spacing: -0.5px;
        }
        
        .item-card:hover .price-badge {
            background: linear-gradient(135deg, rgba(92, 185, 255, 0.15) 0%, rgba(92, 185, 255, 0.1) 100%);
            border-color: rgba(92, 185, 255, 0.3);
        }
        
        .item-card:hover .price-currency {
            color: var(--masbana-sky);
        }
        
        .item-card {
            border: 1px solid rgba(92, 185, 255, 0.25) !important;
            transition: border-color 0.2s ease;
        }
        
        .item-card:hover {
            border-color: rgba(92, 185, 255, 0.4) !important;
        }
        
        .color-picker-wrapper {
            position: relative;
        }
        
        .color-picker-btn {
            transition: all 0.2s ease;
        }
        
        .color-picker-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        
        .color-preview {
            transition: all 0.2s ease;
        }
        
        .color-picker-dropdown {
            min-width: 280px;
            border-radius: 12px;
            box-shadow: 0 8px 24px rgba(0,0,0,0.15);
            border: none;
            margin-top: 8px !important;
        }
        
        .color-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 10px;
        }
        
        .color-option {
            position: relative;
            width: 100%;
            aspect-ratio: 1;
            border-radius: 10px;
            border: 1px solid rgba(0,0,0,0.1);
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            padding: 0;
        }
        
        .color-option:hover {
            transform: scale(1.1);
            box-shadow: 0 4px 12px rgba(0,0,0,0.2);
            z-index: 1;
        }
        
        .color-option.active {
            border-color: var(--masbana-sky);
            box-shadow: 0 0 0 3px rgba(92, 185, 255, 0.3);
        }
        
        .color-name {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(0,0,0,0.7);
            color: white;
            font-size: 0.7rem;
            padding: 4px;
            text-align: center;
            opacity: 0;
            transition: opacity 0.2s ease;
            font-weight: 600;
        }
        
        .color-option:hover .color-name {
            opacity: 1;
        }
        
        .color-option[data-color="white"] .color-name,
        .color-option[data-color="beige"] .color-name,
        .color-option[data-color="yellow"] .color-name {
            background: rgba(0,0,0,0.8);
        }
        
        @media (max-width: 576px) {
            .color-grid {
                grid-template-columns: repeat(3, 1fr);
            }
        }
        
        .remove-item-btn {
            transition: all 0.2s ease;
        }
        
        .remove-item-btn:hover {
            transform: scale(1.1);
            box-shadow: 0 2px 8px rgba(220, 53, 69, 0.3);
        }
        
        .remove-item-btn:active {
            transform: scale(0.95);
        }
        
        #summaryTable {
            font-size: 0.875rem;
        }
        
        #summaryTable thead th {
            padding: 0.5rem 0.25rem;
            font-size: 0.75rem;
            font-weight: 600;
            white-space: nowrap;
        }
        
        #summaryTable tbody td {
            padding: 0.5rem 0.25rem;
            font-size: 0.8rem;
            vertical-align: middle;
        }
        
        #summaryTable tbody tr {
            transition: background-color 0.2s ease;
        }
        
        #summaryTable tbody tr:hover {
            background-color: rgba(92, 185, 255, 0.05);
        }
        
        #summaryTable .badge {
            font-size: 0.7rem;
            padding: 0.25rem 0.5rem;
        }
        
        #summaryTable .remove-item-btn {
            width: 28px !important;
            height: 28px !important;
            padding: 0 !important;
        }
        
        #summaryTable .remove-item-btn i {
            font-size: 0.75rem;
        }

        .filters-row .search-column {
            flex: 0 0 240px;
        }

        @media (max-width: 992px) {
            .filters-row .search-column {
                flex: 1 1 100%;
            }
        }

        .search-input-group {
            border: 1px solid #ced4da;
            border-radius: 999px;
            overflow: hidden;
            background-color: #fff;
        }

        .search-input-group .input-group-text,
        .search-input-group .form-control,
        .search-input-group .btn {
            border: none;
            background-color: transparent;
            box-shadow: none;
        }

        .search-input-group .form-control:focus,
        .search-input-group .btn:focus {
            box-shadow: none;
        }

        .search-input-group .btn {
            border-left: 1px solid #dee2e6;
        }

        .search-input-group .search-clear-btn:disabled {
            opacity: 0.4;
            cursor: not-allowed;
        }

        .items-grid-wrapper {
            max-height: 860px;
            overflow-y: auto;
            overflow-x: hidden;
            padding-right: 0.5rem;
            /* Firefox scrollbar styling */
            scrollbar-width: thin;
            scrollbar-color: rgba(92, 185, 255, 0.5) rgba(92, 185, 255, 0.1);
        }

        /* Custom scrollbar for WebKit browsers (Chrome, Safari, Edge) */
        .items-grid-wrapper::-webkit-scrollbar {
            width: 10px;
        }

        .items-grid-wrapper::-webkit-scrollbar-track {
            background: linear-gradient(180deg, 
                rgba(92, 185, 255, 0.05) 0%, 
                rgba(92, 185, 255, 0.02) 100%);
            border-radius: 10px;
            border: 1px solid rgba(92, 185, 255, 0.1);
            margin: 8px 0;
        }

        .items-grid-wrapper::-webkit-scrollbar-thumb {
            background: linear-gradient(180deg, 
                rgba(92, 185, 255, 0.8) 0%, 
                rgba(92, 185, 255, 0.6) 50%,
                rgba(92, 185, 255, 0.7) 100%);
            border-radius: 10px;
            border: 2px solid transparent;
            background-clip: padding-box;
            box-shadow: 
                0 2px 4px rgba(92, 185, 255, 0.2),
                inset 0 1px 0 rgba(255, 255, 255, 0.3);
            transition: all 0.3s ease;
        }

        .items-grid-wrapper::-webkit-scrollbar-thumb:hover {
            background: linear-gradient(180deg, 
                rgba(92, 185, 255, 1) 0%, 
                rgba(92, 185, 255, 0.8) 50%,
                rgba(92, 185, 255, 0.9) 100%);
            box-shadow: 
                0 4px 8px rgba(92, 185, 255, 0.4),
                inset 0 1px 0 rgba(255, 255, 255, 0.4);
            transform: scaleX(1.1);
        }

        .items-grid-wrapper::-webkit-scrollbar-thumb:active {
            background: linear-gradient(180deg, 
                rgba(62, 141, 211, 1) 0%, 
                rgba(62, 141, 211, 0.9) 50%,
                rgba(62, 141, 211, 0.95) 100%);
            box-shadow: 
                0 2px 4px rgba(62, 141, 211, 0.5),
                inset 0 1px 0 rgba(255, 255, 255, 0.2);
        }

        /* Smooth scrolling */
        .items-grid-wrapper {
            scroll-behavior: smooth;
        }
        
    </style>
<?php $__env->stopPush(); ?>

<?php $__env->startPush('scripts'); ?>
    <script src="https://cdn.jsdelivr.net/npm/axios@1.6.7/dist/axios.min.js"></script>
    <script>
        const currency = <?php echo json_encode($settings['currency'], 15, 512) ?>;
        const receiptCopies = Number(<?php echo json_encode($settings['receipt_copies'], 15, 512) ?>);
        const colorTranslations = <?php echo json_encode($colorTranslations, 15, 512) ?>;
        const addedText = <?php echo json_encode(__('app.front.added'), 15, 512) ?>;
        const removeItemText = <?php echo json_encode(__('app.front.remove_item'), 15, 512) ?>;
        const serviceTypeTranslations = {
            'washing': <?php echo json_encode(__('app.front.washing'), 15, 512) ?>,
            'ironing': <?php echo json_encode(__('app.front.ironing'), 15, 512) ?>
        };

        const state = {
            gender: 'male',
            serviceType: 'ironing',
            items: {},
            customerName: '',
            discount: 0,
            markPaid: false,
        };

        const toastContainer = document.querySelector('.toast-container');
        const successMessage = <?php echo json_encode(__('app.front.toast_success'), 15, 512) ?>;
        const errorMessage = <?php echo json_encode(__('app.front.toast_error'), 15, 512) ?>;
        const clearOrderText = <?php echo json_encode(__('app.front.clear_order'), 15, 512) ?>;
        const clearOrderConfirmText = <?php echo json_encode(__('app.front.clear_order_confirm'), 15, 512) ?>;
        const orderClearedText = <?php echo json_encode(__('app.front.order_cleared'), 15, 512) ?>;

        // LocalStorage functions
        const STORAGE_KEY = 'service_order_state';

        function saveStateToLocalStorage() {
            try {
                localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
            } catch (e) {
                console.error('Error saving to localStorage:', e);
            }
        }

        function loadStateFromLocalStorage() {
            try {
                const saved = localStorage.getItem(STORAGE_KEY);
                if (saved) {
                    const parsed = JSON.parse(saved);
                    if (parsed.items) state.items = parsed.items;
                    if (parsed.gender) state.gender = parsed.gender;
                    if (parsed.serviceType) state.serviceType = parsed.serviceType;
                    if (parsed.customerName !== undefined) state.customerName = parsed.customerName;
                    if (parsed.discount !== undefined) state.discount = parsed.discount;
                    if (parsed.markPaid !== undefined) state.markPaid = parsed.markPaid;
                }
            } catch (e) {
                console.error('Error loading from localStorage:', e);
            }
        }

        function clearStateFromLocalStorage() {
            try {
                localStorage.removeItem(STORAGE_KEY);
            } catch (e) {
                console.error('Error clearing localStorage:', e);
            }
        }

        function showToast(message, type = 'primary') {
            const toastId = `toast-${Date.now()}`;
            const toastElement = document.createElement('div');
            toastElement.className = `toast align-items-center text-bg-${type} border-0`;
            toastElement.id = toastId;
            toastElement.role = 'alert';
            toastElement.innerHTML = `
                <div class="d-flex">
                    <div class="toast-body">${message}</div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                </div>`;
            toastContainer.appendChild(toastElement);
            const toast = new bootstrap.Toast(toastElement);
            toast.show();
            toastElement.addEventListener('hidden.bs.toast', () => toastElement.remove());
        }

        function formatCurrency(value) {
            return `${currency} ${Number(value).toFixed(2)}`;
        }

        const colorMap = {
            'white': '#ffffff',
            'black': '#000000',
            'red': '#dc3545',
            'blue': '#0d6efd',
            'green': '#198754',
            'yellow': '#ffc107',
            'orange': '#fd7e14',
            'purple': '#6f42c1',
            'pink': '#e91e63',
            'brown': '#8b4513',
            'gray': '#6c757d',
            'beige': '#f5f5dc',
            'navy': '#001f3f',
            'other': '#cccccc'
        };

        // Helper function to determine text color based on background color
        function getContrastColor(hexColor) {
            // Remove # if present
            hexColor = hexColor.replace('#', '');
            
            // Convert to RGB
            const r = parseInt(hexColor.substr(0, 2), 16);
            const g = parseInt(hexColor.substr(2, 2), 16);
            const b = parseInt(hexColor.substr(4, 2), 16);
            
            // Calculate luminance
            const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
            
            // Return black for light colors, white for dark colors
            return luminance > 0.5 ? '#000000' : '#ffffff';
        }

        // Helper function to create color badge
        function createColorBadge(colorValue, colorName) {
            if (!colorValue || !colorMap[colorValue]) return '';
            
            const hexColor = colorMap[colorValue];
            const textColor = getContrastColor(hexColor);
            
            return `<span class="badge ms-2" style="background-color: ${hexColor}; color: ${textColor}; border: 1px solid ${hexColor === '#ffffff' || hexColor === '#f5f5dc' ? '#ddd' : 'rgba(0,0,0,0.1)'};">${colorName}</span>`;
        }

        // Helper function to generate item key (itemId + color)
        function getItemKey(itemId, color) {
            return `${itemId}-${color || 'no-color'}`;
        }

        // Helper function to find items by itemId (regardless of color)
        function findItemsByItemId(itemId) {
            return Object.entries(state.items).filter(([key, item]) => item.id === itemId);
        }

        function refreshSummary() {
            const tbody = document.querySelector('#summaryTable tbody');
            tbody.innerHTML = '';

            let subtotal = 0;

            Object.entries(state.items).forEach(([key, item]) => {
                const line = item.price * item.quantity;
                subtotal += line;
                const colorBadge = item.color && colorTranslations[item.color] 
                    ? createColorBadge(item.color, colorTranslations[item.color])
                    : '<span class="text-muted small">-</span>';
                const serviceTypeText = item.serviceType && serviceTypeTranslations[item.serviceType] 
                    ? `<span class="badge bg-primary-subtle text-primary">${serviceTypeTranslations[item.serviceType]}</span>`
                    : '<span class="text-muted small">-</span>';
                const row = document.createElement('tr');
                row.setAttribute('data-item-key', key);
                row.innerHTML = `
                    <td class="small fw-semibold">${item.name}</td>
                    <td class="text-center">${colorBadge}</td>
                    <td class="text-center">${serviceTypeText}</td>
                    <td class="text-muted small text-center">x${item.quantity}</td>
                    <td class="text-end small">${formatCurrency(line)}</td>
                    <td class="text-end" style="width: 50px;">
                        <button type="button" class="btn btn-sm btn-outline-danger remove-item-btn rounded-circle" data-item-key="${key}" title="${removeItemText}" style="width: 32px; height: 32px; padding: 0; display: flex; align-items: center; justify-content: center;">
                            <i class="bi bi-trash"></i>
                        </button>
                    </td>
                `;
                tbody.appendChild(row);
            });

            const discount = Math.min(subtotal, Number($('#discountInput').val()) || 0);
            const total = Math.max(subtotal - discount, 0);

            $('#subtotalDisplay').text(formatCurrency(subtotal));
            $('#discountDisplay').text(`- ${formatCurrency(discount)}`);
            $('#totalDisplay').text(formatCurrency(total));

            // Save state to localStorage
            saveStateToLocalStorage();

            return { subtotal, discount, total };
        }

        function updateItemCard(card) {
            const itemId = card.data('item-id');
            const quantity = Number(card.find('.qty-input').val());
            const color = card.find('.color-input').val() || null;
            const itemKey = getItemKey(itemId, color);
            
            // If item already exists in state with same color, preserve its serviceType
            const existingItem = state.items[itemKey];
            const serviceType = existingItem ? existingItem.serviceType : state.serviceType;
            const price = serviceType === 'washing' ? Number(card.data('wash')) : Number(card.data('iron'));

            // Calculate line total for current color only
            const lineTotalElement = card.find('.line-total');
            lineTotalElement.text(formatCurrency(price * quantity));

            if (quantity > 0) {
                state.items[itemKey] = {
                    id: itemId,
                    name: card.data('name'),
                    quantity,
                    color,
                    price,
                    serviceType: serviceType,
                };
            } else {
                delete state.items[itemKey];
            }

            refreshSummary();
            saveStateToLocalStorage();
        }

        function updatePriceBadges() {
            $('#itemsGrid .item-card').each(function () {
                const card = $(this);
                const itemId = card.data('item-id');
                const allItemsForThisId = findItemsByItemId(itemId);
                
                // Use existing serviceType if item is already in cart, otherwise use current state.serviceType
                const serviceType = allItemsForThisId.length > 0 ? allItemsForThisId[0][1].serviceType : state.serviceType;
                const price = serviceType === 'washing' ? card.data('wash') : card.data('iron');
                
                card.find('.price-currency').text(currency);
                card.find('.price-amount').text(Number(price).toFixed(2));
                
                if (allItemsForThisId.length > 0) {
                    // Update price for each item
                    allItemsForThisId.forEach(([key, item]) => {
                        item.price = Number(price);
                    });
                    
                    // Update line total for current color only
                    const currentColor = card.find('.color-input').val() || null;
                    const currentItemKey = getItemKey(itemId, currentColor);
                    const currentItem = state.items[currentItemKey];
                    if (currentItem) {
                        const lineTotal = Number(price) * currentItem.quantity;
                        card.find('.line-total').text(formatCurrency(lineTotal));
                    } else {
                        card.find('.line-total').text(formatCurrency(0));
                    }
                } else {
                    card.find('.line-total').text(formatCurrency(0));
                }
            });

            refreshSummary();
        }

        $('.gender-btn').on('click', function () {
            $('.gender-btn').removeClass('btn-primary text-white').addClass('btn-outline-primary');
            $(this).removeClass('btn-outline-primary').addClass('btn-primary text-white');
            state.gender = $(this).data('gender');
            saveStateToLocalStorage();
        });

        $('.service-type-btn').on('click', function () {
            $('.service-type-btn').removeClass('btn-primary text-white').addClass('btn-outline-primary');
            $(this).removeClass('btn-outline-primary').addClass('btn-primary text-white');
            state.serviceType = $(this).data('service-type');
            updatePriceBadges();
            saveStateToLocalStorage();
            // Don't call updateItemCard here - it will preserve existing serviceType for items already in cart
        });

        $('#itemsGrid').on('click', '.qty-btn', function () {
            const card = $(this).closest('.item-card');
            const input = card.find('.qty-input');
            let value = Number(input.val());
            if ($(this).data('action') === 'inc') {
                value += 1;
            } else if (value > 0) {
                value -= 1;
            }
            input.val(value);
            
            // Update line total display only (don't add to cart)
            const itemId = card.data('item-id');
            const color = card.find('.color-input').val() || null;
            const itemKey = getItemKey(itemId, color);
            const existingItem = state.items[itemKey];
            const serviceType = existingItem ? existingItem.serviceType : state.serviceType;
            const price = serviceType === 'washing' ? Number(card.data('wash')) : Number(card.data('iron'));
            const lineTotalElement = card.find('.line-total');
            lineTotalElement.text(formatCurrency(price * value));
        });
        
        // Handle add to cart button
        $('#itemsGrid').on('click', '.add-to-cart-btn', function () {
            const card = $(this).closest('.item-card');
            const input = card.find('.qty-input');
            let quantity = Number(input.val());
            
            if (quantity <= 0) {
                // If quantity is 0, set it to 1 and add
                quantity = 1;
                input.val(quantity);
            }
            
            updateItemCard(card);
            
            // Reset color to default state
            const wrapper = card.find('.color-picker-wrapper');
            updateColorPicker(wrapper.find('.color-picker-btn'), null, null);
            
            // Visual feedback
            const btn = $(this);
            const originalText = btn.html();
            btn.html(`<i class="bi bi-check-lg me-1"></i>${addedText}`).addClass('btn-success').removeClass('btn-primary');
            
            setTimeout(() => {
                btn.html(originalText).removeClass('btn-success').addClass('btn-primary');
            }, 1500);
        });
        
        function updateColorPicker(button, colorValue, colorName) {
            const wrapper = $(button).closest('.color-picker-wrapper');
            const preview = wrapper.find('.color-preview');
            const text = wrapper.find('.color-picker-text');
            const input = wrapper.find('.color-input');
            const dropdown = wrapper.find('.color-picker-dropdown');
            
            if (colorValue && colorMap[colorValue]) {
                const hexColor = colorMap[colorValue];
                preview.css({
                    'background-color': hexColor,
                    'border': (colorValue === 'white' || colorValue === 'beige') ? '1px solid #ddd' : '1px solid rgba(0,0,0,0.1)'
                });
                text.text(colorName || colorTranslations[colorValue] || colorValue);
                input.val(colorValue);
                
                // Update active state
                dropdown.find('.color-option').removeClass('active');
                dropdown.find(`.color-option[data-value="${colorValue}"]`).addClass('active');
            } else {
                preview.css({
                    'background-color': 'transparent',
                    'border': '1px solid #ddd'
                });
                text.text('<?php echo e(__('app.front.color_placeholder')); ?>');
                input.val('');
                dropdown.find('.color-option').removeClass('active');
            }
        }
        
        // Handle color selection
        $('#itemsGrid').on('click', '.color-option', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            const card = $(this).closest('.item-card');
            const itemId = card.data('item-id');
            const colorValue = $(this).data('value');
            const colorName = colorTranslations[colorValue] || colorValue;
            const wrapper = $(this).closest('.color-picker-wrapper');
            const dropdown = new bootstrap.Dropdown(wrapper.find('.color-picker-btn')[0]);
            
            updateColorPicker(wrapper.find('.color-picker-btn'), colorValue, colorName);
            dropdown.hide();
            
            // Don't add to cart automatically - only when "Add to cart" button is clicked
        });
        
        // Close dropdown when clicking outside
        $(document).on('click', function(e) {
            if (!$(e.target).closest('.color-picker-wrapper').length) {
                $('.color-picker-dropdown').each(function() {
                    const btn = $(this).siblings('.color-picker-btn');
                    if (btn.length) {
                        const dropdown = bootstrap.Dropdown.getInstance(btn[0]);
                        if (dropdown) dropdown.hide();
                    }
                });
            }
        });

        $('#discountInput').on('input', refreshSummary);

        // Handle remove item from summary
        $(document).on('click', '.remove-item-btn', function() {
            const itemKey = $(this).data('item-key');
            const item = state.items[itemKey];
            if (!item) return;
            
            const itemName = item.name || '';
            const itemColor = item.color;
            const itemId = item.id;
            const colorText = itemColor && colorTranslations[itemColor] 
                ? ` ${createColorBadge(itemColor, colorTranslations[itemColor])}` 
                : '';
            
            // Create and show Bootstrap modal
            const modalId = 'removeItemModal';
            let modal = document.getElementById(modalId);
            
            if (!modal) {
                modal = document.createElement('div');
                modal.className = 'modal fade';
                modal.id = modalId;
                modal.setAttribute('tabindex', '-1');
                modal.innerHTML = `
                    <div class="modal-dialog modal-dialog-centered">
                        <div class="modal-content">
                            <div class="modal-header border-0 pb-0">
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body text-center px-4 pb-4">
                                <div class="mb-3">
                                    <div class="bg-danger-subtle rounded-circle d-inline-flex align-items-center justify-content-center" style="width: 64px; height: 64px;">
                                        <i class="bi bi-trash-fill text-danger fs-2"></i>
                                    </div>
                                </div>
                                <h5 class="modal-title fw-bold mb-2">${removeItemText}</h5>
                                <p class="text-muted mb-0" id="removeItemName"></p>
                            </div>
                            <div class="modal-footer border-0 justify-content-center gap-2 pb-4">
                                <button type="button" class="btn btn-outline-secondary btn-rounded" data-bs-dismiss="modal">
                                    <?php echo e(__('app.items.form.cancel')); ?>

                                </button>
                                <button type="button" class="btn btn-danger btn-rounded" id="confirmRemoveBtn">
                                    <i class="bi bi-trash me-2"></i>${removeItemText}
                                </button>
                            </div>
                        </div>
                    </div>
                `;
                document.body.appendChild(modal);
            }
            
            // Update modal content
            document.getElementById('removeItemName').innerHTML = `<strong>${itemName}</strong>${colorText}`;
            
            // Store itemKey in the button's data attribute for reliable access
            $('#confirmRemoveBtn').data('item-key', itemKey).data('item-id', itemId).data('item-color', itemColor);
            
            // Get or create modal instance
            let bsModal = bootstrap.Modal.getInstance(modal);
            if (!bsModal) {
                bsModal = new bootstrap.Modal(modal);
            }
            
            // Remove all existing event handlers and add new one
            $('#confirmRemoveBtn').off('click.removeItem').on('click.removeItem', function() {
                // Get itemKey from button's data attribute
                const currentItemKey = $(this).data('item-key');
                const currentItemId = $(this).data('item-id');
                const currentItemColor = $(this).data('item-color');
                
                if (!currentItemKey || !state.items[currentItemKey]) {
                    bsModal.hide();
                    return;
                }
                
                const currentItem = state.items[currentItemKey];
                const itemNameForToast = currentItem.name;
                const colorTextForToast = currentItemColor && colorTranslations[currentItemColor] 
                    ? ` ${createColorBadge(currentItemColor, colorTranslations[currentItemColor])}` 
                    : '';
                
                // Remove from state FIRST
                delete state.items[currentItemKey];
                
                // Refresh summary immediately to remove the row
                refreshSummary();
                
                // Update the item card - check if there are any remaining items with same itemId
                const card = $(`#itemsGrid .item-card[data-item-id="${currentItemId}"]`);
                if (card.length) {
                    // Find all remaining items with same itemId
                    const remainingItems = Object.entries(state.items).filter(([key, item]) => item.id === currentItemId);
                    
                    if (remainingItems.length === 0) {
                        // No more items with this itemId, reset the card completely
                        card.find('.qty-input').val(0);
                        card.find('.color-input').val('');
                        card.find('.line-total').text(formatCurrency(0));
                        
                        // Reset color picker
                        const wrapper = card.find('.color-picker-wrapper');
                        wrapper.find('.color-preview').css({
                            'background-color': 'transparent',
                            'border': '1px solid #ddd'
                        });
                        wrapper.find('.color-picker-text').text('<?php echo e(__('app.front.color_placeholder')); ?>');
                        wrapper.find('.color-option').removeClass('active');
                    } else {
                        // There are still items with this itemId, update the card's line total
                        const cardColor = card.find('.color-input').val() || null;
                        if (cardColor === currentItemColor) {
                            // The removed item matches the card's color, reset the card
                            card.find('.qty-input').val(0);
                            card.find('.color-input').val('');
                            card.find('.line-total').text(formatCurrency(0));
                            
                            // Reset color picker
                            const wrapper = card.find('.color-picker-wrapper');
                            wrapper.find('.color-preview').css({
                                'background-color': 'transparent',
                                'border': '1px solid #ddd'
                            });
                            wrapper.find('.color-picker-text').text('<?php echo e(__('app.front.color_placeholder')); ?>');
                            wrapper.find('.color-option').removeClass('active');
                        } else {
                            // Update line total to reflect remaining items with different colors
                            const totalQuantity = remainingItems.reduce((sum, [key, item]) => sum + item.quantity, 0);
                            const serviceType = remainingItems[0][1].serviceType;
                            const price = serviceType === 'washing' ? Number(card.data('wash')) : Number(card.data('iron'));
                            card.find('.line-total').text(formatCurrency(price * totalQuantity));
                        }
                    }
                }
                
                // Hide modal
                bsModal.hide();
                
                // Show toast
                showToast(`${itemNameForToast}${colorTextForToast} ${<?php echo json_encode(__('app.items.deleted'), 15, 512) ?>}`, 'info');
            });
            
            // Show modal
            bsModal.show();
        });

        function buildPayload() {
            const items = Object.values(state.items).map(item => ({
                id: item.id,
                quantity: item.quantity,
                color: item.color || null,
                serviceType: item.serviceType || state.serviceType,
            }));

            if (!state.gender) {
                throw new Error('Please select a gender.');
            }

            if (items.length === 0) {
                throw new Error('Add at least one item.');
            }

            return {
                customer_name: $('#customerName').val(),
                gender: state.gender,
                service_type: state.serviceType,
                discount_amount: Number($('#discountInput').val()) || 0,
                mark_paid: $('#markPaidSwitch').is(':checked'),
                items,
            };
        }

        async function submitOrder(printAfter = false) {
            try {
                $('#saveSpinner').removeClass('d-none');
                $('#saveOrderBtn, #savePrintBtn').prop('disabled', true);
                const payload = buildPayload();

                const response = await axios.post("<?php echo e(route('service-orders.store')); ?>", payload, {
                    headers: { 'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>' },
                });

                showToast(successMessage, 'success');
                
                // Clear localStorage after successful save
                clearStateFromLocalStorage();

                if (printAfter && response.data.receipt_url) {
                    for (let i = 0; i < receiptCopies; i++) {
                        window.open(response.data.receipt_url + '?copy=' + (i + 1), '_blank');
                    }
                }

                setTimeout(() => window.location.reload(), 1200);
            } catch (error) {
                const message = error.response?.data?.message || errorMessage;
                showToast(message, 'danger');
            } finally {
                $('#saveSpinner').addClass('d-none');
                $('#saveOrderBtn, #savePrintBtn').prop('disabled', false);
            }
        }

        $('#saveOrderBtn').on('click', () => submitOrder(false));
        $('#savePrintBtn').on('click', () => submitOrder(true));
        
        // Search functionality
        let searchTimeout;
        const searchRoute = <?php echo json_encode(route('items.search'), 15, 512) ?>;
        const colorPlaceholder = <?php echo json_encode(__('app.front.color_placeholder'), 15, 512) ?>;
        const addToCartText = <?php echo json_encode(__('app.front.add_to_cart'), 15, 512) ?>;
        const colorLabel = <?php echo json_encode(__('app.front.color_label'), 15, 512) ?>;
        const quantityLabel = <?php echo json_encode(__('app.front.quantity'), 15, 512) ?>;
        
        // Store original items HTML for restoring
        const originalItemsHtml = $('#itemsGrid').html();
        
        function createItemCard(item) {
            const price = state.serviceType === 'washing' ? item.default_wash_price : item.default_iron_price;
            const allItemsForThisId = findItemsByItemId(item.id);
            const hasItem = allItemsForThisId.length > 0 && allItemsForThisId.some(([key, item]) => item.quantity > 0);
            
            return `
                <div class="col-12 col-sm-6 col-xl-4">
                    <div class="item-card rounded-4 p-3 h-100 d-flex flex-column" 
                         data-item-id="${item.id}"
                         data-name="${item.name}"
                         data-wash="${item.default_wash_price}"
                         data-iron="${item.default_iron_price}">
                        <div class="position-relative text-center mb-3">
                            <img src="${item.image_url}" alt="${item.name}"
                                 class="rounded-4 img-fluid shadow-sm object-fit-cover" style="height:220px;width:100%;object-fit:cover;">
                            <div class="price-badge position-absolute top-0 end-0 mt-2 me-2">
                                <span class="price-currency">${currency}</span>
                                <span class="price-amount">${Number(price).toFixed(2)}</span>
                            </div>
                        </div>
                        <h5 class="fw-semibold mb-1">${item.name}</h5>
                        <div class="mb-2">
                            <label class="form-label small mb-1">${colorLabel}</label>
                            <div class="color-picker-wrapper">
                                <button type="button" class="btn btn-outline-secondary btn-sm w-100 color-picker-btn rounded-3 d-flex align-items-center justify-content-between" data-bs-toggle="dropdown" aria-expanded="false">
                                    <span class="d-flex align-items-center gap-2">
                                        <span class="color-preview" style="width: 18px; height: 18px; border-radius: 50%; border: 1px solid #ddd; background: transparent; display: inline-block;"></span>
                                        <span class="color-picker-text">${colorPlaceholder}</span>
                                    </span>
                                    <i class="bi bi-chevron-down"></i>
                                </button>
                                <ul class="dropdown-menu color-picker-dropdown p-3">
                                    <div class="color-grid">
                                        <button type="button" class="color-option" data-color="white" data-value="white" style="background: #ffffff; border: 1px solid #ddd;" title="${colorTranslations.white}">
                                            <span class="color-name">${colorTranslations.white}</span>
                                        </button>
                                        <button type="button" class="color-option" data-color="black" data-value="black" style="background: #000000;" title="${colorTranslations.black}">
                                            <span class="color-name">${colorTranslations.black}</span>
                                        </button>
                                        <button type="button" class="color-option" data-color="red" data-value="red" style="background: #dc3545;" title="${colorTranslations.red}">
                                            <span class="color-name">${colorTranslations.red}</span>
                                        </button>
                                        <button type="button" class="color-option" data-color="blue" data-value="blue" style="background: #0d6efd;" title="${colorTranslations.blue}">
                                            <span class="color-name">${colorTranslations.blue}</span>
                                        </button>
                                        <button type="button" class="color-option" data-color="green" data-value="green" style="background: #198754;" title="${colorTranslations.green}">
                                            <span class="color-name">${colorTranslations.green}</span>
                                        </button>
                                        <button type="button" class="color-option" data-color="yellow" data-value="yellow" style="background: #ffc107;" title="${colorTranslations.yellow}">
                                            <span class="color-name">${colorTranslations.yellow}</span>
                                        </button>
                                        <button type="button" class="color-option" data-color="orange" data-value="orange" style="background: #fd7e14;" title="${colorTranslations.orange}">
                                            <span class="color-name">${colorTranslations.orange}</span>
                                        </button>
                                        <button type="button" class="color-option" data-color="purple" data-value="purple" style="background: #6f42c1;" title="${colorTranslations.purple}">
                                            <span class="color-name">${colorTranslations.purple}</span>
                                        </button>
                                        <button type="button" class="color-option" data-color="pink" data-value="pink" style="background: #e91e63;" title="${colorTranslations.pink}">
                                            <span class="color-name">${colorTranslations.pink}</span>
                                        </button>
                                        <button type="button" class="color-option" data-color="brown" data-value="brown" style="background: #8b4513;" title="${colorTranslations.brown}">
                                            <span class="color-name">${colorTranslations.brown}</span>
                                        </button>
                                        <button type="button" class="color-option" data-color="gray" data-value="gray" style="background: #6c757d;" title="${colorTranslations.gray}">
                                            <span class="color-name">${colorTranslations.gray}</span>
                                        </button>
                                        <button type="button" class="color-option" data-color="beige" data-value="beige" style="background: #f5f5dc; border: 1px solid #ddd;" title="${colorTranslations.beige}">
                                            <span class="color-name">${colorTranslations.beige}</span>
                                        </button>
                                        <button type="button" class="color-option" data-color="navy" data-value="navy" style="background: #001f3f;" title="${colorTranslations.navy}">
                                            <span class="color-name">${colorTranslations.navy}</span>
                                        </button>
                                        <button type="button" class="color-option" data-color="other" data-value="other" style="background: #cccccc;" title="${colorTranslations.other}">
                                            <span class="color-name">${colorTranslations.other}</span>
                                        </button>
                                    </div>
                                </ul>
                                <input type="hidden" class="color-input" value="">
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label small mb-2">${quantityLabel}</label>
                            <div class="d-flex align-items-center gap-2">
                                <div class="btn-group" role="group">
                                    <button type="button" class="btn btn-light btn-sm qty-btn" data-action="dec">
                                        <i class="bi bi-dash-lg"></i>
                                    </button>
                                    <input type="text" class="form-control form-control-sm text-center qty-input" value="0" readonly style="width:60px;">
                                    <button type="button" class="btn btn-light btn-sm qty-btn" data-action="inc">
                                        <i class="bi bi-plus-lg"></i>
                                    </button>
                                </div>
                                <button type="button" class="btn btn-primary btn-sm flex-grow-1 add-to-cart-btn rounded-3">
                                    <i class="bi bi-cart-plus me-1"></i>${addToCartText}
                                </button>
                            </div>
                        </div>
                        <div class="d-flex justify-content-center">
                            <span class="badge bg-primary-subtle text-primary fw-semibold px-3 py-2">
                                <span class="line-total">${formatCurrency(0)}</span>
                            </span>
                        </div>
                    </div>
                </div>
            `;
        }
        
        async function searchItems(query) {
            try {
                const response = await axios.get(searchRoute, {
                    params: { q: query }
                });
                
                const itemsGrid = $('#itemsGrid');
                itemsGrid.empty();
                
                if (response.data.items && response.data.items.length > 0) {
                    response.data.items.forEach(item => {
                        itemsGrid.append(createItemCard(item));
                    });
                    updatePriceBadges();
                } else {
                    const noResultsText = <?php echo json_encode(__('app.front.no_search_results'), 15, 512) ?>;
                    itemsGrid.html(`<div class="col-12 text-center text-muted py-5"><i class="bi bi-search fs-1 d-block mb-2"></i><p>${noResultsText}</p></div>`);
                }
            } catch (error) {
                console.error('Search error:', error);
                showToast(errorMessage, 'danger');
            }
        }
        
        $('#itemSearchInput').on('input', function() {
            const query = $(this).val().trim();
            
            clearTimeout(searchTimeout);
            
            // Enable/disable clear button
            $('#clearSearchBtn').prop('disabled', query.length === 0);
            
            if (query.length === 0) {
                // Restore original items
                const itemsGrid = $('#itemsGrid');
                itemsGrid.html(originalItemsHtml);
                updatePriceBadges();
                return;
            }
            
            searchTimeout = setTimeout(() => {
                searchItems(query);
            }, 300); // 300ms debounce
        });
        
        // Clear search button
        $('#clearSearchBtn').on('click', function() {
            if ($(this).prop('disabled')) {
                return;
            }
            $('#itemSearchInput').val('').trigger('input').focus();
        });
        
        // Clear order button
        $('#clearOrderBtn').on('click', function() {
            if (Object.keys(state.items).length === 0) {
                showToast(orderClearedText, 'info');
                return;
            }
            
            // Create confirmation modal
            const modalId = 'clearOrderModal';
            let modal = document.getElementById(modalId);
            
            if (!modal) {
                modal = document.createElement('div');
                modal.className = 'modal fade';
                modal.id = modalId;
                modal.setAttribute('tabindex', '-1');
                modal.innerHTML = `
                    <div class="modal-dialog modal-dialog-centered">
                        <div class="modal-content">
                            <div class="modal-header border-0 pb-0">
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body text-center px-4 pb-4">
                                <div class="mb-3">
                                    <div class="bg-danger-subtle rounded-circle d-inline-flex align-items-center justify-content-center" style="width: 64px; height: 64px;">
                                        <i class="bi bi-trash-fill text-danger fs-2"></i>
                                    </div>
                                </div>
                                <h5 class="modal-title fw-bold mb-2">${clearOrderText}</h5>
                                <p class="text-muted mb-0">${clearOrderConfirmText}</p>
                            </div>
                            <div class="modal-footer border-0 justify-content-center gap-2 pb-4">
                                <button type="button" class="btn btn-outline-secondary btn-rounded" data-bs-dismiss="modal">
                                    <?php echo e(__('app.items.form.cancel')); ?>

                                </button>
                                <button type="button" class="btn btn-danger btn-rounded" id="confirmClearOrderBtn">
                                    <i class="bi bi-trash me-2"></i>${clearOrderText}
                                </button>
                            </div>
                        </div>
                    </div>
                `;
                document.body.appendChild(modal);
            }
            
            // Show modal
            const bsModal = new bootstrap.Modal(modal);
            bsModal.show();
            
            // Handle confirm button
            $('#confirmClearOrderBtn').off('click').on('click', function() {
                // Clear state
                state.items = {};
                state.customerName = '';
                state.discount = 0;
                state.markPaid = false;
                
                // Clear form fields
                $('#customerName').val('');
                $('#discountInput').val(0);
                $('#markPaidSwitch').prop('checked', false);
                
                // Reset all item cards
                $('#itemsGrid .item-card').each(function() {
                    const card = $(this);
                    const itemId = card.data('item-id');
                    card.find('.qty-input').val(0);
                    card.find('.color-input').val('');
                    card.find('.line-total').text(formatCurrency(0));
                    
                    // Reset color picker
                    const wrapper = card.find('.color-picker-wrapper');
                    wrapper.find('.color-preview').css({
                        'background-color': 'transparent',
                        'border': '1px solid #ddd'
                    });
                    wrapper.find('.color-picker-text').text(colorPlaceholder);
                    wrapper.find('.color-option').removeClass('active');
                });
                
                // Refresh summary
                refreshSummary();
                
                // Clear localStorage
                clearStateFromLocalStorage();
                
                // Hide modal
                bsModal.hide();
                
                // Show toast
                showToast(orderClearedText, 'info');
            });
        });
        
        // Save customer name and discount to state
        $('#customerName').on('input', function() {
            state.customerName = $(this).val();
            saveStateToLocalStorage();
        });
        
        $('#discountInput').on('input', function() {
            state.discount = Number($(this).val()) || 0;
            saveStateToLocalStorage();
        });
        
        $('#markPaidSwitch').on('change', function() {
            state.markPaid = $(this).is(':checked');
            saveStateToLocalStorage();
        });
        
        // Restore state from localStorage on page load
        function restoreState() {
            loadStateFromLocalStorage();
            
            // Restore gender
            $(`.gender-btn[data-gender="${state.gender}"]`).click();
            
            // Restore service type
            $(`.service-type-btn[data-service-type="${state.serviceType}"]`).click();
            
            // Restore customer name
            if (state.customerName) {
                $('#customerName').val(state.customerName);
            }
            
            // Restore discount
            if (state.discount) {
                $('#discountInput').val(state.discount);
            }
            
            // Restore mark paid
            if (state.markPaid) {
                $('#markPaidSwitch').prop('checked', true);
            }
            
            // Restore items in cards
            // Note: Since we now support multiple colors per item, we don't restore
            // the card state directly. The summary will show all items correctly.
            // Update price badges and summary
            if (Object.keys(state.items).length > 0) {
                updatePriceBadges();
            }
        }
        
        // Initialize price badges on page load
        $(document).ready(function() {
            restoreState();
            updatePriceBadges();
        });
    </script>
<?php $__env->stopPush(); ?>


<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\lavandera\resources\views/front/service-orders.blade.php ENDPATH**/ ?>