@include('header')

<style>
    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;
}
 .modal-content {
      border-radius: 12px;
    }

    #preview {
      border-radius: 10px;
      border: 1px solid #ddd;
    }
</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"> {{ $item->shank_style }} {{ $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="{{ $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 class="side-data">
                        <form method="POST" id="Form_email_submit"  enctype="multipart/form-data">
                        <meta name="csrf-token" content="{{ csrf_token() }}">
                  

                    <input type="email" name="email" placeholder="Enter Email" required>

                    <br><br>

                    <button type="button" onclick="takeScreenshot()">Take Screenshot</button>

                    <br><br>
                    <img id="preview" width="300" style="display:none;" />
                    <input type="hidden" name="screenshot" id="screenshotInput">

                    <br><br>

                    <button type="submit" id="email_form">Send Email</button>
                </form> -->
                <div id="response"></div>

                    <div class="filter-sec">

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

                            <!-- <h4>Diamond Shape</h4> -->

                            <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'],

                                ];

                                @endphp

                                @foreach($allShapes as $shapeCode => $shapeData)
                               

                                <li

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

                                    <img class="img-fluid"

                                        src="{{ asset('/public/ringbuilderassets/image/' . $shapeData['image'] . '.png') }}"

                                        alt="{{ $shapeData['name'] }}">

                                    <label for="{{ $shapeCode }}">{{ $shapeData['name'] }}</label>

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

                                        data-stock_id="" data-value="{{ $shapeCode }}" id="{{ $shapeCode }}"

                                        {{ isset($shapeStockMap[$shapeCode]) ? '' : 'disabled' }}>

                                </li>

                                @endforeach



                            </ul>

                        </div>

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

                            @if (request()->is('jewelry/type/ring') || request()->is('jewelry/type/pendant'))

                            <p>Head Style:</p>



                            <ul>

                                @foreach($headStyles as $style => $items)

                                @php

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

                                @endphp



                                <li

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

                                    <img class="img-fluid" src="{{ asset('/public/ringbuilderassets/image/prong.png') }}" alt="">

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

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

                                        data-value="{{ $style }}" id="head_style_{{ $loop->index }}">

                                </li>

                                @endforeach


                            </ul>

                            @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">

                                        @foreach($metalHeads as $metal_head => $items)

                                        @php

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

                                        @endphp

                                        @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_{{ $loop->index }}">

                                                14

                                            </label>

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

                                                data-type="metal_head" data-value="{{ $metal_head }}"

                                                id="metal_head_{{ $loop->index }}">

                                        </li>

                                        @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_{{ $loop->index }}">

                                                14

                                            </label>

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

                                                data-type="metal_head" data-value="{{ $metal_head }}"

                                                id="metal_head_{{ $loop->index }}">

                                        </li>

                                        @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_{{ $loop->index }}">

                                                14

                                            </label>

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

                                                data-type="metal_head" data-value="{{ $metal_head }}"

                                                id="metal_head_{{ $loop->index }}">

                                        </li>

                                        @endif

                                        @endforeach



                                    </ul>

                                </div>

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

                                    @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">

                                        @foreach($shankMetals as $metal_head => $items)

                                        @php

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

                                        @endphp

                                        @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_{{ $loop->index }}">

                                                14

                                            </label>



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

                                                data-type="shank_metals" data-value="{{ $metal_head }}"

                                                id="metal_head_{{ $loop->index }}">

                                        </li>

                                        @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_{{ $loop->index }}">

                                                14

                                            </label>



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

                                                data-type="shank_metals" data-value="{{ $metal_head }}"

                                                id="metal_head_{{ $loop->index }}">

                                        </li>

                                        @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_{{ $loop->index }}">

                                                14

                                            </label>



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

                                                data-type="shank_metals" data-value="{{ $metal_head }}"

                                                id="metal_head_{{ $loop->index }}">

                                        </li>

                                        @endif

                                        @endforeach



                                    </ul>

                                </div>

                                @endif

                            </div>





                        </div>

                        <div class="filter-type Band">

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

                            <p>Band Style:</p>

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

                                @foreach($shankStyles as $shank_style => $items)

                                @php



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

                                @endphp

                                @if($shank_style =='Solitaire')

                                <li

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

                                    <img class="img-fluid" src="{{ asset('/public/ringbuilderassets/image/Solitaire.png') }}" alt="">



                                    <label for="shank_style_{{ $loop->index }}">{{ $shank_style }}</label>



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

                                        data-value="{{ $shank_style }}" id="shank_style_{{ $loop->index }}">

                                </li>

                                @elseif($shank_style =='Knife Edge')



                                <li

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

                                    <img class="img-fluid" src="{{ asset('/public/ringbuilderassets/image/knife-edge-solitaire.png') }}"

                                        alt="">

                                    <label for="knife-edge-solitaire">{{ $shank_style }}</label>

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

                                        data-value="{{ $shank_style }}" id="shank_style_{{ $loop->index }}">

                                </li>

                                @elseif($shank_style =='Alternating Baguette')

                                <li

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

                                    <img class="img-fluid" src="{{ asset('/public/ringbuilderassets/image/split-solitaire.png') }}"

                                        alt="">

                                    <label for="split-solitaire">{{ $shank_style }}</label>

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

                                        data-value="{{ $shank_style }}" id="shank_style_{{ $loop->index }}">

                                </li>

                                @elseif($shank_style =='French Pave')

                                <li

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

                                    <img class="img-fluid" src="{{ asset('/public/ringbuilderassets/image/french-pave.png') }}" alt="">

                                    <label for="french-pave">{{ $shank_style }}</label>

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

                                        data-value="{{ $shank_style }}" id="shank_style_{{ $loop->index }}">

                                </li>

                                @elseif($shank_style =='Cathedral Pave')

                                <li

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

                                    <img class="img-fluid" src="{{ asset('/public/ringbuilderassets/image/cathedral-pave.png') }}"

                                        alt="">

                                    <label for="cathedral-pave">{{ $shank_style }}</label>

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

                                        data-value="{{ $shank_style }}" id="shank_style_{{ $loop->index }}">

                                </li>

                                @else

                                <li

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

                                    <img class="img-fluid" src="{{ asset('/public/ringbuilderassets/image/cathedral-pave.png') }}"

                                        alt="">

                                    <label for="cathedral-pave">{{ $shank_style }}</label>

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

                                        data-value="{{ $shank_style }}" id="shank_style_{{ $loop->index }}">

                                </li>

                                @endif



                                @endforeach

                            </ul>

                        </div>



                        @php

                        // All allowed ring sizes

                        $allowedSizes = ['3', '3.5', '4', '4.5', '5', '5.5', '6', '6.5', '7', '7.5', '8', '8.5',

                        '9', '9.5', '10'];



                        // Make sure all sizes are strings for comparison

                        $ring_Sizes = array_map('strval', $ring_Sizes);

                        @endphp



                        <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">

                                    <label for="ring_size">Select Ring Size:</label>

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

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

                                          <option value="4">4</option>

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

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

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

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

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

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

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

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

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

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

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

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

                                    </select>

                                </div>



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

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

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

                                        <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 class="side-data">
    
                         <!-- Trigger Button -->
      <button class="btn btn-dark mt-3" data-bs-toggle="modal" data-bs-target="#emailModal">
        Email Us
      </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">
    
                <!-- 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>
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 = @json($item);

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

}







