

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

    // ================= WALLPAPER CALCULATE =================

    window.calculateWallpaper = function () {

        let width = document.getElementById("wall_width")?.value;
        let height = document.getElementById("wall_height")?.value;

        if (!width || !height) {
              Swal.fire({
        icon: 'warning',
        title: 'Required',
        text: 'Enter width & height'
    });
            
            return;
        }

        let token = localStorage.getItem("token");

        fetch(window.cartUrls.calculate, {
            method: "POST",
            headers: {
                "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').content,
                "Authorization": "Bearer " + token,
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                product_id: 132,
                variant_id: 239,
                width: parseFloat(width),
                height: parseFloat(height)
            })
        })
        .then(res => res.json())
        .then(res => {

            if (res.success) {

                let data = res.data;

                // ✅ fill rolls
                document.getElementById("rolls_required").value = data.rolls_required;

                // ✅ update button text
      let btn = document.getElementById("addToCartBtn");
if (btn) {
    btn.innerText = `₹${d.total} Add to cart`;
}

                // store
                window.wallpaperData = data;

            } else {
                 Swal.fire({
        icon: 'error',
        title: 'Oops...',
        text: 'Calculation failed'
    });
               
            }

        })
        .catch(err => {
    Swal.fire({
        icon: 'error',
        title: 'Oops...',
        text: 'Something went wrong!'
    });
});
    };


    // ================= ADD TO CART =================
// document.querySelectorAll(".addToCartBtn").forEach(btn => {

//     btn.addEventListener("click", function () {

//         console.log("Clicked"); // 🔥 DEBUG

//         let token = localStorage.getItem("token");

//         let product_id = this.dataset.product;
//         let variant_id = this.dataset.variant;
//         let is_sample = this.dataset.sample;
//         let sample_price = this.dataset.price;

//         let formData = new FormData();

//         formData.append("product_id", product_id);
//         formData.append("variant_id", variant_id);
//         formData.append("quantity", 1);

//         if (is_sample == "1") {

//             formData.append("is_sample", 1);
//             formData.append("is_fabric", 0);
//             formData.append("total", sample_price);

//         } else {

//             if (!window.wallpaperData) {
//                Swal.fire({
//         icon: 'warning',
//         title: 'Required',
//         text: 'Please calculate first'
//     });
//                 return;
//             }

//             let data = window.wallpaperData;

//             formData.append("is_sample", 0);
//             formData.append("is_fabric", 0);
//             formData.append("quantity", data.rolls_required);
//             formData.append("width", data.wall_width);
//             formData.append("height", data.wall_height);
//             formData.append("total", data.amount);
//         }

//         fetch(window.cartUrls.add, {
//             method: "POST",
//             headers: {
//                 "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').content,
//                 "Authorization": "Bearer " + token
//             },
//             body: formData
//         })
//         .then(res => res.json())
//         .then(res => {
//             Swal.fire({
//     icon: 'success',
//     title: 'Added to Cart',
//     text: 'Product added successfully!',
//     confirmButtonColor: '#000'
// });
//             console.log(res);
//         });

//     });

