<?php echo $__env->make('header', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<style>
button.btn.btn-dark.mt-3 {
    background: #c18c14;
    border: #c18c14;
}
.container, .container-lg, .container-md, .container-sm, .container-xl, .container-xxl {
    max-width: 100% !important;
}

    select.filter.d-block {
width: 100%;
    height: 48px;
    border: 1px solid #2e2e2e !important;
    background: #f8f8f8;
    padding: 0 42px 0 14px;
    font-size: 18px;
    appearance: none;
    background-image: url(https://cdn.shopify.com/s/files/1/0665/9060/5610/files/download.svg?v=1775829237);
    background-repeat: no-repeat;
    background-position: right 14px center;
}
#ring_size,
#carat_size {
    width: 100% !important;
    display: block;
}
#pendantInfoMessage {
    display: none;
    margin-top: 28px;
    font-size: 16px;
    line-height: 1.6;
}
 .modal-content {
      border-radius: 12px;
    }

    #preview {
      border-radius: 10px;
      border: 1px solid #ddd;
    }
    .offcanvas.offcanvas-open {
    visibility: visible !important;
}
.widget-contact2 p a {
    color: #fff !important;
}
iframe {
    height: 700px;
}
</style>
<section id="diamond-detail">

    <div class="container-fluid">

        <div class="row p-2 align-items-center header_wrapper">

            <div class="col-xxl-2 col-xl-2 col-lg-2 col-md-2 col-sm-2 col-xs-2">

                <div class="logo-wrapper">

                   
                </div>

            </div>

            <div class="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-6 col-xs-6">

                <div class="title text-center">

                    <h3 id="jewelryTitle" class="m-0"> <?php echo e($item->shank_style); ?> <?php echo e($item->head_style); ?></h3>

                </div>



            </div>

            <div class="col-xxl-4 col-xl-4 col-lg-4 col-md-4 col-sm-4 col-xs-4">

               <div class="tab">
                    <ul class="p-0 m-0 d-flex align-items-center justify-content-start gap-2" id="jewelryMenu">

                        <li class="text-uppercase active" data-type="ring">
                            <a href="javascript:void(0)">Rings</a>
                        </li>

                        <li class="text-uppercase" data-type="earring">
                            <a href="javascript:void(0)">Earrings</a>
                        </li>

                        <li class="text-uppercase" data-type="pendant">
                            <a href="javascript:void(0)">Pendants</a>
                        </li>

                    </ul>

                    <!-- Data show yaha hoga -->
                    <div id="jewelryData"></div>

               </div>

            </div>

        </div>

    </div>

    <div class="container-fluid">


        <input type="hidden" id="master_id" value="<?php echo e($item->master_id); ?>">
        

        <div class="row position-relative">



            <div class="col-xxl-8 col-xl-8 col-lg-7 col-md-12 p-0" id="jewelryResults">
              
            </div>


            <input type="hidden" name="selected_shape" id="selected_shape_input">



            <div class="col-xxl-4 col-xl-4 col-lg-5 col-md-12">

                <div id="response"></div>

                    <div class="filter-sec">

                        <div class="filter-type mt-4">

                            <p>Shape:</p>

                            <ul class="shape-slider d-flex align-items-center flex-wrap">

                                <?php

                                $allShapes = [

                                'RD' => ['name' => 'Round', 'image' => 'round'],

                                'OV' => ['name' => 'Oval', 'image' => 'oval'],

                                'PR' => ['name' => 'Princess', 'image' => 'princess'],

                                'EM' => ['name' => 'Emerald', 'image' => 'emerald'],

                                'PE' => ['name' => 'Pear', 'image' => 'pear'],

                                'CU' => ['name' => 'Cushion', 'image' => 'cushion'],

                                'MQ' => ['name' => 'Marquise', 'image' => 'marquise'],

                                'HE' => ['name' => 'Heart', 'image' => 'heart'],

                                ];

                                ?>

                                <?php $__currentLoopData = $allShapes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $shapeCode => $shapeData): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                               

                                <li

                                    class="d-flex flex-column align-items-center justify-content-around position-relative">

                                    <img class="img-fluid"

                                        src="<?php echo e(asset('/public/ringbuilderassets/image/' . $shapeData['image'] . '.png')); ?>"

                                        alt="<?php echo e($shapeData['name']); ?>">

                                    <label for="<?php echo e($shapeCode); ?>"><?php echo e($shapeData['name']); ?></label>

                                    <input type="checkbox" name="shape" class="filter" data-type="shape"

                                        data-stock_id="" data-value="<?php echo e($shapeCode); ?>" id="<?php echo e($shapeCode); ?>"

                                        <?php echo e(isset($shapeStockMap[$shapeCode]) ? '' : 'disabled'); ?>>

                                </li>

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



                            </ul>

                        </div>

                        <div class="filter-type Band d-none">

                            <?php if(request()->is('jewelry/type/ring') || request()->is('jewelry/type/pendant')): ?>

                            <p>Head Style:</p>



                            <ul>

                                <?php $__currentLoopData = $headStyles; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $style => $items): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>

                                <?php

                                $firstStockId = $items->first()->stock_id;

                                ?>



                                <li

                                    class="d-flex flex-column align-items-center justify-content-around position-relative">

                                    <img class="img-fluid" src="<?php echo e(asset('/public/ringbuilderassets/image/prong.png')); ?>" alt="">

                                    <label for="<?php echo e($style); ?>"><?php echo e($style); ?></label>

                                    <input type="checkbox" name="head_style" class="filter" data-type="head_style"

                                        data-value="<?php echo e($style); ?>" id="head_style_<?php echo e($loop->index); ?>">

                                </li>

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


                            </ul>

                            <?php endif; ?>

                        </div>

                        <div class="filter-type metal ">

                            <div class="row d-none">

                                <div class="col-xxl-6 col-xl-6 col-lg-6 col-md-12 col-sm-12 col-xs-12 col-12  ">

                                    <p>Head Metal:</p>

                                    <ul class="d-flex align-items-center metal_filter_ring">

                                        <?php $__currentLoopData = $metalHeads; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $metal_head => $items): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>

                                        <?php

                                        $firstStockId = $items->first()->stock_id;

                                        ?>

                                        <?php if($metal_head == 'WG'): ?>

                                        <li

                                            class="d-flex flex-column align-items-center justify-content-around position-relative white">

                                            <label class="d-flex align-items-center justify-content-center"

                                                for="metal_head_<?php echo e($loop->index); ?>">

                                                14

                                            </label>

                                            <input type="checkbox" name="metal_head" class="filter"

                                                data-type="metal_head" data-value="<?php echo e($metal_head); ?>"

                                                id="metal_head_<?php echo e($loop->index); ?>">

                                        </li>

                                        <?php elseif($metal_head == 'YG'): ?>

                                        <li

                                            class="d-flex flex-column align-items-center justify-content-around position-relative yellow">

                                            <label class="d-flex align-items-center justify-content-center"

                                                for="metal_head_<?php echo e($loop->index); ?>">

                                                14

                                            </label>

                                            <input type="checkbox" name="metal_head" class="filter"

                                                data-type="metal_head" data-value="<?php echo e($metal_head); ?>"

                                                id="metal_head_<?php echo e($loop->index); ?>">

                                        </li>

                                        <?php elseif($metal_head == 'RG'): ?>

                                        <li

                                            class="d-flex flex-column align-items-center justify-content-around position-relative rose">

                                            <label class="d-flex align-items-center justify-content-center"

                                                for="metal_head_<?php echo e($loop->index); ?>">

                                                14

                                            </label>

                                            <input type="checkbox" name="metal_head" class="filter"

                                                data-type="metal_head" data-value="<?php echo e($metal_head); ?>"

                                                id="metal_head_<?php echo e($loop->index); ?>">

                                        </li>

                                        <?php endif; ?>

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



                                    </ul>

                                </div>

                                <div class="col-xxl-6 col-xl-6 col-lg-6 col-md-12 col-sm-12 col-xs-12 col-12 ">

                                    <?php if(request()->is('jewelry/type/ring') || request()->is('jewelry/type/pendant')): ?>

                                    <!-- <p>Head Style:</p> -->

                                    <p>Band Metal:</p>

                                    <ul class="d-flex align-items-center metal_filter_ring">

                                        <?php $__currentLoopData = $shankMetals; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $metal_head => $items): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>

                                        <?php

                                        $firstStockId = $items->first()->stock_id;

                                        ?>

                                        <?php if($metal_head == 'WG'): ?>

                                        <li

                                            class="d-flex flex-column align-items-center justify-content-around position-relative white">

                                            <label class="d-flex align-items-center justify-content-center"

                                                for="metal_head_<?php echo e($loop->index); ?>">

                                                14

                                            </label>



                                            <input type="checkbox" name="metal_head" class="filter"

                                                data-type="shank_metals" data-value="<?php echo e($metal_head); ?>"

                                                id="metal_head_<?php echo e($loop->index); ?>">

                                        </li>

                                        <?php elseif($metal_head == 'YG'): ?>

                                        <li

                                            class="d-flex flex-column align-items-center justify-content-around position-relative yellow">

                                            <label class="d-flex align-items-center justify-content-center"

                                                for="metal_head_<?php echo e($loop->index); ?>">

                                                14

                                            </label>



                                            <input type="checkbox" name="metal_head" class="filter"

                                                data-type="shank_metals" data-value="<?php echo e($metal_head); ?>"

                                                id="metal_head_<?php echo e($loop->index); ?>">

                                        </li>

                                        <?php elseif($metal_head == 'RG'): ?>

                                        <li

                                            class="d-flex flex-column align-items-center justify-content-around position-relative rose">

                                            <label class="d-flex align-items-center justify-content-center"

                                                for="metal_head_<?php echo e($loop->index); ?>">

                                                14

                                            </label>



                                            <input type="checkbox" name="metal_head" class="filter"

                                                data-type="shank_metals" data-value="<?php echo e($metal_head); ?>"

                                                id="metal_head_<?php echo e($loop->index); ?>">

                                        </li>

                                        <?php endif; ?>

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



                                    </ul>

                                </div>

                                <?php endif; ?>

                            </div>





                        </div>

                        <div class="filter-type Band">

                            <!-- <h4>Band</h4> -->

                            <p>Style:</p>

                            <?php
                                $defaultRingBandStyles = ['Solitaire', 'Knife Edge', 'French Pave', 'Cathedral Pave'];
                                $defaultRingBandIndex = 0;
                            ?>

                            <ul id="bandStyleList" class="d-flex align-items-center flex-wrap">

                                <?php $__currentLoopData = $shankStyles; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $shank_style => $items): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <?php if(!in_array(trim($shank_style), $defaultRingBandStyles)) continue; ?>

                                <?php
                                $firstStockId = $items->first()->stock_id;
                                $isDefaultRingBand = $defaultRingBandIndex === 0;
                                ?>

                                <?php if($shank_style =='Solitaire'): ?>

                                <li

                                    class="d-flex flex-column align-items-center justify-content-around position-relative <?php echo e($isDefaultRingBand ? 'active' : ''); ?>">

                                    <img class="img-fluid" src="<?php echo e(asset('/public/ringbuilderassets/image/Solitaire.png')); ?>" alt="">



                                    <label for="shank_style_<?php echo e($loop->index); ?>"><?php echo e($shank_style); ?></label>



                                    <input type="checkbox" name="shank_style" class="filter" data-type="shank_style"

                                        data-value="<?php echo e($shank_style); ?>" id="shank_style_<?php echo e($loop->index); ?>" <?php echo e($isDefaultRingBand ? 'checked' : ''); ?>>

                                </li>

                                <?php elseif($shank_style =='Knife Edge'): ?>



                                <li

                                    class="d-flex flex-column align-items-center justify-content-around position-relative <?php echo e($isDefaultRingBand ? 'active' : ''); ?>">

                                    <img class="img-fluid" src="<?php echo e(asset('/public/ringbuilderassets/image/knife-edge-solitaire.png')); ?>"

                                        alt="">

                                    <label for="knife-edge-solitaire"><?php echo e($shank_style); ?></label>

                                    <input type="checkbox" name="shank_style" class="filter" data-type="shank_style"

                                        data-value="<?php echo e($shank_style); ?>" id="shank_style_<?php echo e($loop->index); ?>" <?php echo e($isDefaultRingBand ? 'checked' : ''); ?>>

                                </li>

                                <?php elseif($shank_style =='French Pave'): ?>

                                <li

                                    class="d-flex flex-column align-items-center justify-content-around position-relative <?php echo e($isDefaultRingBand ? 'active' : ''); ?>">

                                    <img class="img-fluid" src="<?php echo e(asset('/public/ringbuilderassets/image/french-pave.png')); ?>" alt="">

                                    <label for="french-pave"><?php echo e($shank_style); ?></label>

                                    <input type="checkbox" name="shank_style" class="filter" data-type="shank_style"

                                        data-value="<?php echo e($shank_style); ?>" id="shank_style_<?php echo e($loop->index); ?>" <?php echo e($isDefaultRingBand ? 'checked' : ''); ?>>

                                </li>

                                <?php elseif($shank_style =='Cathedral Pave'): ?>

                                <li

                                    class="d-flex flex-column align-items-center justify-content-around position-relative <?php echo e($isDefaultRingBand ? 'active' : ''); ?>">

                                    <img class="img-fluid" src="<?php echo e(asset('/public/ringbuilderassets/image/cathedral-pave.png')); ?>"

                                        alt="">

                                    <label for="cathedral-pave"><?php echo e($shank_style); ?></label>

                                    <input type="checkbox" name="shank_style" class="filter" data-type="shank_style"

                                        data-value="<?php echo e($shank_style); ?>" id="shank_style_<?php echo e($loop->index); ?>" <?php echo e($isDefaultRingBand ? 'checked' : ''); ?>>

                                </li>

                                <?php endif; ?>

                                <?php $defaultRingBandIndex++; ?>

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

                            </ul>

                        </div>



                    <?php
                        $allowedSizes = [
                            '3',
                            '3.5',
                            '4',
                            '4.5',
                            '5',
                            '5.5',
                            '6',
                            '6.5',
                            '7',
                            '7.5',
                            '8',
                            '8.5',
                            '9',
                            '9.5',
                            '10'
                        ];
                    ?>
                    
                    <div class="filter-type ring-size">
                    
                        <div class="row align-items-center">
                    
                            <div class="
                                col-xxl-12
                                col-xl-12
                                col-lg-12
                                col-md-12
                                col-sm-12
                                col-xs-12
                                ring-size-control
                            ">
                    
                                <label for="ring_size">
                                    Select Ring Size:
                                </label>
                    
                                <select
                                    name="ring_size"
                                    class="filter d-block mt-2"
                                    id="ring_size"
                                >
                    
                                    <option value="">
                                        Select Size
                                    </option>
                    
                                    <?php $__currentLoopData = $allowedSizes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $size): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    
                                        <option
                                            value="<?php echo e($size); ?>"
                                            <?php echo e($size == '7' ? 'selected' : ''); ?>

                                        >
                                            <?php echo e($size); ?>

                                        </option>
                    
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    
                                </select>
                    
                            </div>
                    
                        </div>
                    
                    </div>
                                <div class="filter-type ring-size ">

                                    <label for="ring_size">Select Carats:</label>

                                    <select name="carat_size" class="filter d-block mt-2" id="carat_size">

                                        <option value="">Select Carats</option>

                                      
                                        <option value="1">1 cttw</option>

                                        <option value="1.5">1.5 cttw</option>

                                        <option value="2">2 cttw</option>

                                        <option value="2.5">2.5 cttw</option>

                                        <option value="3">3 cttw</option>

                                        <option value="3.5">3.5 cttw</option>

                                        <option value="4.5">4.5 cttw</option>

                                        <option value="5">5 cttw</option>

                                        <option value="5.5">5.5 cttw</option>

                                        <option value="6">6 cttw</option>

                                        <option value="6.5">6.5 cttw</option>

                                        <option value="7">7 cttw</option>

                                        <option value="7.5">7.5 cttw</option>

                                        <option value="8">8 cttw</option>

                                        <option value="8.5">8.5 cttw</option>

                                        <option value="9">9 cttw</option>

                                        <option value="9.5">9.5 cttw</option>

                                        <option value="10">10 cttw</option>

                                    </select>

                                </div>

                                <!-- <div class="col-xxl-4 col-xl-4 col-lg-4 col-md-4 col-sm-4 col-xs-4">

                                    <div class="price" id="priceDisplay">

                                          <button class="btn dark">EMAIL US</button>

                                    </div>

                                </div> -->

                            </div>





                        </div>

                        <div id="pendantInfoMessage">
                            The pendant comes with a 16-inch chain, and all pieces are made in 14-carat gold.
                        </div>

                            <div class="side-data">
                            
                                                <!-- Trigger Button -->
                            <button class="btn btn-dark mt-3" data-bs-toggle="modal" data-bs-target="#emailModal">
                                Email Us
                            </button>
                           <button type="button" class="btn btn-dark mt-3" id="createProductBtn">
                                        Buy Now
                              </button>
                            
                            <!-- Modal -->
                            <div class="modal fade" id="emailModal" tabindex="-1">
                                <div class="modal-dialog modal-dialog-centered">
                                <div class="modal-content p-3">
                            
                                    <!-- Header -->
                                    <div class="modal-header border-0">
                                    <h5 class="modal-title">Send Screenshot</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                    </div>
                            
                                    <!-- Body -->
                                    <div class="modal-body">
                            
                                    <form method="POST" id="Form_email_submit" enctype="multipart/form-data">
                                        
                                        <!-- Email -->
                                        <input type="email" name="email" class="form-control mb-3" placeholder="Enter Email" required>
                            
                                        <!-- Comment Textarea -->
                                        <textarea name="comment" class="form-control mb-3" rows="4" placeholder="Add your comment..." required></textarea>
                            
                                        <!-- Screenshot Button -->
                                        <button type="button" class="btn btn-outline-dark w-100 mb-3" onclick="takeScreenshot()">
                                        Take Screenshot
                                        </button>
                            
                                        <!-- Preview -->
                                        <img id="preview" class="img-fluid mb-3" style="display:none;" />
                            
                                        <!-- Hidden input -->
                                        <input type="hidden" name="screenshot" id="screenshotInput">
                                        
                                        <div id="emailStatusMessage" style="display:none;margin-bottom:12px;padding:10px 12px;border-radius:6px;font-size:14px;"></div>
                            
                                        <!-- Submit -->
                                        <button type="submit" class="btn btn-dark w-100">
                                        Send Email
                                        </button>
                            
                                    </form>
                            
                                    </div>
                            
                                </div>
                                </div>
                            </div>


                    </div>




                </div>

            </div>

        </div>

    </div>

