const flashproductContainers = [...document.querySelectorAll('.flash-product-container')];
const flashnxtBtn = [...document.querySelectorAll('.flex-pre-btn')];
const flashpreBtn = [...document.querySelectorAll('.flex-nxt-btn')];

flashproductContainers.forEach((item, i) => {
    let containerDimensions = item.getBoundingClientRect();
    let containerWidth = containerDimensions.width;

    flashnxtBtn[i].addEventListener('click', () => {
        item.scrollLeft += containerWidth;
    })

    flashpreBtn[i].addEventListener('click', () => {
        item.scrollLeft -= containerWidth;
    })
})




let productStocks = [];

/* OPEN MODAL */
function show_addtocart_modal(el) {



    let productId   = el.dataset.id;
    let name        = el.dataset.name;
    let unit        = el.dataset.unit;
    let unitPrice   = parseFloat(el.dataset.unitprice) || 0;
    let discount    = parseFloat(el.dataset.discount) || 0;

    let colors  = JSON.parse(el.dataset.colors || '[]');
    let choices = JSON.parse(el.dataset.choice || '[]');
    productStocks = JSON.parse(el.dataset.stocks || '[]');

    document.getElementById('modal_product_title').innerText = name;
    document.getElementById('original_price').innerText = unitPrice.toFixed(2) + '/' + unit;
    document.getElementById('selling_price').innerText = 'Rs ' + (unitPrice - discount).toFixed(2) + '/' + unit;
    document.getElementById('Total_price').innerText = 'Rs ' + (unitPrice - discount).toFixed(2);

    document.getElementById('modal_product_id').value = productId;
    document.getElementById('modal_product_unitprice').value = unitPrice;
    document.getElementById('modal_product_discount').value = discount;
    document.getElementById('modal_product_unit').value = unit;

    /* MAIN IMAGE */
   

    // ---------- IMAGES FIX ----------
let images = [];
if (el.dataset.images) {
    images = el.dataset.images.split(',').map(img => {
        img = img.trim();
        return STORAGE_URL + img;
    });
}

// fallback if no images
if (!images.length && el.dataset.image) {
    images = [el.dataset.image];
}

let thumbBox = document.querySelector('.thumb-list');
thumbBox.innerHTML = '';

// Set main image
document.getElementById('modal_product_image').src = images[0];

// Create thumbnails
images.forEach((img, index) => {
    let thumb = document.createElement('img');
    thumb.src = img;
    thumb.className = 'thumb-img ' + (index === 0 ? 'active' : '');

    thumb.onclick = function () {
        document.getElementById('modal_product_image').src = img;
        document.querySelectorAll('.thumb-img').forEach(t => t.classList.remove('active'));
        thumb.classList.add('active');
    };

    thumbBox.appendChild(thumb);
});



    /* COLORS */
   
    let colorHtml = '';
    colorHtml += `
        <div class="row mb-2">
            <div class="col-sm-3 opacity-50">Color:</div>
            <div class="col-sm-9 d-flex flex-wrap">
    `;
    
    colors.forEach((c, i) => {
        let colorName = colorname(c);
        colorHtml += `
        <label class="aiz-megabox me-2">
            <input type="radio" name="color"
                    value="${colorName}"    
                    data-code="${colorName}" 
                   ${i === 0 ? 'checked' : ''}
                   onchange="updateVariantData()" hidden>
                   
                   <span class="aiz-megabox-elem rounded d-flex align-items-center justify-content-center p-1 mb-2">
                   <span class="my-box" style="background-color:${c};"></span>
              </span>

        </label>`;
    });
    colorHtml += `
            </div>
        </div>
        <hr>
    `;

    document.getElementById('modal_colors').innerHTML = colorHtml;

    let container = document.getElementById('modal_choices');
    container.innerHTML = '';
    choices.forEach(choice => {
        let row = document.createElement('div');
        row.className = 'row g-0 align-items-center mb-2';
        row.innerHTML = `
            <div class="col-sm-3"><div class="opacity-50 my-2">${choice.attribute_name}:</div></div>
            <div class="col-sm-9 d-flex flex-wrap">
                ${choice.values.map((v,i) => `
                    <label class="aiz-megabox me-2">
                        <input type="radio" name="attribute_id_${choice.attribute_id}" value="${v}" ${i===0?'checked':''} onchange="updateVariantData()">
                        <span class="aiz-megabox-elem rounded d-flex align-items-center justify-content-center py-2 px-3 mb-2">${v}</span>
                    </label>
                `).join('')}
            </div>
        `;
        container.appendChild(row);
    });
    document.getElementById('addToCartForm').action = `/addtomycart/${productId}`;
    
    /* SINGLE ATTRIBUTE (Cotton, Silk, etc.) */
    
    updateVariantData();
    document.getElementById('quantity').value = 1;

   

    new bootstrap.Modal(document.getElementById('chat_modal')).show();
}
function colorname(colorcode) {
    const color = COLORS.find(c => c.code.toLowerCase() === colorcode.toLowerCase());
    return color ? color.name : 'Unknown';
}

/* BUILD VARIANT EXACTLY LIKE DB */
function getSelectedVariant() {

    let colorInput = document.querySelector('input[name="color"]:checked');
    let color = colorInput ? colorInput.dataset.code : '';
    let attrInput = document.querySelector('input[name^="attribute_id_"]:checked');
    let attr = attrInput ? attrInput.value : '';
     

    if (!color && !attr) return '';
    if(color && !attr){
        return color
     }
     if(!color && attr){
        return attr
     }
     if(color && attr){
        return color + '-' + attr;
     }

   // return color + '-' + attr; // 🔥 DarkGreen-Cotton
}