// });
document.addEventListener("click", function (e) {

    let btn = e.target.closest(".addToCartBtn");
    if (!btn) return;

    let token = localStorage.getItem("token");

    if (!token) {
        Swal.fire({
            icon: 'warning',
            title: 'Login Required',
            text: 'Please login first'
        });
        return;
    }

    let product_id = btn.dataset.product;
    let variant_id = btn.dataset.variant;
    let is_sample = btn.dataset.sample || "0";
    let sample_price = btn.dataset.price || 0;

    let formData = new FormData();

    formData.append("product_id", product_id);
    formData.append("variant_id", variant_id);

    // ================= SAMPLE PRODUCT =================
    if (is_sample === "1") {

        formData.append("quantity", 1);
        formData.append("is_sample", 1);
        formData.append("is_fabric", 0);
        formData.append("total", sample_price);

    }

    // ================= FABRIC =================
    else if (document.getElementById("fabric_meter")) {

        if (!window.fabricData) {
            Swal.fire({
                icon: 'warning',
                title: 'Enter Meter',
                text: 'Please enter fabric meter'
            });
            return;
        }

        formData.append("quantity", 1);
        formData.append("is_sample", 0);
        formData.append("is_fabric", 1);

        formData.append("fabric_meter", window.fabricData.meter);
        formData.append("fabric_total", window.fabricData.total);
        formData.append("total", window.fabricData.total);
    }

    // ================= WALLPAPER =================
    else if (document.getElementById("wall_width")) {

        if (!window.wallpaperData) {
            Swal.fire({
                icon: 'warning',
                title: 'Required',
                text: 'Please calculate wallpaper first'
            });
            return;
        }

        let d = window.wallpaperData;

        formData.append("quantity", d.rolls_required);
        formData.append("is_sample", 0);
        formData.append("is_fabric", 0);

        formData.append("width", d.wall_width);
        formData.append("height", d.wall_height);
        formData.append("total", d.amount);
    }

    // ================= CURTAIN =================
    else if (document.getElementById("curtain_width")) {

        if (!window.selectedModel) {
            Swal.fire({
                icon: 'warning',
                title: 'Select Model',
                text: 'Please select curtain model'
            });
            return;
        }

        if (!window.curtainData) {
            Swal.fire({
                icon: 'warning',
                title: 'Required',
                text: 'Please calculate curtain first'
            });
            return;
        }

        let d = window.curtainData;

        formData.append("is_sample", 0);
        formData.append("is_fabric", 0);

        formData.append("model_id", window.selectedModel);
        formData.append("width", document.getElementById("curtain_width").value);
        formData.append("height", document.getElementById("curtain_height").value);
        formData.append("quantity", document.getElementById("curtain_qty").value);

        formData.append("panels", d.panels);
        formData.append("fabric_meter", d.fabric_meter);
        formData.append("fabric_total", d.fabric_total);
        formData.append("stitch_rate", d.stitch_rate);
        formData.append("stitch_total", d.stitch_total);
        formData.append("total", d.total);
    }

    // ================= NORMAL PRODUCT =================
    else {

        let qtyInput = document.querySelector(".cart-plus-minus-box");

        let qty = qtyInput ? qtyInput.value : 1;

        let priceText = document.getElementById("price")?.innerText || "0";
        let price = parseFloat(priceText.replace(/[^\d.]/g, ""));

        let total = price * qty;

        formData.append("quantity", qty);
        formData.append("is_sample", 0);
        formData.append("is_fabric", 0);
        formData.append("total", total);
    }

    // ================= API CALL =================
    fetch(window.cartUrls.add, {
        method: "POST",
        headers: {
            "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').content,
            "Authorization": "Bearer " + token
        },
        body: formData
    })
    .then(res => res.json())
    .then(res => {

        if (res.success || res.status) {

            Swal.fire({
                icon: 'success',
                title: 'Added to Cart',
                text: 'Product added successfully!',
                timer: 1500,
                showConfirmButton: false
            });

        } else {

            Swal.fire({
                icon: 'error',
                title: 'Failed',
                text: res.message || 'Something went wrong'
            });

        }

    })
    .catch(err => {
        console.error(err);

        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Server error. Please try again'
        });
    });

});

// ===================== Curtain Calculate Function ======================