</section>

<script>
     const allowedRingSizes = <?php echo json_encode(array_map('strval', $allowedSizes), 512) ?>;
  
let capturedScreenCanvas = null;
let selectionOverlay = null;
let selectionBox = null;

let selectionStartX = 0;
let selectionStartY = 0;
let isSelectingArea = false;

/*
|--------------------------------------------------------------------------
| BUY BUTTON
|--------------------------------------------------------------------------
*/

$(document).on('click', '#createProductBtn', async function () {

    $('#createProductBtn')
        .prop('disabled', true)
        .text('Capturing Ring...');

    try {
        await captureFullScreenForProduct();
    } catch (error) {
        console.error('Screen capture error:', error);

        $('#createProductBtn')
            .prop('disabled', false)
            .text('BUY');

        alert(
            'Screen capture cancel hua. Entire Screen select karke Share karein.'
        );
    }
});

/*
|--------------------------------------------------------------------------
| CAPTURE ENTIRE SCREEN
|--------------------------------------------------------------------------
*/

async function captureFullScreenForProduct() {

    let stream = null;

    try {
        stream = await navigator.mediaDevices.getDisplayMedia({
            video: {
                displaySurface: 'monitor',
                frameRate: {
                    ideal: 30,
                    max: 30
                }
            },
            audio: false,

            /*
             * Browser popup me Entire Screen select karna hai.
             */
            preferCurrentTab: false,
            selfBrowserSurface: 'include',
            surfaceSwitching: 'exclude'
        });

        const video = document.createElement('video');

        video.srcObject = stream;
        video.muted = true;
        video.playsInline = true;

        await video.play();

        await new Promise(function (resolve) {
            if (
                video.videoWidth > 0 &&
                video.videoHeight > 0
            ) {
                resolve();
                return;
            }

            video.onloadedmetadata = resolve;
        });

        /*
        |--------------------------------------------------------------------------
        | Ring/WebGL frame load hone ka wait
        |--------------------------------------------------------------------------
        */

        await new Promise(function (resolve) {
            setTimeout(resolve, 1500);
        });

        if (
            typeof video.requestVideoFrameCallback === 'function'
        ) {
            await new Promise(function (resolve) {
                video.requestVideoFrameCallback(resolve);
            });
        }

        /*
        |--------------------------------------------------------------------------
        | Entire screen frame canvas me draw karein
        |--------------------------------------------------------------------------
        */

        capturedScreenCanvas =
            document.createElement('canvas');

        capturedScreenCanvas.width =
            video.videoWidth;

        capturedScreenCanvas.height =
            video.videoHeight;

        const context =
            capturedScreenCanvas.getContext('2d');

        context.drawImage(
            video,
            0,
            0,
            video.videoWidth,
            video.videoHeight
        );

        stream.getTracks().forEach(function (track) {
            track.stop();
        });

        video.srcObject = null;
        video.remove();

        /*
        |--------------------------------------------------------------------------
        | Automatically crop the Ring viewer area
        |--------------------------------------------------------------------------
        */

        autoCropRingViewerArea();

    } catch (error) {

        if (stream) {
            stream.getTracks().forEach(function (track) {
                track.stop();
            });
        }

        throw error;
    }
}