const BASE_URL = "{{ config('app.url') }}";



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
let selectedShank = document.querySelector('input[data-type="shank_style"]:checked');
if (selectedShank) {
    window.filters['shank_style'] = selectedShank.dataset.value;
}

sendFilters(window.filters);

                });

            });

        }

    });






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

    if (ringSizeDropdown) {

        // Set default if already selected

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

            filters['ring_size'] = ringSizeDropdown.value;

        }



        // On change

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

            filters['ring_size'] = this.value;

            sendFilters(filters);

        });

    }

    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

        });

    });

    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 = "{{ route('jewelry.filter') }}";

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

    $.ajax({

        url: routeUrl,

        method: 'POST',

        data: filters,

        headers: {

            'X-CSRF-TOKEN': '{{ 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);
                    }
                };

            });


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

            var form = document.getElementById('Form_email_submit');
            var formData = new FormData(form); // ✅ correct way
            let routes_Url = "{{ route('send-email') }}";

            $.ajax({
                url: routes_Url,
                type: "POST",
                data: formData,

                processData: false,   // ✅ required
                contentType: false,   // ✅ required
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                },


                beforeSend: function() {
                    $('#response').html('Sending...');
                },

                success: function(response) {
                    $('#response').html(response.message);
                },

                error: function(xhr) {
                    console.log(xhr);
                    $('#response').html('Error');
                }
            });
        });

