$(document).ready(function () {
    // Setup CSRF token for AJAX requests
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    // Define Base API URL
    const BASE_URL = "https://diamondapp.mydiamondsearch.com/jewelry_app/load-more-diamond";

    // Load Initial Data
    loadMoreData(BASE_URL);

    // Apply saved text color & font size from local storage
    $(".text_color").css("color", localStorage.getItem('text_color'));
    $(".font_size").css("font-size", localStorage.getItem('font_size'));

    // Attach event listeners
    $('#form').on('change', debounce(submitForm, 500));

    $(".form-control").on("keyup", function (event) {
        if (event.keyCode === 13 && event.target.value) {
            submitForm();
        }
    });

    $("li > :checkbox").on("click", function (event) {
        (event.target.name === 'ex3' || event.target.name === 'ex3n') ? debounce(submitForm, 500) : submitForm();
    });

    $("#checkAlls").on("click", function () {
        $(".tr_checkbox").prop("checked", $(this).is(':checked'));
    });
});

// 🔹 Debounce Function to Limit API Calls
function debounce(func, delay) {
    let timer;
    return function (...args) {
        clearTimeout(timer);
        timer = setTimeout(() => func.apply(this, args), delay);
    };
}

// 🔹 Submit Form and Fetch Data
function submitForm() {
    loadMoreData("https://diamondapp.mydiamondsearch.com/jewelry_app/load-more-diamond"h);
}

// 🔹 Pagination Handler
function pagination(url) {
    const urlParams = new URL(url).searchParams;
    const page = urlParams.get('page');
    loadMoreData(`${BASE_URL}?shop=${Shopify.shop}&page=${page}`);
}

// 🔹 Validate Numeric Input
function checkInput(event) {
    const allowedKeys = ['.', 'Enter', 'Backspace', 'Delete'];
    if (isNaN(event.key) && !allowedKeys.includes(event.key)) {
        event.preventDefault();
    }
}

// 🔹 Handle Input Change with Debounce
function inputValue(event, id, index, text) {
    if (checkInput(event)) {
        debounce(() => inputValueDelay(id, index, text), 500)();
    }
}

// 🔹 Validate and Set Range Values
function inputValueDelay(id, index, text) {
    let from_val = $(`#${id}_from`).val().trim() || (index ? "0" : "");
    let to_val = $(`#${id}_to`).val().trim() || (!index ? "100" : "");

    if (parseFloat(from_val) > parseFloat(to_val)) {
        alertify.warning(`${text} from cannot be greater than ${text} to`);
        $(`#${id}_to`).val(from_val);
    }

    submitForm();
}

// 🔹 Load Data via AJAX and Render Products
function loadMoreData(url) {
    const dia_view = localStorage.getItem('dia_view');
    const stock_number = $("#stock_number").val();
    const page_name = $("#page_name").val();
    const per_page = $("#per_page").val();
    const shop_name = Shopify.shop;
    const value_form = $('#form').serialize() + '&' + $.param({ stock_number, page_name, shop_name, per_page });

    localStorage.setItem('diamondForm', value_form);

    $.ajax({
        url,
        type: 'GET',
        dataType: 'json',
        headers: { 'Content-Type': 'application/json' },
        data: value_form,
        beforeSend: () => $("#page-loader").show(),
        success: (data) => {
            console.log(data);

            if (data.retaillerid) {
                const { text_color, border_color, button_background, button_text_color, button_background_hover, input_bg, font_size } = data.retaillerid;
                
                // Set CSS Variables Dynamically
                document.documentElement.style.setProperty('--text_color_pr', text_color);
                document.documentElement.style.setProperty('--border_color_pr', border_color);
                document.documentElement.style.setProperty('--button_background_pr', button_background);
                document.documentElement.style.setProperty('--button_text_color_pr', button_text_color);
                document.documentElement.style.setProperty('--button_background_hover_pr', button_background_hover);
                document.documentElement.style.setProperty('--input_bg', input_bg);
                
                if (font_size) {
                    document.documentElement.style.setProperty('--font_size_pr', `${font_size}px`);
                }
            }

            // Generate HTML for Products
            const html = (data.records || []).map(product => `
                <div class="product_col col-sm-4 col-md-4">
                    <div class="prod-list-block product_card">
                        <div class="prod-img product_thumb">
                            <a href="${product.products_seo_url}" target="_blank">
                                <img src="${product.image_url || ''}" alt="${product.products_name || ''}" title="${product.products_name || ''}">
                            </a>
                        </div>
                        <div class="product-description">
                            <p class="product-description__title">
                                <a href="${product.products_seo_url}" target="_blank">${product.products_name || ''}</a>
                            </p>
                            <p class="product-description__price">$${Math.round(product.products_price || 0)}</p>
                        </div>
                        <div class="product-actions">
                            <button onclick="AddToWishList('${product.products_id}')">❤️ Wishlist</button>
                            <button onclick="AddToCart('${product.products_id}')">🛒 Add to Cart</button>
                        </div>
                    </div>
                </div>
            `).join("");

            $("#grid_diamond").html(html).show();
        },
        complete: () => $("#page-loader").fadeOut(),
        error: (xhr, status, error) => console.error(`Error: ${error}`)
    });
}