/*
|--------------------------------------------------------------------------
| AUTOMATICALLY CROP RING VIEWER AREA
|--------------------------------------------------------------------------
|
| This uses the visible #jewelryResults / iframe position and automatically
| crops that area from the Entire Screen capture.
|
*/

function autoCropRingViewerArea() {

    try {

        if (!capturedScreenCanvas) {
            throw new Error('Captured screen image not found.');
        }

        /*
        |--------------------------------------------------------------------------
        | Find the Ring viewer element
        |--------------------------------------------------------------------------
        */

        const targetElement =
            document.querySelector('#jewelryResults .pro-img') ||
            document.querySelector('#jewelryResults iframe') ||
            document.getElementById('jewelryResults');

        if (!targetElement) {
            throw new Error('Ring viewer area not found.');
        }

        const targetRect =
            targetElement.getBoundingClientRect();

        if (
            targetRect.width <= 0 ||
            targetRect.height <= 0
        ) {
            throw new Error('Ring viewer area is not visible.');
        }

        /*
        |--------------------------------------------------------------------------
        | Screen capture dimensions
        |--------------------------------------------------------------------------
        */

        const sourceWidth =
            capturedScreenCanvas.width;

        const sourceHeight =
            capturedScreenCanvas.height;

        /*
        |--------------------------------------------------------------------------
        | Convert browser page position to physical screen position
        |--------------------------------------------------------------------------
        |
        | Entire Screen capture includes browser toolbar and window borders.
        | screenX/screenY gives browser-window location on the monitor.
        | outerHeight - innerHeight estimates the browser toolbar height.
        |
        */

        const browserLeft =
            window.screenX ||
            window.screenLeft ||
            0;

        const browserTop =
            window.screenY ||
            window.screenTop ||
            0;

        const browserChromeHeight =
            Math.max(
                0,
                window.outerHeight -
                window.innerHeight
            );

        const browserBorderWidth =
            Math.max(
                0,
                (
                    window.outerWidth -
                    window.innerWidth
                ) / 2
            );

        /*
        |--------------------------------------------------------------------------
        | Screen scaling
        |--------------------------------------------------------------------------
        */

        const screenScaleX =
            sourceWidth /
            window.screen.width;

        const screenScaleY =
            sourceHeight /
            window.screen.height;

        /*
        |--------------------------------------------------------------------------
        | Add a small inner margin to remove surrounding page content
        |--------------------------------------------------------------------------
        */

        const marginX = 12;
        const marginTop = 12;
        const marginBottom = 12;

        let cropX =
            Math.round(
                (
                    browserLeft +
                    browserBorderWidth +
                    targetRect.left +
                    marginX
                ) *
                screenScaleX
            );

        let cropY =
            Math.round(
                (
                    browserTop +
                    browserChromeHeight +
                    targetRect.top +
                    marginTop
                ) *
                screenScaleY
            );

        let cropWidth =
            Math.round(
                (
                    targetRect.width -
                    (marginX * 2)
                ) *
                screenScaleX
            );

        let cropHeight =
            Math.round(
                (
                    targetRect.height -
                    marginTop -
                    marginBottom
                ) *
                screenScaleY
            );

        /*
        |--------------------------------------------------------------------------
        | Keep crop inside captured screen
        |--------------------------------------------------------------------------
        */

        cropX =
            Math.max(
                0,
                Math.min(
                    cropX,
                    sourceWidth - 1
                )
            );

        cropY =
            Math.max(
                0,
                Math.min(
                    cropY,
                    sourceHeight - 1
                )
            );

        cropWidth =
            Math.max(
                1,
                Math.min(
                    cropWidth,
                    sourceWidth - cropX
                )
            );

        cropHeight =
            Math.max(
                1,
                Math.min(
                    cropHeight,
                    sourceHeight - cropY
                )
            );

        console.log(
            'Automatic Ring Crop:',
            {
                targetRect,
                browserLeft,
                browserTop,
                browserChromeHeight,
                browserBorderWidth,
                screenScaleX,
                screenScaleY,
                cropX,
                cropY,
                cropWidth,
                cropHeight
            }
        );

        /*
        |--------------------------------------------------------------------------
        | Crop Ring viewer
        |--------------------------------------------------------------------------
        */

        const outputCanvas =
            document.createElement('canvas');

        outputCanvas.width =
            cropWidth;

        outputCanvas.height =
            cropHeight;

        const outputContext =
            outputCanvas.getContext(
                '2d',
                {
                    alpha: false
                }
            );

        outputContext.fillStyle =
            '#ffffff';

        outputContext.fillRect(
            0,
            0,
            cropWidth,
            cropHeight
        );

        outputContext.drawImage(
            capturedScreenCanvas,

            cropX,
            cropY,
            cropWidth,
            cropHeight,

            0,
            0,
            cropWidth,
            cropHeight
        );

        const selectedAreaImage =
            outputCanvas.toDataURL(
                'image/png',
                1.0
            );

        /*
        |--------------------------------------------------------------------------
        | Release large screenshot canvas and submit automatically
        |--------------------------------------------------------------------------
        */

        capturedScreenCanvas = null;

        $('#createProductBtn')
            .prop('disabled', true)
            .text('Creating...');

        submitCreateProduct(
            selectedAreaImage
        );

    } catch (error) {

        console.error(
            'Automatic Ring crop failed:',
            error
        );

        /*
         * If automatic crop fails, keep manual selection as fallback.
         */
        alert(
            'Automatic Ring selection failed. Please select the Ring area manually.'
        );

        showCapturedScreenForSelection();
    }
}

/*
|--------------------------------------------------------------------------
| SHOW CAPTURED SCREEN IN FULLSCREEN OVERLAY
|--------------------------------------------------------------------------
*/