/* UPDATE PRICE & IMAGE */
function updateVariantData() {

    let variant = getSelectedVariant();
   console.log(variant);
    let stock = productStocks.find(s => s.variant === variant);

    if (!stock) {
        console.warn('Variant not found:', variant);
        return;
    }

    document.getElementById('modal_product_unitprice').value = stock.price;

    document.getElementById('original_price').innerText = 'Rs ' + stock.price.toFixed(2) + '/' + document.getElementById('modal_product_unit').value;

    document.getElementById('modal_product_image').src =
        STORAGE_URL + stock.image;

    updatePrices();
}

/* TOTAL */
function updatePrices() {

    let qty = parseInt(document.getElementById('quantity').value) || 1;
    let price = parseFloat(document.getElementById('modal_product_unitprice').value);
    let discount = parseFloat(document.getElementById('modal_product_discount').value);
    let unit    =  document.getElementById('modal_product_unit').value;

    let selling = price - discount;
    let total = selling * qty;

    document.getElementById('selling_price').innerText = 'Rs ' + selling.toFixed(2) + '/' + unit;
    document.getElementById('Total_price').innerText = 'Rs ' + total.toFixed(2);
}

/* QTY */
document.getElementById('plus').onclick = () => {
    if (+quantity.value < 5) quantity.value++;
    updatePrices();
};
document.getElementById('minus').onclick = () => {
    if (+quantity.value > 1) quantity.value--;
    updatePrices();
};
function closeModal() {
    const modal = document.getElementById('chat_modal');
    if (modal) {
        modal.style.display = 'none'; // hides fade + modal
        document.body.style.overflow = 'auto'; // enable scroll again
    }
}
window.addEventListener('click', function (e) {
    const modal = document.getElementById('chat_modal');
    if (e.target === modal) {
        closeModal();
    }
});

function addToCart() {

    let product_id = document.getElementById('product_id').value;
    let variant = getSelectedVariant();
    let qty = document.getElementById('qty').value;

    if (!variant) {
        alert('Please select variant');
        return;
    }

    fetch(`/addtomycart/${product_id}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
        },
        body: JSON.stringify({
            variant: variant,
            quantity: qty
        })
    })
    .then(res => res.json())
    .then(data => {
        alert(data.message);
        closeModal();
    });
}

function changeMainImage(element) {
    document.getElementById('mainProductImage').src = element.src;

    document.querySelectorAll('.thumb-img').forEach(img => {
        img.classList.remove('active');
    });

    element.classList.add('active');
}

function openCity(evt, cityName) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
      tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
      tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(cityName).style.display = "block";
    evt.currentTarget.className += " active";
  }

  function myFunctionadd() {
    let qtyInput = document.getElementById('quantity');
    let currentQty = parseInt(qtyInput.value);
    let maxQty = parseInt(qtyInput.dataset.max) || 1;

    if (currentQty < 5) {
        qtyInput.value = currentQty + 1;
        updateTotalPrice();
    }
}

function myFunctionminus() {
    let qtyInput = document.getElementById('quantity');
    let currentQty = parseInt(qtyInput.value);

    if (currentQty > 1) {
        qtyInput.value = currentQty - 1;
        updateTotalPrice();
    }
}
function updateTotalPrice() {
    let qty = parseInt(document.getElementById('quantity').value);
    let unitPrice = parseFloat(document.getElementById('unitprice').value);

    let total = qty * unitPrice;

    document.getElementById('price').innerText =
        total.toLocaleString('en-PK', { minimumFractionDigits: 2 });

    document.getElementById('price1').value = total;
}


function checkStockFromDB(productId) {
    return fetch(`/product-stock/${productId}`)
        .then(response => response.json())
        .catch(err => {
            console.error(err);
            return [];
        });
}

function updateStockBySelection() {

    let colorEl = document.querySelector('input[name="color"]:checked');
let selectedColor = colorEl ? colorEl.dataset.code : ''; 

    let prod_id = document.getElementById('id').value;

    // 1️⃣ Get stock from server
    checkStockFromDB(prod_id).then(productStocks => {

        let variantParts = [];
        document.querySelectorAll('input[name^="attribute_id_"]:checked')
            .forEach(el => variantParts.push(el.value));

        let selectedVariant = variantParts.join('-');
        let selectedFullVariant = selectedColor + (selectedVariant ? '-' + selectedVariant : '');

        let matchedStock = productStocks.find(stock =>
            stock.variant === selectedFullVariant
        );

        if (!matchedStock) {
            console.warn('No matching stock found:', selectedFullVariant);
            return;
        }

        // Update main image
        let mainImg = document.getElementById('mainProductImage');
        if (mainImg && matchedStock.image) {
            mainImg.src = "/storage/" + matchedStock.image;
        }

        // Update quantity max
        let qtyInput = document.getElementById('quantity');
        qtyInput.dataset.max = matchedStock.qty;
        qtyInput.value = 1;

        // Update price and stock ID
        let discount=document.getElementById('descount').value 
        document.getElementById('unitprice').value = matchedStock.price-discount;
        document.getElementById('stock_id').value = matchedStock.id;

        updateTotalPrice();
    });

}
