$(document).ready(function () {
    // 1. Base URL for static assets
    var BASE_URL = "https://braintreeeasysoft.com/brillianttouchllc_app/public/ringbuilderassets/image/";
    //  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');
        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: "{{ route('jewelry-type') }}",
            type: "POST",
            data: {
                type: type,
                _token: $('meta[name="csrf-token"]').attr('content')
            },
            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="800px" 
                                        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);
                    updateSectionData(res, BASE_URL);
                } 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 updateSectionData(res, BASE_URL) {
        // $('#jewelryResults').html(res.html);           
        /* --- TITLE & MASTER ID --- */

        let activeBand = $('.filter-type.Band ul li.active');
    if (activeBand.length === 0) {
        let firstBand = $('.filter-type.Band ul').last().find('li').first();
        firstBand.addClass('active');
        firstBand.find('input.filter').prop('checked', true);
        
        // Agar aap chahte hain ki select hote hi filter trigger ho:
        // let type = firstBand.find('input').data('type');
        // let val = firstBand.find('input').data('value');
        // sendFilters({ [type]: val, 'jewelry_type': $('#jewelryMenu li.active').data('type') });
    }
        $('#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');
            });
        }

        /* --- 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">
                    <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 bandHtml = '';
        if (res.shankStyles) {
            $.each(res.shankStyles, function (style) {
                // Image selection logic
                let imgName = 'cathedral-pave.png'; // Default
                if (style === 'Solitaire') {
                    imgName = 'Solitaire.png';
                } else if (style === 'Knife Edge') {
                    imgName = 'knife-edge-solitaire.png';
                } else if (style === 'Alternating Baguette') {
                    imgName = 'split-solitaire.png';
                } else if (style === 'French Pave') {
                    imgName = 'french-pave.png';
                } else if (style === 'Cathedral Pave') {
                    imgName = 'cathedral-pave.png';
                }
                // let isActive = (res.item?.shank_style == style || (index === 0 && !res.item?.shank_style)) ? 'active' : '';
                bandHtml += `
                <li class="d-flex flex-column align-items-center justify-content-around position-relative ">

                                    <img class="img-fluid" src="${BASE_URL}${imgName}" alt="${style}">

                                    <label for="french-pave">${style}</label>

                                    <input type="checkbox" name="shank_style" class="filter" data-type="shank_style" data-value="${style}" id="shank_style_2"  ${res.item?.shank_style == style ? 'checked' : ''}>

                                </li>
               `;
            });
        }
        $('.filter-type.Band ul').last().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);

        /* --- 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() {
    // 1. UI update: Active class manage karein
    $(this).closest('ul').find('li').removeClass('active');
    $(this).addClass('active');

    // 2. Iske andar ke hidden checkbox ko select karein
    let checkbox = $(this).find('input.filter');
    checkbox.prop('checked', true);

    // 3. Filters object taiyar karke sendFilters call karein
    let type = checkbox.data('type'); // shank_style
    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);
});

$(window).on('load', function () {
    setTimeout(function () {
        $('#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>

@include('footer')