function showCapturedScreenForSelection() {

    if (!capturedScreenCanvas) {
        alert('Screen image not found.');

        $('#createProductBtn')
            .prop('disabled', false)
            .text('BUY');

        return;
    }

    selectionOverlay =
        document.createElement('div');

    selectionOverlay.id =
        'capturedScreenOverlay';

    selectionOverlay.style.cssText = `
        position: fixed;
        inset: 0;
        width: 100vw;
        height: 100vh;
        background: #111;
        z-index: 9999999;
        overflow: hidden;
        cursor: crosshair;
        user-select: none;
    `;

    /*
    |--------------------------------------------------------------------------
    | Screenshot image
    |--------------------------------------------------------------------------
    */

    const screenshotImage =
        document.createElement('img');

    screenshotImage.id =
        'capturedScreenImage';

    screenshotImage.src =
        capturedScreenCanvas.toDataURL(
            'image/png',
            1.0
        );

    screenshotImage.style.cssText = `
        position: absolute;
        inset: 0;
        width: 100%;
        height: 100%;
        object-fit: contain;
        pointer-events: none;
    `;

    selectionOverlay.appendChild(
        screenshotImage
    );

    /*
    |--------------------------------------------------------------------------
    | Instruction
    |--------------------------------------------------------------------------
    */

    const instruction =
        document.createElement('div');

    instruction.innerHTML = `
        Ring aur required page area ko drag karke select karein.
        <button
            type="button"
            id="cancelScreenSelection"
            style="
                margin-left:15px;
                background:#fff;
                color:#000;
                border:0;
                padding:5px 12px;
                border-radius:4px;
            "
        >
            Cancel
        </button>
    `;

    instruction.style.cssText = `
        position: fixed;
        top: 15px;
        left: 50%;
        transform: translateX(-50%);
        background: rgba(0,0,0,0.85);
        color: #fff;
        padding: 10px 18px;
        border-radius: 6px;
        font-size: 14px;
        z-index: 10000002;
        cursor: default;
    `;

    selectionOverlay.appendChild(
        instruction
    );

    /*
    |--------------------------------------------------------------------------
    | Selection rectangle
    |--------------------------------------------------------------------------
    */

    selectionBox =
        document.createElement('div');

    selectionBox.id =
        'capturedAreaSelectionBox';

    selectionBox.style.cssText = `
        position: fixed;
        display: none;
        border: 3px dashed #ff0000;
        background: rgba(255,255,255,0.12);
        z-index: 10000001;
        pointer-events: none;
    `;

    document.body.appendChild(
        selectionBox
    );

    document.body.appendChild(
        selectionOverlay
    );

    selectionOverlay.addEventListener(
        'mousedown',
        startCapturedAreaSelection
    );

    $(document).off(
        'click',
        '#cancelScreenSelection'
    );

    $(document).on(
        'click',
        '#cancelScreenSelection',
        function (event) {
            event.stopPropagation();

            removeCapturedSelectionUI();

            $('#createProductBtn')
                .prop('disabled', false)
                .text('BUY');
        }
    );
}

/*
|--------------------------------------------------------------------------
| START SELECTION
|--------------------------------------------------------------------------
*/

function startCapturedAreaSelection(event) {

    if (
        event.target.id ===
        'cancelScreenSelection'
    ) {
        return;
    }

    isSelectingArea = true;

    selectionStartX =
        event.clientX;

    selectionStartY =
        event.clientY;

    selectionBox.style.left =
        selectionStartX + 'px';

    selectionBox.style.top =
        selectionStartY + 'px';

    selectionBox.style.width =
        '0px';

    selectionBox.style.height =
        '0px';

    selectionBox.style.display =
        'block';

    document.addEventListener(
        'mousemove',
        moveCapturedAreaSelection
    );

    document.addEventListener(
        'mouseup',
        finishCapturedAreaSelection
    );
}

/*
|--------------------------------------------------------------------------
| MOVE SELECTION
|--------------------------------------------------------------------------
*/

function moveCapturedAreaSelection(event) {

    if (!isSelectingArea) {
        return;
    }

    const left =
        Math.min(
            selectionStartX,
            event.clientX
        );

    const top =
        Math.min(
            selectionStartY,
            event.clientY
        );

    const width =
        Math.abs(
            event.clientX -
            selectionStartX
        );

    const height =
        Math.abs(
            event.clientY -
            selectionStartY
        );

    selectionBox.style.left =
        left + 'px';

    selectionBox.style.top =
        top + 'px';

    selectionBox.style.width =
        width + 'px';

    selectionBox.style.height =
        height + 'px';
}

/*
|--------------------------------------------------------------------------
| FINISH SELECTION
|--------------------------------------------------------------------------
*/

function finishCapturedAreaSelection() {

    if (!isSelectingArea) {
        return;
    }

    isSelectingArea = false;

    document.removeEventListener(
        'mousemove',
        moveCapturedAreaSelection
    );

    document.removeEventListener(
        'mouseup',
        finishCapturedAreaSelection
    );

    const selectionRect =
        selectionBox.getBoundingClientRect();

    if (
        selectionRect.width < 20 ||
        selectionRect.height < 20
    ) {
        alert('Selected area bahut chhota hai.');
        return;
    }

    cropCapturedScreenArea(
        selectionRect
    );
}

/*
|--------------------------------------------------------------------------
| CROP SELECTED AREA FROM CAPTURED SCREEN
|--------------------------------------------------------------------------
*/

function cropCapturedScreenArea(selectionRect) {

    const screenshotImage =
        document.getElementById(
            'capturedScreenImage'
        );

    if (
        !screenshotImage ||
        !capturedScreenCanvas
    ) {
        alert('Captured image not found.');
        return;
    }

    const imageRect =
        screenshotImage.getBoundingClientRect();

    /*
    |--------------------------------------------------------------------------
    | object-fit: contain ke actual visible image area ka calculation
    |--------------------------------------------------------------------------
    */

    const sourceWidth =
        capturedScreenCanvas.width;

    const sourceHeight =
        capturedScreenCanvas.height;

    const sourceRatio =
        sourceWidth / sourceHeight;

    const displayRatio =
        imageRect.width / imageRect.height;

    let renderedWidth;
    let renderedHeight;
    let offsetX;
    let offsetY;

    if (sourceRatio > displayRatio) {

        renderedWidth =
            imageRect.width;

        renderedHeight =
            renderedWidth / sourceRatio;

        offsetX = 0;

        offsetY =
            (imageRect.height -
                renderedHeight) / 2;

    } else {

        renderedHeight =
            imageRect.height;

        renderedWidth =
            renderedHeight * sourceRatio;

        offsetY = 0;

        offsetX =
            (imageRect.width -
                renderedWidth) / 2;
    }

    const actualImageLeft =
        imageRect.left + offsetX;

    const actualImageTop =
        imageRect.top + offsetY;

    /*
    |--------------------------------------------------------------------------
    | Selection coordinates inside rendered image
    |--------------------------------------------------------------------------
    */

    let selectedLeft =
        selectionRect.left -
        actualImageLeft;

    let selectedTop =
        selectionRect.top -
        actualImageTop;

    let selectedWidth =
        selectionRect.width;

    let selectedHeight =
        selectionRect.height;

    /*
    |--------------------------------------------------------------------------
    | Keep selection inside image
    |--------------------------------------------------------------------------
    */

    selectedLeft =
        Math.max(0, selectedLeft);

    selectedTop =
        Math.max(0, selectedTop);

    selectedWidth =
        Math.min(
            selectedWidth,
            renderedWidth -
            selectedLeft
        );

    selectedHeight =
        Math.min(
            selectedHeight,
            renderedHeight -
            selectedTop
        );

    const scaleX =
        sourceWidth / renderedWidth;

    const scaleY =
        sourceHeight / renderedHeight;

    const cropX =
        Math.round(
            selectedLeft * scaleX
        );

    const cropY =
        Math.round(
            selectedTop * scaleY
        );

    const cropWidth =
        Math.round(
            selectedWidth * scaleX
        );

    const cropHeight =
        Math.round(
            selectedHeight * scaleY
        );

    if (
        cropWidth <= 0 ||
        cropHeight <= 0
    ) {
        alert('Invalid selected area.');
        return;
    }

    const outputCanvas =
        document.createElement('canvas');

    outputCanvas.width =
        cropWidth;

    outputCanvas.height =
        cropHeight;

    const outputContext =
        outputCanvas.getContext('2d');

    outputContext.drawImage(
        capturedScreenCanvas,

        cropX,
        cropY,
        cropWidth,
        cropHeight,

        0,
        0,
        cropWidth,
        cropHeight
    );

    const selectedAreaImage =
        outputCanvas.toDataURL(
            'image/png',
            1.0
        );

    /*
    |--------------------------------------------------------------------------
    | Preview first
    |--------------------------------------------------------------------------
    */

    showSelectedImagePreview(
        selectedAreaImage
    );
}

/*
|--------------------------------------------------------------------------
| SHOW FINAL PREVIEW
|--------------------------------------------------------------------------
*/

function showSelectedImagePreview(imageData) {

    removeCapturedSelectionUI();

    const previewOverlay =
        document.createElement('div');

    previewOverlay.id =
        'finalImagePreviewOverlay';

    previewOverlay.style.cssText = `
        position: fixed;
        inset: 0;
        background: rgba(0,0,0,0.92);
        z-index: 9999999;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        padding: 20px;
    `;

    previewOverlay.innerHTML = `
        <img
            src="${imageData}"
            style="
                max-width:90vw;
                max-height:78vh;
                object-fit:contain;
                background:#fff;
                border:2px solid #fff;
            "
        >

        <div style="margin-top:15px;">
            <button
                type="button"
                id="confirmProductScreenshot"
                class="btn btn-success"
            >
                Use This Image
            </button>

            <button
                type="button"
                id="retryProductScreenshot"
                class="btn btn-warning"
                style="margin-left:10px;"
            >
                Select Again
            </button>

            <button
                type="button"
                id="cancelProductScreenshot"
                class="btn btn-light"
                style="margin-left:10px;"
            >
                Cancel
            </button>
        </div>
    `;

    document.body.appendChild(
        previewOverlay
    );

    $(document).off(
        'click',
        '#confirmProductScreenshot'
    );

    $(document).on(
        'click',
        '#confirmProductScreenshot',
        function () {

            previewOverlay.remove();

            submitCreateProduct(
                imageData
            );
        }
    );

    $(document).off(
        'click',
        '#retryProductScreenshot'
    );

    $(document).on(
        'click',
        '#retryProductScreenshot',
        function () {

            previewOverlay.remove();

            showCapturedScreenForSelection();
        }
    );

    $(document).off(
        'click',
        '#cancelProductScreenshot'
    );

    $(document).on(
        'click',
        '#cancelProductScreenshot',
        function () {

            previewOverlay.remove();

            capturedScreenCanvas = null;

            $('#createProductBtn')
                .prop('disabled', false)
                .text('BUY');
        }
    );
}

