// Color map for swatches when no image URL given
var COLOR_MAP = {
    "Deep Purple": "#5B2D8E", "Gold": "#C8A951", "Silver": "#C0C0C0",
    "Space Black": "#1C1C1E", "Blue": "#007AFF", "Midnight": "#1C1C1E",
    "Starlight": "#F2E8D5", "Purple": "#BF5AF2", "PRODUCT RED": "#FF3B30",
    "Phantom Black": "#1C1C1E", "Phantom White": "#F0F0F0", "Burgundy": "#800020",
    "Green": "#34C759", "Sonic Black": "#222222", "Galactic Silver": "#C0C0C0",
    "Snow": "#F5F5F5", "Obsidian": "#232323", "Lemongrass": "#BFCC6F",
    "Nebula Green": "#2EAD6C", "Eclipse Black": "#141414", "Viva Magenta": "#BB2649",
    "Magic Blue": "#1E88E5", "Noble Black": "#1A1A1A", "Emerald Green": "#50C878",
    "Active Black": "#111111", "Bold Red": "#E53935", "Mint Green": "#3EB489",
    "Navy Blue": "#003153", "Blended Black": "#1A1A1A", "Stone Blue": "#4682B4",
    "Luscious Red": "#C62828", "Charcoal Black": "#2C2C2C", "Pearl White": "#F8F8F8",
    "Sky Blue": "#87CEEB", "Orange": "#FF8C00", "Misty Lilac": "#C8A2C8",
    "Bold Black": "#111111", "Black/Red": "#B71C1C", "White": "#FFFFFF",
    "Black": "#111111", "Red": "#E53935", "Pink": "#FF69B4",
    "Yellow": "#FFD700", "Brown": "#795548", "Rose Gold": "#B76E79"
};

$(document).ready(function() {
    var productId = getProductIdFromURL();
    if (productId) {
        loadProduct(productId);
    }
});

function getProductIdFromURL() {
    var urlParams = new URLSearchParams(window.location.search);
    return urlParams.get("productId");
}

function loadProduct(productId) {
    $.getJSON("./js/products.json", function(products) {
        var product = null;
        for (var i = 0; i < products.length; i++) {
            if (products[i].id === productId) { product = products[i]; break; }
        }
        if (!product) {
            console.error("Product not found: " + productId);
            return;
        }
        renderProduct(product);
        localStorage.setItem("savedProduct", JSON.stringify(product));
        updatePaymentLinks(product.selling_price);
    }).fail(function() {
        console.error("Could not load products.json");
    });
}

function renderProduct(product) {
    // --- CAROUSEL ---
    var carousel = $("#productCarousel");
    carousel.empty();
    var imgs = [];
    for (var i = 1; i <= 5; i++) {
        if (product["img" + i]) imgs.push(product["img" + i]);
    }
    if (imgs.length === 0) {
        carousel.html('<div class="carousel-item active"><div style="height:300px;display:flex;align-items:center;justify-content:center;color:#999;">No Image</div></div>');
    } else {
        imgs.forEach(function(src, idx) {
            var activeClass = idx === 0 ? "active" : "";
            carousel.append(
                '<div class="carousel-item ' + activeClass + '">' +
                '<img src="' + src + '" alt="' + product.name + '" ' +
                'style="height:320px;width:100%;object-fit:contain;display:block;" ' +
                'onerror="this.style.display=\'none\'">' +
                '</div>'
            );
        });
    }

    // Update indicators count
    var ol = $("#sliderX ol.carousel-indicators");
    ol.empty();
    imgs.forEach(function(_, idx) {
        ol.append('<li data-bs-target="#sliderX" data-bs-slide-to="' + idx + '" class="' + (idx===0?"active":"") + '"></li>');
    });

    // --- VARIANTS ---
    renderVariants(product);

    // --- PRICE CARD ---
    $(".product-title").text(product.name);
    var discount = product.discount || "90%";
    $(".discount.detls-dis").text(discount + " off");
    $(".mrp").text("₹" + Number(product.mrp).toLocaleString('en-IN'));
    $(".price").text("₹" + Number(product.selling_price).toLocaleString('en-IN'));

    // --- FEATURES ---
    $("#productFeatures").html(product.fetaures || "");

    // --- DETAIL IMAGES ---
    var det = $("#productDetailImages");
    det.empty();
    for (var j = 1; j <= 5; j++) {
        if (product["img" + j]) {
            det.append('<img src="' + product["img" + j] + '" style="max-width:100%;display:block;margin-bottom:6px;" onerror="this.remove()">');
        }
    }

    // Back button
    $("#back_btn").on("click", function() { history.back(); });
}

function renderVariants(product) {
    var varients = product.verients || [];
    var section = $("#variantSection");
    section.empty();

    // Filter out empty variant groups
    var validVariants = [];
    for (var i = 0; i < varients.length; i++) {
        var v = varients[i];
        if (v.options && v.options.length > 0) {
            validVariants.push(v);
        }
    }

    if (validVariants.length === 0) {
        section.hide();
        return;
    }
    section.show();

    validVariants.forEach(function(variant) {
        var block = $('<div class="variant-block"></div>');
        var title = $('<div class="variant-title">Select ' + variant.label + '</div>');
        var row = $('<div class="variant-options-row"></div>');

        if (variant.type === "color") {
            variant.options.forEach(function(opt) {
                var isActive = opt.selected ? " active" : "";
                var chip = $('<div class="color-item' + isActive + '"></div>');
                var wrap = $('<div class="color-img-wrap"></div>');

                if (opt.img && opt.img.trim() !== "") {
                    // Show product image thumbnail
                    var img = $('<img src="' + opt.img + '" alt="' + opt.name + '">');
                    img.on("error", function() {
                        // fallback to color swatch
                        var swatch = $('<div class="color-swatch"></div>');
                        swatch.css("background-color", COLOR_MAP[opt.name] || "#999999");
                        $(this).replaceWith(swatch);
                    });
                    wrap.append(img);
                } else {
                    // Show color swatch
                    var swatch = $('<div class="color-swatch"></div>');
                    swatch.css("background-color", COLOR_MAP[opt.name] || "#999999");
                    wrap.append(swatch);
                }

                var name = $('<div class="color-item-name">' + opt.name + '</div>');
                chip.append(wrap).append(name);

                chip.on("click", function() {
                    row.find(".color-item").removeClass("active");
                    $(this).addClass("active");
                });
                row.append(chip);
            });
        } else {
            variant.options.forEach(function(opt) {
                var isActive = opt.selected ? " active" : "";
                var btn = $('<div class="storage-btn' + isActive + '">' + opt.name + '</div>');
                btn.on("click", function() {
                    row.find(".storage-btn").removeClass("active");
                    $(this).addClass("active");
                });
                row.append(btn);
            });
        }

        block.append(title).append(row);
        section.append(block);
    });
}

function buyNow() {
    var productId = getProductIdFromURL();
    window.location.href = "address.html?productId=" + productId;
}

function btnContinue() {
    var productId = getProductIdFromURL();
    window.location.href = "payment.php?productId=" + productId;
}

function updatePaymentLinks(price) {
    document.querySelectorAll(".available-method").forEach(function(method) {
        var url = method.getAttribute("data-payment-url");
        if (url) {
            method.setAttribute("data-payment-url", url.replace(/am=[^&]+/, "am=" + price));
        }
    });
}

document.querySelectorAll(".available-method").forEach(function(method) {
    method.addEventListener("click", function() {
        document.querySelectorAll(".available-method").forEach(function(m) { m.classList.remove("active"); });
        method.classList.add("active");
    });
});