window.calculateCurtain = function () {

    let width = document.getElementById("curtain_width").value;
    let height = document.getElementById("curtain_height").value;
    let qty = document.getElementById("curtain_qty").value;

    // if (!width || !height || !qty) {
    //     Swal.fire({
    //         icon: 'warning',
    //         title: 'Required',
    //         text: 'Enter all values'
    //     });
    //     return;
    // }

    if (!window.selectedModel) {
        Swal.fire({
            icon: 'warning',
            title: 'Select Model',
            text: 'Please select curtain model'
        });
        return;
    }

    let token = localStorage.getItem("token");

    fetch(window.cartUrls.calculate, {
        method: "POST",
        headers: {
            "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').content,
            "Authorization": "Bearer " + token,
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            product_id: document.querySelector(".addToCartBtn").dataset.product,
            variant_id: document.querySelector(".addToCartBtn").dataset.variant,
            model_id: window.selectedModel,
            width: parseFloat(width),
            height: parseFloat(height),
            quantity: parseInt(qty)
        })
    })
    .then(res => res.json())
    .then(res => {

        let d = res;

        // ✅ SAFE UPDATE (NO optional chaining)
       if (document.getElementById("curtain_panels")) {
    document.getElementById("curtain_panels").innerText = d.panels;
}
        if (document.getElementById("curtain_meter"))
            document.getElementById("curtain_meter").innerText = parseFloat(d.fabric_meter).toFixed(2);

        if (document.getElementById("curtain_fabric_total"))
            document.getElementById("curtain_fabric_total").innerText = d.fabric_total;

        if (document.getElementById("curtain_stitch_total"))
            document.getElementById("curtain_stitch_total").innerText = d.stitch_total;

        if (document.getElementById("curtain_total"))
            document.getElementById("curtain_total").innerText = d.total;

        // ✅ update button price
        let btn = document.querySelector(".addToCartBtn");
        if (btn) {
            btn.innerText = `₹${d.total} Add to Cart`;
        }

        // ✅ store data for add to cart
        window.curtainData = d;

    })
    .catch(err => {
        console.error(err);
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Calculation failed'
        });
    });
};
// ["curtain_width", "curtain_height", "curtain_qty"].forEach(id => {
//     document.getElementById(id)?.addEventListener("input", () => {
//         if (window.selectedModel) {
//             calculateCurtain();
//         }
//     });
// });

// ================= FABRIC CALCULATION =================

let fabricInput = document.getElementById("fabric_meter");

if (fabricInput) {

    fabricInput.addEventListener("input", function () {

        let meter = parseFloat(this.value);
        let pricePerMeter = parseFloat(document.getElementById("fabric_price_per_meter").innerText);

        if (!meter || meter <= 0) {
            document.getElementById("fabric_total_meter").innerText = 0;
            document.getElementById("fabric_total_price").innerText = 0;
            return;
        }

        let total = meter * pricePerMeter;

        // update UI
        document.getElementById("fabric_total_meter").innerText = meter.toFixed(2);
        document.getElementById("fabric_total_price").innerText = total.toFixed(2);

        // update button text
        let btn = document.querySelector(".addToCartBtn");
        if (btn) {
            btn.innerText = `₹${total.toFixed(0)} Add to Cart`;
        }

        // store globally
        window.fabricData = {
            meter: meter,
            total: total
        };

    });

}

});


// ************************** product details style js *********************************


    document.querySelectorAll('.variant-btn').forEach(btn => {
            btn.addEventListener('click', function() {

                // active class
                document.querySelectorAll('.variant-btn').forEach(b => b.classList.remove('active'));
                this.classList.add('active');

                let images = JSON.parse(this.dataset.images);
                let price = this.dataset.price;

                // change price
                document.getElementById('price').innerText = '₹' + price;

                // change images
                let bigWrapper = document.getElementById('bigImageWrapper');
                let thumbWrapper = document.getElementById('thumbWrapper');

                bigWrapper.innerHTML = '';
                thumbWrapper.innerHTML = '';

                images.forEach(img => {

                    bigWrapper.innerHTML += `
                <div class="swiper-slide">
                    <img src="${img.image}" style="width:100%">
                </div>
            `;

                    thumbWrapper.innerHTML += `
                <div class="swiper-slide">
                    <img src="${img.image}" style="width:60px">
                </div>
            `;
                });

            });
        });


           let selectedModel = null;

       document.querySelectorAll('.model-card').forEach(card => {
    card.addEventListener('click', function() {

        document.querySelectorAll('.model-card').forEach(c => c.classList.remove('active'));
        this.classList.add('active');

        window.selectedModel = this.dataset.id;

        // ✅ auto calculate after selecting model
        if (
            document.getElementById("curtain_width").value &&
            document.getElementById("curtain_height").value
        ) {
            calculateCurtain();
        }
    });
});