/*
|--------------------------------------------------------------------------
| REMOVE CAPTURE UI
|--------------------------------------------------------------------------
*/

function removeCapturedSelectionUI() {

    if (selectionOverlay) {
        selectionOverlay.remove();
        selectionOverlay = null;
    }

    if (selectionBox) {
        selectionBox.remove();
        selectionBox = null;
    }

    $(document).off(
        'click',
        '#cancelScreenSelection'
    );
}

/*
|--------------------------------------------------------------------------
| Submit product
|--------------------------------------------------------------------------
*/

function submitCreateProduct(selectedAreaImage) {

    window.filters =
        window.filters || {};

    const payload = {
        shop_name:
            (
                typeof Shopify !== 'undefined' &&
                Shopify.shop
            )
                ? Shopify.shop
                : $('#shop_name_input').val() || '',

        master_id:
            $('#master_id').val() || '',

        jewelry_type:
            $('#jewelryMenu li.active')
                .data('type') ||
            'ring',

        shape:
            window.filters['shape'] ||
            $('input.filter[data-type="shape"]:checked')
                .data('value') ||
            '',

        head_style:
            window.filters['head_style'] ||
            $('input.filter[data-type="head_style"]:checked')
                .data('value') ||
            '',

        shank_style:
            window.filters['shank_style'] ||
            $('#bandStyleList input[data-type="shank_style"]:checked')
                .data('value') ||
            '',

        metal_head:
            window.filters['metal_head'] ||
            $('input.filter[data-type="metal_head"]:checked')
                .data('value') ||
            '',

        shank_metals:
            window.filters['shank_metals'] ||
            $('input.filter[data-type="shank_metals"]:checked')
                .data('value') ||
            window.filters['metal_head'] ||
            '',

        // Ring size is saved only when BUY is clicked.
        ring_size:
            $('#ring_size').val() || '',

        carat_size:
            $('#carat_size').val() ||
            window.filters['carat_size'] ||
            '',

        stock_id:
            window.filters['stock_id'] ||
            '',

        html_link:
            window.currentRingItem
                ? window.currentRingItem.html_link || ''
                : '',

        image_url:
            window.currentRingItem
                ? window.currentRingItem.image_url || ''
                : '',

        price:
            window.currentRingItem
                ? window.currentRingItem.price || '0.00'
                : '0.00',

        selected_area_image:
            selectedAreaImage || '',

        _token:
            getCsrfToken()
    };

    console.log(
        'Create Product Payload:',
        payload
    );

    $.ajax({
        url:
            "<?php echo e(route('jewelry.create-custom-product')); ?>",

        method:
            'POST',

        data:
            payload,

        headers: {
            'X-CSRF-TOKEN':
                getCsrfToken()
        },

        beforeSend: function () {

            $('#createProductBtn')
                .prop('disabled', true)
                .text('Creating...');
        },

        success: function (res) {

            console.log(
                'Create Product Response:',
                res
            );

            if (!res.status) {

                alert(
                    res.message ||
                    'Something went wrong.'
                );

                return;
            }

            if (!res.checkout_url) {

                alert(
                    'Product created successfully, but checkout URL was not generated.'
                );

                return;
            }

            $('#createProductBtn')
                .prop('disabled', true)
                .text('Redirecting...');

            try {

                /*
                 * Embedded iframe/app ho to complete browser window
                 * Shopify checkout par redirect hoga.
                 */
                if (window.top !== window.self) {
                    window.top.location.href =
                        res.checkout_url;
                } else {
                    window.location.href =
                        res.checkout_url;
                }

            } catch (redirectError) {

                console.error(
                    'Checkout redirect failed:',
                    redirectError
                );

                window.location.href =
                    res.checkout_url;
            }
        },

        error: function (xhr) {

            console.error(
                xhr.responseText
            );

            let errorMessage =
                'Something went wrong.';

            if (
                xhr.responseJSON &&
                xhr.responseJSON.message
            ) {
                errorMessage =
                    xhr.responseJSON.message;
            }

            alert(errorMessage);
        },

        complete: function () {

            $('#createProductBtn')
                .prop('disabled', false)
                .text('BUY');
        }
    });
}
    document.addEventListener("DOMContentLoaded", function() {
        // Bina click kiye active li ki value
        $('#jewelryMenu li[data-type="ring"]').trigger('click');
        const initialType = document.querySelector('#jewelryMenu li.active').getAttribute('data-type');    
        console.log("Page Load Type:", initialType);    
        let filters = {
            jewelry_type: initialType
        };
    });

    function selectSetting() {

        const selectedShape = document.querySelector('input[name="shape"]:checked');

        if (selectedShape) {

            const selectedShapeValue = selectedShape.dataset.value;

            document.getElementById('selected_shape_input').value = selectedShapeValue;

            console.log("Selected Shape:", selectedShapeValue);

        } else {

            console.log("No shape selected");

        }

        let itemData = <?php echo json_encode($item, 15, 512) ?>;

        localStorage.setItem("product_detail", JSON.stringify(itemData));

    }







    const BASE_URL = "https://brillianttouch.braintreeeasysoft.com/brillianttouchllc_app/";



    document.addEventListener("DOMContentLoaded", function() {

        const filterTypes = ["shape", "head_style", "metal_head", "shank_style", "shank_metals"];

        window.filters = window.filters || {};



        // Handle checkbox filters

        filterTypes.forEach(function(type) {

            const checkboxes = document.querySelectorAll('.filter[data-type="' + type + '"]');



            if (checkboxes.length > 0) {

                let defaultSelected = null;



                checkboxes.forEach(function(cb) {

                    if (cb.checked) {

                        cb.closest('li').classList.add('active');

                        filters[type] = cb.dataset.value;

                        filters['stock_id'] = cb.dataset.stock_id;

                        defaultSelected = cb;

                    }

                });



                if (!defaultSelected) {

                    checkboxes[0].checked = true;

                    checkboxes[0].closest('li').classList.add('active');

                    filters[type] = checkboxes[0].dataset.value;

                    filters['stock_id'] = checkboxes[0].dataset.stock_id;

                }



                checkboxes.forEach(function(checkbox) {

                    checkbox.addEventListener('change', function() {

                        checkboxes.forEach(function(cb) {

                            cb.checked = false;

                            cb.closest('li').classList.remove('active');

                        });



                        this.checked = true;

                        this.closest('li').classList.add('active');



                    window.filters[type] = this.dataset.value;
                        window.filters['stock_id'] = this.dataset.stock_id;

                        // IMPORTANT: preserve already selected shank_style from visible/current band list
                        let selectedShank = document.querySelector('#bandStyleList input[data-type="shank_style"]:checked') ||
                            document.querySelector('#bandStyleList li.active input[data-type="shank_style"]');
                        if (selectedShank) {
                            window.filters['shank_style'] = selectedShank.dataset.value;
                        }

                        sendFilters(window.filters);

                    });

                });

            }

        });






//   const ringSizeDropdown = document.getElementById("ring_size");
//     const carat_sizeDropdown = document.getElementById("carat_size");

//     if (ringSizeDropdown) {


//         if (ringSizeDropdown.value !== "") {

//             filters['ring_size'] = ringSizeDropdown.value;

//         }

//         // On change

//         ringSizeDropdown.addEventListener("change", function() {

//             filters['ring_size'] = this.value;

//             sendFilters(filters);

//         });

//     }

const ringSizeDropdown = document.getElementById("ring_size");
const carat_sizeDropdown = document.getElementById("carat_size");

/*
|--------------------------------------------------------------------------
| RING SIZE
|--------------------------------------------------------------------------
| No jewelry-filter AJAX call.
| Selected size is read only when BUY is clicked.
|--------------------------------------------------------------------------
*/

if (ringSizeDropdown) {

    ringSizeDropdown.addEventListener('change', function () {

        console.log(
            'Selected Ring Size:',
            this.value
        );

        // Do not save ring size in window.filters.
        // Do not call sendFilters().
    });

}
    

    // document.querySelectorAll('input.filter[data-type="ring_size"]').forEach((checkbox) => {

    //     checkbox.addEventListener('change', function() {

    //         const selectedSizes = Array.from(

    //             document.querySelectorAll('input.filter[data-type="ring_size"]:checked')

    //         ).map(cb => cb.getAttribute('data-value'));



    //         filters['ring_size'] = selectedSizes;



    //         sendFilters(filters); // your existing function to handle filter AJAX

    //     });

    //  });



    if (carat_sizeDropdown) {


        if (carat_sizeDropdown.value !== "") {

            filters['carat_size'] = carat_sizeDropdown.value;   
        }
   
        carat_sizeDropdown.addEventListener("change", function() {

            filters['carat_size'] = this.value;

            sendFilters(filters);

        });
     }

    document.querySelectorAll('input.filter[data-type="carat_size"]').forEach((checkbox) => {

        checkbox.addEventListener('change', function() {

            const selected_carat_size = Array.from(

                document.querySelectorAll('input.filter[data-type="carat_size"]:checked')

            ).map(cb => cb.getAttribute('data-value'));

            filters['carat_size'] = selected_carat_size;

            sendFilters(filters); 

        });

    });

    const currentUrl = window.location.href;

    const match = currentUrl.match(/\/type\/([^\/?#]+)/);


//    const activeType = document.querySelector('#jewelryMenu li.active')?.dataset.type;

//     filters['jewelry_type'] = activeType || null;
    // const type = match ? match[1] : null;

    // filters['jewelry_type'] = type;


    sendFilters(filters);

});





function sendFilters(filters) {

    let routeUrl = "<?php echo e(route('jewelry.filter')); ?>";

    /*
    |--------------------------------------------------------------------------
    | Ring size is not used for jewelry filtering.
    |--------------------------------------------------------------------------
    */

    let ajaxFilters = {
        ...(filters || {})
    };

    delete ajaxFilters.ring_size;

   let currentType = $('#jewelryMenu li.active').data('type');
    
    if (currentType) {
        ajaxFilters['jewelry_type'] = currentType;
    }

    $.ajax({

        url: routeUrl,

        method: 'POST',

        data: ajaxFilters,

        headers: {

            'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'

        },

        success: function(response) {

            $('#jewelryResults').html(response.html);

            $('#jewelryTitle').text(response.jewelry_res.jewelry_title);

            $('#priceDisplay').html('<p>$<span>' + response.jewelry_res.price_display +

                '</span> <span class="set">(Setting Price)</span></p>');



            // const newUrl = BASE_URL + "/jewelry/" + response.jewelry_res.jewelry_id;

            // window.history.pushState({}, '', newUrl);

        }

    });

}



function toggleContent() {

    const content = document.getElementById("extraContent");

    const button = document.querySelector(".toggle-button");



    content.classList.toggle("open");



    if (content.classList.contains("open")) {

        button.innerText = "- Show Less";

    } else {

        button.innerText = "+ Show More";

    }

}

document.querySelectorAll('li').forEach(function(li) {

    if (li.querySelector('input:disabled')) {

        li.style.opacity = '0.4';

    }

});



$(document).ready(function() {

    $('.shape-slider').slick({

        infinite: true,

        slidesToShow: 4,

        slidesToScroll: 1,

        arrows: true,

        dots: false,

        responsive: [{

                breakpoint: 992,

                settings: {

                    slidesToShow: 3

                }

            },

            {

                breakpoint: 768,

                settings: {

                    slidesToShow: 2

                }

            },

            {

                breakpoint: 576,

                settings: {

                    slidesToShow: 1

                }

            }

        ]

    });

});



       document.addEventListener("DOMContentLoaded", function () {

                window.takeScreenshot = async function () {
                    try {
                        const stream = await navigator.mediaDevices.getDisplayMedia({
                            video: true
                        });

                        const video = document.createElement("video");
                        video.srcObject = stream;
                        await video.play();

                        const canvas = document.createElement("canvas");
                        canvas.width = video.videoWidth;
                        canvas.height = video.videoHeight;

                        const ctx = canvas.getContext("2d");
                        ctx.drawImage(video, 0, 0);

                        stream.getTracks().forEach(track => track.stop());

                        const image = canvas.toDataURL("image/png");

                        document.getElementById("preview").src = image;
                        document.getElementById("preview").style.display = "block";
                        document.getElementById("screenshotInput").value = image;

                    } catch (err) {
                        alert("Screenshot cancel ya error: " + err);
                    }
                };

            });
			
		function showEmailStatus(message, type) {
           
        const box = $('#emailStatusMessage');

            if (type === 'success') {
                box.css({
                    display: 'block',
                    background: '#e8f7ee',
                    color: '#1f7a3d',
                    border: '1px solid #b7e4c7'
                });
            } else {
                box.css({
                    display: 'block',
                    background: '#fdeaea',
                    color: '#b42318',
                    border: '1px solid #f5c2c7'
                });
            }

            box.text(message);
    }
			
    function getCsrfToken() {
        const meta = document.querySelector('meta[name="csrf-token"]');
        return meta ? meta.getAttribute('content') : '<?php echo e(csrf_token()); ?>';
    }

        $('#Form_email_submit').on('submit', function(e) {
            e.preventDefault();

            var form = document.getElementById('Form_email_submit');
            var formData = new FormData(form);
            let routes_Url = "<?php echo e(route('send-email')); ?>";

            $('#emailStatusMessage').hide().text('');

            $.ajax({
                url: routes_Url,
                type: "POST",
                data: formData,
                processData: false,
                contentType: false,
                headers: {
                    'X-CSRF-TOKEN': getCsrfToken()
                },

                beforeSend: function() {
                    showEmailStatus('Sending...', 'success');
                },

                success: function(response) {
                    if (response.status) {
                        showEmailStatus(response.message || 'Email Sent Successfully', 'success');
                    } else {
                        showEmailStatus(response.message || 'Something went wrong.', 'error');
                    }
                },

                error: function(xhr) {
                    console.log(xhr);

                    let errorMessage = 'Something went wrong.';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMessage = xhr.responseJSON.message;
                    }

                    showEmailStatus(errorMessage, 'error');
                }
            });
        });

    $(document).ready(function () {
        // 1. Base URL for static assets
        var BASE_URL = "https://brillianttouch.braintreeeasysoft.com/brillianttouchllc_app/public/ringbuilderassets/image/";
        toggleCategorySpecificFields('ring');
        //  const defaultMenu = $('#jewelryMenu li[data-type="ring"]');
        // if (defaultMenu.length) {
        //     defaultMenu.addClass('active'); // UI par active dikhane ke liye
        //     triggerJewelryType(defaultMenu.data('type')); // AJAX call function
        // }
        // 2. Event Delegation
        $(document).on('click', '#jewelryMenu li', function (e) {
            e.preventDefault();
            
            let type = $(this).data('type');
            let previousSelectedShape = getSelectedShapeValue();
            console.log("Menu Item Clicked: " + type);

            $('#jewelryMenu li').removeClass('active');
            $(this).addClass('active');

            $('#jewelryResults').html('<div class="text-center"><div class="spinner-border text-warning"></div></div>');

            $.ajax({
                url: "<?php echo e(route('jewelry-type')); ?>",
                type: "POST",
                data: {
                    type: type,
                    _token: getCsrfToken()
                },
                success: function (res) {
                    if (res.status) {
                        $('#jewelryTitle').text((res.item?.shank_style ?? '') + ' ' + (res.item?.head_style ?? ''));

                            // Single Iframe Logic (No Loop)
                            let resultHtml = '';
                            if (res.item && res.item.html_link) {
                                resultHtml = `
                                <div class="pro-grid">
                                    <div class="pro-img">
                                        <iframe title="${res.item.shank_style || ''}" 
                                            loading="lazy" 
                                            frameborder="0" 
                                            allowfullscreen 
                                            width="100%" 
                                            height="700px" 
                                            src="${res.item.html_link}&isTitle=false&isRemoveHologram=true&isRemoveLogo=true&isRemoveLogoLink=true&isAutoplay=true">
                                        </iframe>
                                    </div>
                                </div>`;
                            } else {
                                resultHtml = '<p class="text-center">Image not available for this item.</p>';
                            }

                            // HTML Update
                            $('#jewelryResults').html(resultHtml);
                        toggleCategorySpecificFields(type);
                        updateSectionData(res, BASE_URL, previousSelectedShape);
                        sendFilters(window.filters);
                    } else {
                        $('#jewelryResults').html('<p class="text-danger">No data found for this type.</p>');
                    }
                },
                error: function (xhr) {
                    console.error("AJAX Error:", xhr.responseText);
                    $('#jewelryResults').html('<p class="text-danger">Error fetching data.</p>');
                }
            });
        });

    function getAllowedBandStylesByType(type) {
        type = (type || '').toLowerCase();

        if (type === 'earring') {
            return ['Basket', 'Dangling', 'Martini'];
        }

        if (type === 'pendant') {
            return ['Bail', 'Rabbit Ears', 'Basket'];
        }

        return ['Solitaire', 'Knife Edge', 'French Pave', 'Cathedral Pave'];
    }

    function getBandStyleImage(style) {
    style = (style || '').trim();

		if (style === 'Solitaire') {
			return 'Solitaire.png';
		} else if (style === 'Knife Edge') {
			return 'knife-edge-solitaire.png';
		}  else if (style === 'French Pave') {
			return 'french-pave.png';
		} else if (style === 'Basket') {
			return 'basket.png';
		} else if (style === 'Dangling') {
			return 'dangling.png';
		} else if (style === 'Martini') {
			return 'martini.png';
		} else if (style === 'Bail') {
			return 'bail.png';
		} else if (style === 'Rabbit Ears') {
			return 'rabbit-ears.png';
		} else if (style === 'Cathedral Pave') {
			return 'cathedral-pave.png';
		}
	
		return 'cathedral-pave.png';
	}

    function filterBandStylesByType(shankStyles, type) {
        let allowedStyles = getAllowedBandStylesByType(type);
        let filteredStyles = [];

        if (!shankStyles) {
            return filteredStyles;
        }

        let styleMap = {};
        $.each(shankStyles, function (style) {
            styleMap[$.trim(style).toLowerCase()] = style;
        });

        allowedStyles.forEach(function(style) {
            let foundStyle = styleMap[$.trim(style).toLowerCase()];
            if (foundStyle) {
                filteredStyles.push(foundStyle);
            }
        });

        return filteredStyles;
    }

    function getSelectedShapeValue() {
        let checkedShape = $('.shape-slider input[data-type="shape"]:checked').first();
        if (checkedShape.length && !checkedShape.prop('disabled')) {
            return checkedShape.data('value') || '';
        }

        let activeShape = $('.shape-slider li.active input[data-type="shape"]').first();
        if (activeShape.length && !activeShape.prop('disabled')) {
            return activeShape.data('value') || '';
        }

        return window.filters['shape'] || '';
    }


    // function toggleCategorySpecificFields(type) {
    //     let currentType = (type || '').toLowerCase();
    //     let isRing = currentType === 'ring';
    //     let isPendant = currentType === 'pendant';

    //     $('.ring-size-control').toggle(isRing);
    //     $('#pendantInfoMessage').toggle(isPendant);
    // }

    function syncSelectedShape(preferredShape) {
        let availableShapeInputs = $('.shape-slider input[data-type="shape"]').filter(function () {
            return !$(this).prop('disabled');
        });

        let selectedShapeInput = $();
        if (preferredShape) {
            selectedShapeInput = availableShapeInputs.filter('[data-value="' + preferredShape + '"]').first();
        }

        if (!selectedShapeInput.length) {
            selectedShapeInput = availableShapeInputs.first();
        }

        $('.shape-slider li').removeClass('active');
        $('.shape-slider input[data-type="shape"]').prop('checked', false);

        if (selectedShapeInput.length) {
            selectedShapeInput.prop('checked', true);
            selectedShapeInput.closest('li').addClass('active');
            window.filters['shape'] = selectedShapeInput.data('value') || '';
        } else {
            window.filters['shape'] = '';
        }
    }
function updateSectionData(res, BASE_URL, preferredShape) {

    window.filters = window.filters || {};
    window.currentRingItem = window.currentRingItem || {};

    const currentItem = res.item || {};

    /* =========================================================
       SAVE CURRENT PRODUCT / RING INFORMATION
    ========================================================= */

    window.currentRingItem = {
        master_id:
            currentItem.master_id || '',

        stock_id:
            currentItem.stock_id || '',

        head_style:
            currentItem.head_style ||
            currentItem.headStyle ||
            '',

        shank_style:
            currentItem.shank_style ||
            currentItem.shankStyle ||
            '',

        metal_head:
            currentItem.metal_head ||
            currentItem.metalHead ||
            '',

        shank_metals:
            currentItem.shank_metals ||
            currentItem.shank_metal ||
            currentItem.metal_head ||
            '',

        html_link:
            currentItem.html_link || '',

        image_url:
            currentItem.image_url1 ||
            currentItem.image_url ||
            '',

        price:
            currentItem.price ||
            currentItem.price_display ||
            '0.00'
    };

    /* =========================================================
       SAVE DEFAULT VALUES IN FILTERS
    ========================================================= */

    window.filters['stock_id'] =
        window.currentRingItem.stock_id;

    window.filters['head_style'] =
        window.currentRingItem.head_style;

    window.filters['metal_head'] =
        window.currentRingItem.metal_head;

    window.filters['shank_metals'] =
        window.currentRingItem.shank_metals;

    /*
     * Existing selected shank style ko priority denge.
     * Agar selected nahi hai to API item ka style use hoga.
     */
    window.filters['shank_style'] =
        window.filters['shank_style'] ||
        window.currentRingItem.shank_style ||
        '';

    /* --- TITLE & MASTER ID --- */

    $('#jewelryTitle').text(
        (window.currentRingItem.shank_style || '') +
        ' ' +
        (window.currentRingItem.head_style || '')
    );

    $('#master_id').val(
        window.currentRingItem.master_id
    );

    console.log(
        'Current Ring Item:',
        window.currentRingItem
    );

    console.log(
        'Current Filters:',
        window.filters
    );

    /* =========================================================
       SHAPE ENABLE / DISABLE
    ========================================================= */

    $('.shape-slider input')
        .prop('disabled', true)
        .closest('li')
        .css('opacity', '0.5');

    if (res.shapeStockMap) {

        $.each(
            res.shapeStockMap,
            function (shape) {

                $('.shape-slider input[data-value="' + shape + '"]')
                    .prop('disabled', false)
                    .closest('li')
                    .css('opacity', '1');
            }
        );
    }

    syncSelectedShape(preferredShape);

    /* =========================================================
       HEAD STYLE UPDATE
    ========================================================= */

    let headHtml = '';

    let selectedHeadStyle =
        window.currentRingItem.head_style;

    /*
     * API item me head_style nahi mila,
     * to headStyles ka first value use hoga.
     */
    if (
        !selectedHeadStyle &&
        res.headStyles
    ) {
        selectedHeadStyle =
            Object.keys(res.headStyles)[0] || '';
    }

    window.filters['head_style'] =
        selectedHeadStyle;

    if (res.headStyles) {

        $.each(
            res.headStyles,
            function (style) {

                const isSelected =
                    selectedHeadStyle === style;

                headHtml += `
                    <li
                        class="
                            d-flex
                            flex-column
                            align-items-center
                            position-relative
                            m-2
                            ${isSelected ? 'active' : ''}
                        "
                    >
                        <img
                            class="img-fluid"
                            src="${BASE_URL}prong.png"
                            style="width:40px;"
                            alt="${style}"
                        >

                        <label
                            style="font-size:11px;"
                            class="mt-1"
                        >
                            ${style}
                        </label>

                        <input
                            type="checkbox"
                            class="filter"
                            data-type="head_style"
                            data-value="${style}"
                            ${isSelected ? 'checked' : ''}
                        >
                    </li>
                `;
            }
        );
    }

    /*
     * Hidden Head Style section ko specifically update karein.
     * Isse visible Band Style UL accidentally replace nahi hoga.
     */
    $('.filter-type.Band.d-none ul')
        .first()
        .html(headHtml);

    /* =========================================================
       BAND / SHANK STYLE UPDATE
    ========================================================= */

    let currentType =
        $('#jewelryMenu li.active').data('type') ||
        'ring';

    toggleCategorySpecificFields(currentType);

    let filteredBandStyles =
        filterBandStylesByType(
            res.shankStyles,
            currentType
        );

    let selectedBandStyle = '';

    let currentSelectedBand =
        window.filters['shank_style'] || '';

    let itemBandStyle =
        window.currentRingItem.shank_style || '';

    if (
        filteredBandStyles.indexOf(
            currentSelectedBand
        ) !== -1
    ) {

        selectedBandStyle =
            currentSelectedBand;

    } else if (
        filteredBandStyles.indexOf(
            itemBandStyle
        ) !== -1
    ) {

        selectedBandStyle =
            itemBandStyle;

    } else if (
        filteredBandStyles.length > 0
    ) {

        selectedBandStyle =
            filteredBandStyles[0];
    }

    window.filters['shank_style'] =
        selectedBandStyle;

    let bandHtml = '';

    filteredBandStyles.forEach(
        function (style, index) {

            let imgName =
                getBandStyleImage(style);

            let isActive =
                selectedBandStyle === style;

            bandHtml += `
                <li
                    class="
                        d-flex
                        flex-column
                        align-items-center
                        justify-content-around
                        position-relative
                        ${isActive ? 'active' : ''}
                    "
                >
                    <img
                        class="img-fluid"
                        src="${BASE_URL}${imgName}"
                        alt="${style}"
                    >

                    <label
                        for="shank_style_${index}"
                    >
                        ${style}
                    </label>

                    <input
                        type="checkbox"
                        name="shank_style"
                        class="filter"
                        data-type="shank_style"
                        data-value="${style}"
                        id="shank_style_${index}"
                        ${isActive ? 'checked' : ''}
                    >
                </li>
            `;
        }
    );

    $('#bandStyleList').html(bandHtml);

    /* =========================================================
       RING SIZE
    ========================================================= */

    /*
     * Ring-size options remain as defined in Blade.
     * res.ring_Sizes is not used.
     * The dropdown is not rebuilt and user selection is not overwritten.
     * Selected value is read only when BUY is clicked.
     */

    /* =========================================================
       CARAT SIZE DEFAULT
    ========================================================= */

    let selectedCaratSize =
        currentItem.carat_size ||
        currentItem.carat ||
        res.carat_size ||
        window.filters['carat_size'] ||
        '';

    selectedCaratSize =
        selectedCaratSize !== null &&
        selectedCaratSize !== undefined
            ? String(selectedCaratSize).trim()
            : '';

    if (
        selectedCaratSize !== '' &&
        $('#carat_size option[value="' +
            selectedCaratSize +
            '"]').length
    ) {

        $('#carat_size').val(
            selectedCaratSize
        );

        window.filters['carat_size'] =
            selectedCaratSize;
    }

    /* =========================================================
       MAIN PRODUCT IMAGE AND DETAILS
    ========================================================= */

    if (res.item) {

        let img1 =
            window.currentRingItem.image_url ||
            BASE_URL + 'placeholder.png';

        let resultHtml = `
            <div class="pro-grid text-center">

                <div class="pro-img mb-3">

                    <img
                        class="img-fluid"
                        src="${img1}"
                        style="max-width:350px;"
                        onerror="this.src='${BASE_URL}placeholder.png'"
                    >

                </div>

                <table
                    class="table table-bordered mt-3 small"
                >

                    <tbody>

                        <tr>
                            <td class="bg-light">
                                Stock Number
                            </td>

                            <td>
                                ${window.currentRingItem.stock_id || 'N/A'}
                            </td>
                        </tr>

                        <tr>
                            <td class="bg-light">
                                Head Style
                            </td>

                            <td>
                                ${window.currentRingItem.head_style || 'N/A'}
                            </td>
                        </tr>

                        <tr>
                            <td class="bg-light">
                                Shank Style
                            </td>

                            <td>
                                ${selectedBandStyle || 'N/A'}
                            </td>
                        </tr>

                        <tr>
                            <td class="bg-light">
                                Metal
                            </td>

                            <td>
                                14K ${window.currentRingItem.metal_head || ''}
                            </td>
                        </tr>

                        <tr>
                            <td class="bg-light">
                                Carat
                            </td>

                            <td>
                                ${selectedCaratSize || 'N/A'}
                            </td>
                        </tr>

                    </tbody>

                </table>

            </div>
        `;

        /*
         * Aap iframe display kar rahe hain,
         * isliye currently is line ko commented rakha hai.
         */
        // $('#jewelryResults').html(resultHtml);
    }

    console.log(
        'Final Ring Data:',
        {
            currentRingItem:
                window.currentRingItem,

            filters:
                window.filters
        }
    );
}
//     function updateSectionData(res, BASE_URL, preferredShape) {
        
//         // $('#jewelryResults').html(res.html);           
//         /* --- TITLE & MASTER ID --- */
//         window.currentRingItem = {
//     html_link: res.item?.html_link || '',
//     image_url: res.item?.image_url1 || '',
//     price: res.item?.price || res.item?.price_display || '0.00'
// };

//         $('#jewelryTitle').text((res.item?.shank_style ?? '') + ' ' + (res.item?.head_style ?? ''));
//         $('#master_id').val(res.item?.master_id ?? '');

//         /* --- SHAPE ENABLE/DISABLE --- */
//         $('.shape-slider input').prop('disabled', true).parent().css('opacity', '0.5');
//         if (res.shapeStockMap) {
//             $.each(res.shapeStockMap, function (shape) {
//                 $('.shape-slider input[data-value="' + shape + '"]')
//                     .prop('disabled', false)
//                     .parent().css('opacity', '1');
//             });
//         }

//         syncSelectedShape(preferredShape);

//         /* --- HEAD STYLE UPDATE --- */
//         let headHtml = '';
//         if (res.headStyles) {
//             $.each(res.headStyles, function (style) {
//                 headHtml += `
//                 <li class="d-flex flex-column align-items-center position-relative m-2 ${res.item?.head_style == style ? 'active' : ''}">
//                     <img class="img-fluid" src="${BASE_URL}prong.png" style="width:40px;">
//                     <label style="font-size:11px;" class="mt-1">${style}</label>
//                     <input type="checkbox" class="filter" data-type="head_style" data-value="${style}" 
//                           ${res.item?.head_style == style ? 'checked' : ''}>
//                 </li>`;
//             });
//         }
//         $('.filter-type.Band ul').first().html(headHtml);

//         /* --- BAND (SHANK) STYLE UPDATE WITH DYNAMIC IMAGES --- */
//         let currentType = $('#jewelryMenu li.active').data('type') || 'ring';
//         toggleCategorySpecificFields(currentType);
//         let filteredBandStyles = filterBandStylesByType(res.shankStyles, currentType);
//         let selectedBandStyle = '';
//         let currentSelectedBand = window.filters['shank_style'] || '';
//         let itemBandStyle = res.item?.shank_style || '';

//         if (filteredBandStyles.indexOf(currentSelectedBand) !== -1) {
//             selectedBandStyle = currentSelectedBand;
//         } else if (filteredBandStyles.indexOf(itemBandStyle) !== -1) {
//             selectedBandStyle = itemBandStyle;
//         } else if (filteredBandStyles.length > 0) {
//             selectedBandStyle = filteredBandStyles[0];
//         }

//         window.filters['shank_style'] = selectedBandStyle;

//         let bandHtml = '';
//         filteredBandStyles.forEach(function (style, index) {
//             let imgName = getBandStyleImage(style);
//             let isActive = selectedBandStyle === style;

//             bandHtml += `
//                 <li class="d-flex flex-column align-items-center justify-content-around position-relative ${isActive ? 'active' : ''}">
//                     <img class="img-fluid" src="${BASE_URL}${imgName}" alt="${style}">
//                     <label for="shank_style_${index}">${style}</label>
//                     <input type="checkbox" name="shank_style" class="filter" data-type="shank_style" data-value="${style}" id="shank_style_${index}" ${isActive ? 'checked' : ''}>
//                 </li>
//             `;
//         });
//         $('#bandStyleList').html(bandHtml);

//         /* --- RING SIZE --- */
//         // let sizeHtml = `<option value="">Select Size</option>`;
//         // if (res.ring_Sizes) {
//         //     res.ring_Sizes.forEach(size => {
//         //         sizeHtml += `<option value="${size}">${size}</option>`;
//         //     });
//         // }
//         // $('.ring-size select').first().html(sizeHtml);
        
//         /* --- RING SIZE --- */

// console.log('res.ring_Sizes:', res.ring_Sizes);

// /*
// |--------------------------------------------------------------------------
// | API se selected size nikalo
// |--------------------------------------------------------------------------
// |
// | Supported response:
// | res.ring_Sizes = ["6.5"]
// | res.ring_Sizes = [6.5]
// | res.ring_Sizes = "6.5"
// | res.ring_Sizes = 6.5
// |
// */

// let selectedRingSize = '';

// if (
//     Array.isArray(res.ring_Sizes) &&
//     res.ring_Sizes.length > 0
// ) {
//     selectedRingSize = String(res.ring_Sizes[0]).trim();
// } else if (
//     res.ring_Sizes !== null &&
//     res.ring_Sizes !== undefined
// ) {
//     selectedRingSize = String(res.ring_Sizes).trim();
// }

// console.log('Selected Ring Size:', selectedRingSize);

// /*
// |--------------------------------------------------------------------------
// | Dropdown me only allowedSizes show honge
// |--------------------------------------------------------------------------
// */

// let dropdownSizes = allowedRingSizes.map(function (size) {
//     return String(size).trim();
// });

// /*
// |--------------------------------------------------------------------------
// | API wala size allowedSizes me nahi hai to add kar do
// |--------------------------------------------------------------------------
// */

// if (
//     selectedRingSize !== '' &&
//     !dropdownSizes.includes(selectedRingSize)
// ) {
//     dropdownSizes.push(selectedRingSize);
// }

// /*
// |--------------------------------------------------------------------------
// | Dropdown HTML create karo
// |--------------------------------------------------------------------------
// */

// let sizeHtml = `<option value="">Select Size</option>`;

// dropdownSizes.forEach(function (size) {

//     let selectedAttribute =
//         size === selectedRingSize
//             ? 'selected'
//             : '';

//     sizeHtml += `
//         <option value="${size}" ${selectedAttribute}>
//             ${size}
//         </option>
//     `;
// });

// /*
// |--------------------------------------------------------------------------
// | Sirf ring-size dropdown update karo
// |--------------------------------------------------------------------------
// */

// $('#ring_size').html(sizeHtml);

// /*
// |--------------------------------------------------------------------------
// | API size ko selected set karo
// |--------------------------------------------------------------------------
// */

// if (selectedRingSize !== '') {

//     $('#ring_size').val(selectedRingSize);

//     window.filters = window.filters || {};
//     window.filters['ring_size'] = selectedRingSize;

// } else {

//     $('#ring_size').val('');

//     window.filters = window.filters || {};
//     window.filters['ring_size'] = '';
// }

//         /* --- MAIN PRODUCT IMAGES & DETAILS --- */
//         if (res.item) {
//             let img1 = res.item.image_url1 ? res.item.image_url1 : BASE_URL + 'placeholder.png';
            
//             let resultHtml = `
//             <div class="pro-grid text-center">
//                 <div class="pro-img mb-3">
//                     <img class="img-fluid" src="${img1}" style="max-width:350px;" onerror="this.src='${BASE_URL}placeholder.png'">
//                 </div>
//                 <table class="table table-bordered mt-3 small">
//                     <tbody>
//                         <tr><td class="bg-light">Stock Number</td><td>${res.item.stock_id ?? 'N/A'}</td></tr>
//                         <tr><td class="bg-light">Metal</td><td>14K ${res.item.metal_head ?? ''}</td></tr>
//                         <tr><td class="bg-light">Carat</td><td>${res.item.carat ?? 'N/A'}</td></tr>
//                     </tbody>
//                 </table>
//             </div>`;
//           //  $('#jewelryResults').html(res.html);
//         }
//     }
});
// Band Style (Shank) aur Head Style ke liye delegated click handler
$(document).on('click', '.filter-type.Band ul li', function() {
    let currentUl = $(this).closest('ul');

    // 1. UI update: Active class manage karein
    currentUl.find('li').removeClass('active');
    $(this).addClass('active');

    // 2. Same group ke saare checkboxes ko uncheck karke current ko select karein
    currentUl.find('input.filter').prop('checked', false);
    let checkbox = $(this).find('input.filter').first();
    checkbox.prop('checked', true);

    // 3. Filters object taiyar karke sendFilters call karein
    let type = checkbox.data('type');
    let val = checkbox.data('value');

    // Global filters update (jewelry_type ke saath)
    window.filters = window.filters || {};
    window.filters[type] = val;
    window.filters['jewelry_type'] = $('#jewelryMenu li.active').data('type') || 'ring';

    sendFilters(window.filters);
});

/* =========================================================
   FIX: toggleCategorySpecificFields is now attached to
   window so it can be safely called from anywhere
   (e.g. the $(window).on('load', ...) block below),
   not just inside the $(document).ready() closure
   where it was originally declared.
========================================================= */
window.toggleCategorySpecificFields = function (type) {
    let currentType = (type || '').toLowerCase();
    let isRing = currentType === 'ring';
    let isPendant = currentType === 'pendant';

    $('.ring-size-control').toggle(isRing);
    $('#pendantInfoMessage').toggle(isPendant);
};

$(window).on('load', function () {
    setTimeout(function () {
        toggleCategorySpecificFields('ring');
        $('#jewelryMenu li[data-type="ring"]').first().trigger('click');
        $('#jewelryMenu li[data-type="ring"]').first().trigger('click');
        $('.filter-type.Band ul li').first().addClass('active').find('input').prop('checked', true);
    }, 300);
});


// ---------------------------------------
     
</script>

<?php echo $__env->make('footer', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/brillianttouch/public_html/brillianttouchllc_app/resources/views/rdi_jewelry.blade.php ENDPATH**/ ?>