var jQuery = jQuery || $.noConflict();
(function ($) {
    "use strict";

    // === Color Palettes ===
    var palettes = [
        { id: "0", name: "Default",  brand: "#ff6600", accent: "#f3f4f6", text: "#111827", bg: "#ffffff", price: "#ff6600", pageBg: "#ffffff" },
        { id: "1", name: "Slate",  brand: "#374151", accent: "#9CA3AF", text: "#1f2937", bg: "#ffffff", price: "#374151", pageBg: "#ffffff" },
        { id: "9", name: "Classic Green",  brand: "#0a5114", accent: "#2e6e4a", text: "#1a1a2e", bg: "#ffffff", price: "#0a5114", pageBg: "#ffffff" },
        { id: "2", name: "Ocean",      brand: "#0070c9", accent: "#ff6b35", text: "#1a1a2e", bg: "#ffffff", price: "#0070c9", pageBg: "#e8f4fd" },
        { id: "3", name: "Nature",      brand: "#2d9f4f", accent: "#e67e22", text: "#1a1a2e", bg: "#ffffff", price: "#2d9f4f", pageBg: "#eaf5ed" },
        { id: "4", name: "Warm",      brand: "#e74c3c", accent: "#f39c12", text: "#1a1a2e", bg: "#ffffff", price: "#e74c3c", pageBg: "#fdecea" },
        { id: "5", name: "Night",       brand: "#2c3e50", accent: "#1abc9c", text: "#1a1a2e", bg: "#f8f9fa", price: "#1abc9c", pageBg: "#e8eaed" },
        { id: "6", name: "Business",    brand: "#1a5276", accent: "#c0392b", text: "#1a1a2e", bg: "#ffffff", price: "#1a5276", pageBg: "#e8eef3" },
        { id: "7", name: "Rose",        brand: "#e91e63", accent: "#9c27b0", text: "#1a1a2e", bg: "#ffffff", price: "#e91e63", pageBg: "#fce4ec" },
        { id: "8", name: "Minimal",    brand: "#333333", accent: "#666666", text: "#1a1a2e", bg: "#ffffff", price: "#333333", pageBg: "#f5f5f5" }
    ];

    // === Color Helpers ===
    function hexToRgb(hex) {
        hex = hex.replace("#", "");
        return {
            r: parseInt(hex.substring(0, 2), 16),
            g: parseInt(hex.substring(2, 4), 16),
            b: parseInt(hex.substring(4, 6), 16)
        };
    }

    function rgbToHex(r, g, b) {
        r = Math.max(0, Math.min(255, Math.round(r)));
        g = Math.max(0, Math.min(255, Math.round(g)));
        b = Math.max(0, Math.min(255, Math.round(b)));
        return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
    }

    function darken(hex, percent) {
        var rgb = hexToRgb(hex);
        var f = 1 - percent / 100;
        return rgbToHex(rgb.r * f, rgb.g * f, rgb.b * f);
    }

    function lighten(hex, percent) {
        var rgb = hexToRgb(hex);
        var f = percent / 100;
        return rgbToHex(rgb.r + (255 - rgb.r) * f, rgb.g + (255 - rgb.g) * f, rgb.b + (255 - rgb.b) * f);
    }

    function ultraLight(hex) {
        return mixWithWhite(hex, 92);
    }

    function mixWithWhite(hex, whitePercent) {
        var rgb = hexToRgb(hex);
        var f = whitePercent / 100;
        return rgbToHex(rgb.r + (255 - rgb.r) * f, rgb.g + (255 - rgb.g) * f, rgb.b + (255 - rgb.b) * f);
    }

    function rgba(hex, alpha) {
        var rgb = hexToRgb(hex);
        return "rgba(" + rgb.r + ", " + rgb.g + ", " + rgb.b + ", " + alpha + ")";
    }

    function isDark(hex) {
        var rgb = hexToRgb(hex);
        return (0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b) / 255 < 0.62;
    }

    // === Generate CSS Override ===
    function generateCssOverrides(brand, accent, text, bg, price, pageBg) {
        var brandDark = darken(brand, 18);
        var brandLight = lighten(brand, 35);
        var brandUltra = ultraLight(brand);
        var brandContrast = isDark(brand) ? "#ffffff" : "#000000";
        var accentDark = darken(accent, 15);
        var accentLight = lighten(accent, 30);
        var textSecondary = lighten(text, 25);
        var textMuted = lighten(text, 45);
        var surfaceSubtle = (bg === "#ffffff" || bg === "#fff") ? mixWithWhite(brand, 97) : lighten(bg, 3);
        var borderColor = mixWithWhite(brand, 85);
        var borderColorHover = mixWithWhite(brand, 75);
        var isLightNeutralAccent = accent.toLowerCase() === "#f3f4f6";
        var chromeBg = isLightNeutralAccent ? accent : bg;
        var chromeBorder = isLightNeutralAccent ? "#e5e7eb" : borderColor;
        var chromeText = isLightNeutralAccent ? "#4b5563" : text;
        var chromeHeading = isLightNeutralAccent ? "#111827" : text;

        var css = ":root {\n";
        css += "  --brandColor: " + brand + ";\n";
        css += "  --brandColorDark: " + brandDark + ";\n";
        css += "  --brandColorLight: " + brandLight + ";\n";
        css += "  --brandColorUltraLight: " + brandUltra + ";\n";
        css += "  --brandContrast: " + brandContrast + ";\n";
        css += "  --accentColor: " + accent + ";\n";
        css += "  --accentColorDark: " + accentDark + ";\n";
        css += "  --accentColorLight: " + accentLight + ";\n";
        css += "  --textPrimary: " + text + ";\n";
        css += "  --textSecondary: " + textSecondary + ";\n";
        css += "  --textMuted: " + textMuted + ";\n";
        css += "  --surfaceBase: " + bg + ";\n";
        css += "  --surfaceElevated: " + bg + ";\n";
        css += "  --surfaceSubtle: " + surfaceSubtle + ";\n";
        css += "  --borderColor: " + borderColor + ";\n";
        css += "  --borderColorHover: " + borderColorHover + ";\n";
        css += "  --chromeBg: " + chromeBg + ";\n";
        css += "  --chromeBorder: " + chromeBorder + ";\n";
        css += "  --chromeText: " + chromeText + ";\n";
        css += "  --chromeHeading: " + chromeHeading + ";\n";
        css += "  --priceColor: " + price + ";\n";
        css += "  --pageBackground: " + (pageBg || "#ffffff") + ";\n";
        css += "  --backgroundColor: " + brand + ";\n";
        css += "  --backgroundAltColor: " + brandDark + ";\n";

        var alphas = [0.06, 0.08, 0.10, 0.12, 0.14, 0.15, 0.18, 0.20, 0.22, 0.25, 0.30, 0.35];
        for (var i = 0; i < alphas.length; i++) {
            var key = (alphas[i] * 100).toString().padStart(2, "0");
            css += "  --brandAlpha" + key + ": " + rgba(brand, alphas[i]) + ";\n";
        }

        css += "  --shadowSm: 0 1px 3px " + rgba(brand, 0.08) + ";\n";
        css += "  --shadowMd: 0 4px 12px " + rgba(brand, 0.10) + ";\n";
        css += "  --shadowLg: 0 8px 24px " + rgba(brand, 0.14) + ";\n";
        css += "  --shadowHover: 0 8px 30px " + rgba(brand, 0.18) + ";\n";
        css += "}\n";
        css += "[id^='pjWrapperShoppingCart_'], #pjWrapper { color: var(--textPrimary); }\n";
        css += "body:has([id^='pjWrapperShoppingCart_']) { background-color: var(--pageBackground); }\n";
        css += "[id^='pjWrapperShoppingCart_'] .scContainer, #pjWrapper .scContainer { background-color: var(--surfaceBase); color: var(--textPrimary); }\n";
        css += "[id^='pjWrapperShoppingCart_'] a, #pjWrapper a, [id^='pjWrapperShoppingCart_'] .pjScProductName a, [id^='pjWrapperShoppingCart_'] .scProductLink { color: var(--brandColor); }\n";
        css += "[id^='pjWrapperShoppingCart_'] a:hover, #pjWrapper a:hover, [id^='pjWrapperShoppingCart_'] .pjScProductName a:hover, [id^='pjWrapperShoppingCart_'] .scProductLink:hover { color: var(--brandColorDark); }\n";
        css += "[id^='pjWrapperShoppingCart_'] .pjScBtnPrimary, [id^='pjWrapperShoppingCart_'] .btn-primary, [id^='pjWrapperShoppingCart_'] .scButtonDark, [id^='pjWrapperShoppingCart_'] .scSelectorCheckout, [id^='pjWrapperShoppingCart_'] .scSelectorAdd2Cart, [id^='pjWrapperShoppingCart_'] .scSelectorButton.pjScBtnPrimary, #pjWrapper .pjScBtnPrimary, #pjWrapper .btn-primary, #pjWrapper .scButtonDark { background-color: var(--brandColor) !important; border-color: var(--brandColor) !important; color: var(--brandContrast) !important; }\n";
        css += "[id^='pjWrapperShoppingCart_'] .pjScBtnPrimary:hover, [id^='pjWrapperShoppingCart_'] .pjScBtnPrimary:focus, [id^='pjWrapperShoppingCart_'] .btn-primary:hover, [id^='pjWrapperShoppingCart_'] .btn-primary:focus, [id^='pjWrapperShoppingCart_'] .scButtonDark:hover, [id^='pjWrapperShoppingCart_'] .scButtonDark:focus, #pjWrapper .pjScBtnPrimary:hover, #pjWrapper .btn-primary:hover, #pjWrapper .scButtonDark:hover { background-color: var(--brandColorDark) !important; border-color: var(--brandColorDark) !important; color: var(--brandContrast) !important; }\n";
        css += "[id^='pjWrapperShoppingCart_'] .pjScBtnSecondary, [id^='pjWrapperShoppingCart_'] .btn-default, [id^='pjWrapperShoppingCart_'] .scButtonAdd2Favs, [id^='pjWrapperShoppingCart_'] .scButtonSend2Friend, [id^='pjWrapperShoppingCart_'] .sc-oh-action-btn, #pjWrapper .pjScBtnSecondary, #pjWrapper .btn-default { background-color: var(--surfaceElevated) !important; border-color: var(--borderColor) !important; color: var(--brandColor) !important; }\n";
        css += "[id^='pjWrapperShoppingCart_'] .pjScBtnSecondary:hover, [id^='pjWrapperShoppingCart_'] .pjScBtnSecondary:focus, [id^='pjWrapperShoppingCart_'] .btn-default:hover, [id^='pjWrapperShoppingCart_'] .btn-default:focus, [id^='pjWrapperShoppingCart_'] .scButtonAdd2Favs:hover, [id^='pjWrapperShoppingCart_'] .scButtonSend2Friend:hover, [id^='pjWrapperShoppingCart_'] .sc-oh-action-btn:hover, #pjWrapper .pjScBtnSecondary:hover, #pjWrapper .btn-default:hover { background-color: var(--brandColorUltraLight) !important; border-color: var(--brandColor) !important; color: var(--brandColorDark) !important; }\n";
        css += "[id^='pjWrapperShoppingCart_'] .pjScBtnPrimary, [id^='pjWrapperShoppingCart_'] .btn.pjScBtnPrimary, [id^='pjWrapperShoppingCart_'] button.pjScBtnPrimary, [id^='pjWrapperShoppingCart_'] a.pjScBtnPrimary, #pjWrapper .pjScBtnPrimary, #pjWrapper .btn.pjScBtnPrimary { background-color: var(--brandColor) !important; border-color: var(--brandColor) !important; color: var(--brandContrast) !important; }\n";
        css += "[id^='pjWrapperShoppingCart_'] .pjScBtnPrimary:hover, [id^='pjWrapperShoppingCart_'] .btn.pjScBtnPrimary:hover, [id^='pjWrapperShoppingCart_'] button.pjScBtnPrimary:hover, [id^='pjWrapperShoppingCart_'] a.pjScBtnPrimary:hover, #pjWrapper .pjScBtnPrimary:hover, #pjWrapper .btn.pjScBtnPrimary:hover { background-color: var(--brandColorDark) !important; border-color: var(--brandColorDark) !important; color: var(--brandContrast) !important; }\n";
        css += "[id^='pjWrapperShoppingCart_'] .pjScBtnApply, [id^='pjWrapperShoppingCart_'] .btn-info, [id^='pjWrapperShoppingCart_'] .sc-oh-action-btn--primary, [id^='pjWrapperShoppingCart_'] .pjScBtnReorder, #pjWrapper .pjScBtnApply, #pjWrapper .btn-info { background-color: var(--accentColor) !important; border-color: var(--accentColor) !important; color: " + (isDark(accent) ? "#ffffff" : "#000000") + " !important; }\n";
        css += "[id^='pjWrapperShoppingCart_'] .pjScBtnApply:hover, [id^='pjWrapperShoppingCart_'] .btn-info:hover, [id^='pjWrapperShoppingCart_'] .sc-oh-action-btn--primary:hover, [id^='pjWrapperShoppingCart_'] .pjScBtnReorder:hover, #pjWrapper .pjScBtnApply:hover, #pjWrapper .btn-info:hover { background-color: var(--accentColorDark) !important; border-color: var(--accentColorDark) !important; }\n";
        css += "[id^='pjWrapperShoppingCart_'] .pjScBtnLink, [id^='pjWrapperShoppingCart_'] .btn-link, #pjWrapper .pjScBtnLink, #pjWrapper .btn-link { color: var(--brandColor) !important; }\n";
        css += "[id^='pjWrapperShoppingCart_'] .navbar-default, [id^='pjWrapperShoppingCart_'] .pjScHeader, [id^='pjWrapperShoppingCart_'] .scContainer .pjScHeader, #pjWrapper .navbar-default, #pjWrapper .pjScHeader, #pjWrapper .scContainer .pjScHeader { background-color: var(--chromeBg) !important; border-color: var(--chromeBorder) !important; color: var(--chromeText) !important; }\n";
        css += "[id^='pjWrapperShoppingCart_'] .scContainer .pjScHeader .scStoreName, [id^='pjWrapperShoppingCart_'] .scContainer .pjScHeader a, #pjWrapper .scContainer .pjScHeader .scStoreName, #pjWrapper .scContainer .pjScHeader a { color: var(--chromeText) !important; }\n";
        css += "[id^='pjWrapperShoppingCart_'] .scContainer .pjScHeader .scStoreName, #pjWrapper .scContainer .pjScHeader .scStoreName { color: var(--chromeHeading) !important; }\n";
        css += "[id^='pjWrapperShoppingCart_'] .scContainer .pjScHeader .scStoreName:hover, [id^='pjWrapperShoppingCart_'] .scContainer .pjScHeader a:hover, #pjWrapper .scContainer .pjScHeader .scStoreName:hover, #pjWrapper .scContainer .pjScHeader a:hover { background-color: transparent !important; color: var(--brandColor) !important; }\n";
        css += "[id^='pjWrapperShoppingCart_'] .scContainer .scSearchForm, [id^='pjWrapperShoppingCart_'] .scContainer .btn-group.pull-right, #pjWrapper .scContainer .scSearchForm, #pjWrapper .scContainer .btn-group.pull-right { border-color: var(--chromeBorder) !important; background-color: var(--surfaceElevated) !important; }\n";
        css += "[id^='pjWrapperShoppingCart_'] .scContainer .scSearchForm .input-group-btn .btn, #pjWrapper .scContainer .scSearchForm .input-group-btn .btn { background-color: var(--surfaceElevated) !important; border-color: var(--chromeBorder) !important; color: var(--chromeText) !important; }\n";
        css += ":is(#pjWrapperShoppingCart_1,#pjWrapperShoppingCart_2,#pjWrapperShoppingCart_3,#pjWrapperShoppingCart_4,#pjWrapperShoppingCart_5) .scContainer .scSearchForm .input-group-btn .btn { background-color: var(--surfaceElevated) !important; border-color: var(--chromeBorder) !important; color: var(--chromeText) !important; }\n";
        css += "[id^='pjWrapperShoppingCart_'] .scContainer .scSearchForm .input-group-btn .btn:hover, #pjWrapper .scContainer .scSearchForm .input-group-btn .btn:hover { background-color: var(--surfaceElevated) !important; color: var(--brandColor) !important; }\n";
        css += "[id^='pjWrapperShoppingCart_'] .scContainer .btn-group.pull-right .btn, #pjWrapper .scContainer .btn-group.pull-right .btn { color: var(--chromeText) !important; background-color: transparent !important; }\n";
        css += "[id^='pjWrapperShoppingCart_'] .scContainer .btn-group.pull-right .btn strong, [id^='pjWrapperShoppingCart_'] .scContainer .btn-group.pull-right .btn .text-warning, #pjWrapper .scContainer .btn-group.pull-right .btn strong, #pjWrapper .scContainer .btn-group.pull-right .btn .text-warning { color: var(--chromeHeading) !important; }\n";
        css += "[id^='pjWrapperShoppingCart_'] .navbar-default .navbar-nav > .active > a, [id^='pjWrapperShoppingCart_'] .navbar-default .navbar-nav > .active > a:hover, [id^='pjWrapperShoppingCart_'] .navbar-default .navbar-nav > .active > a:focus, #pjWrapper .navbar-default .navbar-nav > .active > a { background-color: var(--brandColorUltraLight); color: var(--brandColorDark); }\n";
        css += "[id^='pjWrapperShoppingCart_'] .dropdown-menu > .active > a, [id^='pjWrapperShoppingCart_'] .dropdown-menu > .active > a:hover, [id^='pjWrapperShoppingCart_'] .dropdown-menu > li > a:hover, #pjWrapper .dropdown-menu > .active > a, #pjWrapper .dropdown-menu > li > a:hover { background-color: var(--brandColorUltraLight); color: var(--brandColorDark); }\n";
        css += "[id^='pjWrapperShoppingCart_'] .panel, [id^='pjWrapperShoppingCart_'] .table, [id^='pjWrapperShoppingCart_'] .sc-oh-card, [id^='pjWrapperShoppingCart_'] .sc-oh-table, #pjWrapper .panel, #pjWrapper .table { background-color: var(--surfaceElevated); border-color: var(--borderColor); color: var(--textPrimary); }\n";
        css += "[id^='pjWrapperShoppingCart_'] .panel-heading, [id^='pjWrapperShoppingCart_'] .table > thead > tr > th, [id^='pjWrapperShoppingCart_'] .sc-oh-table thead th, #pjWrapper .panel-heading, #pjWrapper .table > thead > tr > th { background-color: var(--surfaceSubtle); border-color: var(--borderColor); color: var(--textPrimary); }\n";
        css += "[id^='pjWrapperShoppingCart_'] .table > tbody > tr > td, [id^='pjWrapperShoppingCart_'] .table > tfoot > tr > td, [id^='pjWrapperShoppingCart_'] .sc-oh-table td, #pjWrapper .table > tbody > tr > td, #pjWrapper .table > tfoot > tr > td { border-color: var(--borderColor); }\n";
        css += "[id^='pjWrapperShoppingCart_'] .form-control, #pjWrapper .form-control { background-color: var(--surfaceElevated); border-color: var(--borderColor); color: var(--textPrimary); }\n";
        css += "[id^='pjWrapperShoppingCart_'] .form-control:focus, #pjWrapper .form-control:focus { border-color: var(--brandColor); box-shadow: 0 0 0 3px var(--brandAlpha15); }\n";
        css += "[id^='pjWrapperShoppingCart_'] .input-group-addon, #pjWrapper .input-group-addon { background-color: var(--surfaceSubtle); border-color: var(--borderColor); color: var(--brandColor); }\n";
        css += "[id^='pjWrapperShoppingCart_'] .scSelectorPrice, [id^='pjWrapperShoppingCart_'] .pjScProductPrice, [id^='pjWrapperShoppingCart_'] .scProductPrice, [id^='pjWrapperShoppingCart_'] .sc-oh-total, #pjWrapper .scSelectorPrice, #pjWrapper .pjScProductPrice, #pjWrapper .scProductPrice { color: var(--priceColor) !important; }\n";
        css += "[id^='pjWrapperShoppingCart_'] .label-primary, [id^='pjWrapperShoppingCart_'] .badge, [id^='pjWrapperShoppingCart_'] .sc-product-badge, [id^='pjWrapperShoppingCart_'] .sc-oh-status, #pjWrapper .label-primary, #pjWrapper .badge { background-color: var(--brandColor) !important; color: var(--brandContrast) !important; }\n";
        css += "[id^='pjWrapperShoppingCart_'] .nav-tabs > li.active > a, [id^='pjWrapperShoppingCart_'] .nav-tabs > li.active > a:hover, [id^='pjWrapperShoppingCart_'] .nav-tabs > li.active > a:focus, #pjWrapper .nav-tabs > li.active > a { color: var(--brandColor); border-color: var(--borderColor); border-bottom-color: var(--surfaceElevated); }\n";
        css += "[id^='pjWrapperShoppingCart_'] .pagination > .active > a, [id^='pjWrapperShoppingCart_'] .pagination > .active > span, #pjWrapper .pagination > .active > a, #pjWrapper .pagination > .active > span { background-color: var(--brandColor); border-color: var(--brandColor); color: var(--brandContrast); }\n";
        css += "[id^='pjWrapperShoppingCart_'] .scSelectorRemoveFromCart, [id^='pjWrapperShoppingCart_'] .scSelectorRemoveFromFavs, #pjWrapper .scSelectorRemoveFromCart, #pjWrapper .scSelectorRemoveFromFavs { color: var(--accentColor) !important; }\n";
        css += "[id^='pjWrapperShoppingCart_'] .alert-info, #pjWrapper .alert-info { background-color: var(--brandColorUltraLight); border-color: var(--borderColor); color: var(--brandColorDark); }\n";
        css += "[id^='pjWrapperShoppingCart_'] .text-danger, [id^='pjWrapperShoppingCart_'] .alert-danger, #pjWrapper .text-danger, #pjWrapper .alert-danger { color: #b91c1c; }\n";

        return css;
    }

    // === Randomizer ===
    var availableFonts = ["Inter", "Poppins", "Roboto", "Open Sans", "Lato", "Montserrat", "Nunito", "Raleway", "Source Sans 3", "DM Sans"];

    function hslToHex(h, s, l) {
        h = h / 360; s = s / 100; l = l / 100;
        var r, g, b;
        if (s === 0) { r = g = b = l; } else {
            var hue2rgb = function (p, q, t) {
                if (t < 0) t += 1; if (t > 1) t -= 1;
                if (t < 1/6) return p + (q - p) * 6 * t;
                if (t < 1/2) return q;
                if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
                return p;
            };
            var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
            var p = 2 * l - q;
            r = hue2rgb(p, q, h + 1/3);
            g = hue2rgb(p, q, h);
            b = hue2rgb(p, q, h - 1/3);
        }
        return rgbToHex(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255));
    }

    function randomBetween(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    function generateRandomPalette() {
        // Random strategy: complementary, triadic, analogous, or split-complementary
        var strategies = ["complementary", "triadic", "analogous", "split"];
        var strategy = strategies[Math.floor(Math.random() * strategies.length)];

        var brandHue = randomBetween(0, 359);
        var brandSat = randomBetween(55, 85);
        var brandLight = randomBetween(38, 55);

        var accentHue;
        switch (strategy) {
            case "complementary":
                accentHue = (brandHue + 180 + randomBetween(-20, 20)) % 360;
                break;
            case "triadic":
                accentHue = (brandHue + (Math.random() > 0.5 ? 120 : 240) + randomBetween(-15, 15)) % 360;
                break;
            case "analogous":
                accentHue = (brandHue + (Math.random() > 0.5 ? 30 : -30) + randomBetween(-10, 10)) % 360;
                break;
            case "split":
                accentHue = (brandHue + (Math.random() > 0.5 ? 150 : 210) + randomBetween(-10, 10)) % 360;
                break;
        }
        if (accentHue < 0) accentHue += 360;

        var accentSat = randomBetween(60, 90);
        var accentLight = randomBetween(42, 58);

        var brand = hslToHex(brandHue, brandSat, brandLight);
        var accent = hslToHex(accentHue, accentSat, accentLight);
        var text = "#1a1a2e";
        var bg = "#ffffff";
        // Price: sometimes brand, sometimes accent
        var price = Math.random() > 0.3 ? brand : accent;

        return { brand: brand, accent: accent, text: text, bg: bg, price: price };
    }

    // === Get Current Values ===
    function getValues() {
        return {
            brand: $("#brandColor").val(),
            accent: $("#accentColor").val(),
            text: $("#textColor").val(),
            bg: $("#bgColor").val(),
            price: $("#priceColor").val(),
            pageBg: $("#pageBgColor").val() || "#ffffff",
            font: $("#fontFamily").val()
        };
    }

    // === Update Preview ===
    var previewTimeout;
    function applyPreviewInteractionGuard(iframeDoc) {
        var guardId = "pj-preview-interaction-guard";
        var guard = iframeDoc.getElementById(guardId);
        if (!guard) {
            guard = iframeDoc.createElement("style");
            guard.id = guardId;
            iframeDoc.head.appendChild(guard);
        }
        guard.textContent = [
            ".pjScProductImages,",
            ".pjScProductNamePrice,",
            ".pjScProductGallery .scSelectorFancy,",
            ".pjScProductGallery .scSelectorProductThumb,",
            ".scProductGallery .scSelectorFancy,",
            ".scProductThumbs,",
            ".owl-carousel,",
            ".owl-nav { pointer-events: none !important; }",
            ".pjScProductDefaultGalleryImage { display: block !important; }",
            ".owl-nav { display: none !important; }",
            ".owl-carousel-hidden { display: none !important; }"
        ].join("\n");
    }

    function updatePreview() {
        clearTimeout(previewTimeout);
        previewTimeout = setTimeout(function () {
            var v = getValues();
            try {
                var iframeDoc = document.getElementById("pjPreviewFrame").contentDocument ||
                                document.getElementById("pjPreviewFrame").contentWindow.document;
                applyPreviewInteractionGuard(iframeDoc);

                // Inject or update style tag
                var styleId = "pj-dynamic-theme";
                var existing = iframeDoc.getElementById(styleId);
                if (!existing) {
                    existing = iframeDoc.createElement("style");
                    existing.id = styleId;
                    iframeDoc.head.appendChild(existing);
                }
                existing.textContent = generateCssOverrides(v.brand, v.accent, v.text, v.bg, v.price, v.pageBg);

                // Font
                if (v.font) {
                    var fontLinkId = "pj-google-font";
                    var fontLink = iframeDoc.getElementById(fontLinkId);
                    if (!fontLink) {
                        fontLink = iframeDoc.createElement("link");
                        fontLink.id = fontLinkId;
                        fontLink.rel = "stylesheet";
                        iframeDoc.head.appendChild(fontLink);
                    }
                    fontLink.href = "https://fonts.googleapis.com/css2?family=" + encodeURIComponent(v.font) + ":wght@400;500;600;700&display=swap";

                    // Apply font to wrapper
                    var fontStyle = iframeDoc.getElementById("pj-font-override");
                    if (!fontStyle) {
                        fontStyle = iframeDoc.createElement("style");
                        fontStyle.id = "pj-font-override";
                        iframeDoc.head.appendChild(fontStyle);
                    }
                    fontStyle.textContent = "[id^='pjWrapperShoppingCart_'], [id^='pjWrapperShoppingCart_'] * { font-family: '" + v.font + "', sans-serif !important; }"
                        + "[id^='pjWrapperShoppingCart_'] .fa, [id^='pjWrapperShoppingCart_'] .fa:before, [id^='pjWrapperShoppingCart_'] .fa:after { font-family: FontAwesome !important; }"
                        + "[id^='pjWrapperShoppingCart_'] .glyphicon, [id^='pjWrapperShoppingCart_'] .glyphicon:before, [id^='pjWrapperShoppingCart_'] .glyphicon:after { font-family: 'Glyphicons Halflings' !important; }";
                } else {
                    // Remove font overrides
                    var iframeHead = iframeDoc.head;
                    var fontLink = iframeDoc.getElementById("pj-google-font");
                    if (fontLink) iframeHead.removeChild(fontLink);
                    var fontStyle = iframeDoc.getElementById("pj-font-override");
                    if (fontStyle) iframeHead.removeChild(fontStyle);
                }
            } catch (e) {
                // Cross-origin or iframe not ready
            }
        }, 50);
    }

    // === Render Palettes ===
    function renderPalettes() {
        var $container = $("#pjPalettes");
        var currentPalette = $("#pjCurrentPalette").val();

        for (var i = 0; i < palettes.length; i++) {
            var p = palettes[i];
            var isActive = (p.id === currentPalette) ? " active" : "";
            var html = '<div class="pj-palette-card' + isActive + '" data-palette="' + p.id + '">' +
                '<div class="pj-palette-name">' + p.name + '</div>' +
                '<div class="pj-palette-swatches">' +
                    '<div class="pj-palette-swatch" style="background:' + p.brand + '"></div>' +
                    '<div class="pj-palette-swatch" style="background:' + p.accent + '"></div>' +
                    '<div class="pj-palette-swatch" style="background:' + p.text + '"></div>' +
                    '<div class="pj-palette-swatch" style="background:' + p.bg + ';border-color:#ccc"></div>' +
                    '<div class="pj-palette-swatch" style="background:' + p.price + '"></div>' +
                '</div></div>';
            $container.append(html);
        }
    }

    // === Detect Active Palette ===
    function detectActivePalette() {
        var v = getValues();
        var found = "0";
        for (var i = 0; i < palettes.length; i++) {
            var p = palettes[i];
            if (v.brand.toLowerCase() === p.brand.toLowerCase() &&
                v.accent.toLowerCase() === p.accent.toLowerCase() &&
                v.text.toLowerCase() === p.text.toLowerCase() &&
                v.bg.toLowerCase() === p.bg.toLowerCase() &&
                v.price.toLowerCase() === p.price.toLowerCase() &&
                v.pageBg.toLowerCase() === p.pageBg.toLowerCase()) {
                found = p.id;
                break;
            }
        }
        $(".pj-palette-card").removeClass("active");
        $(".pj-palette-card[data-palette='" + found + "']").addClass("active");
        $("#pjCurrentPalette").val(found);
    }

    // === Sync hex input ↔ color input ===
    function syncColorInputs(colorId, hexId) {
        $("#" + colorId).on("input", function () {
            $("#" + hexId).val(this.value);
            detectActivePalette();
            updatePreview();
        });
        $("#" + hexId).on("input", function () {
            var val = this.value;
            if (/^#[0-9a-fA-F]{6}$/.test(val)) {
                $("#" + colorId).val(val);
                detectActivePalette();
                updatePreview();
            }
        });
    }

    // === Init ===
    $(function () {
        renderPalettes();

        // Sync color pickers with hex inputs
        syncColorInputs("brandColor", "brandColorHex");
        syncColorInputs("accentColor", "accentColorHex");
        syncColorInputs("textColor", "textColorHex");
        syncColorInputs("bgColor", "bgColorHex");
        syncColorInputs("priceColor", "priceColorHex");
        syncColorInputs("pageBgColor", "pageBgColorHex");

        // Palette click
        $(document).on("click", ".pj-palette-card", function () {
            var paletteId = $(this).data("palette");
            var palette = null;
            for (var i = 0; i < palettes.length; i++) {
                if (palettes[i].id === String(paletteId)) { palette = palettes[i]; break; }
            }
            if (!palette) return;

            // Set color pickers
            $("#brandColor").val(palette.brand);
            $("#brandColorHex").val(palette.brand);
            $("#accentColor").val(palette.accent);
            $("#accentColorHex").val(palette.accent);
            $("#textColor").val(palette.text);
            $("#textColorHex").val(palette.text);
            $("#bgColor").val(palette.bg);
            $("#bgColorHex").val(palette.bg);
            $("#priceColor").val(palette.price);
            $("#priceColorHex").val(palette.price);
            $("#pageBgColor").val(palette.pageBg);
            $("#pageBgColorHex").val(palette.pageBg);

            $(".pj-palette-card").removeClass("active");
            $(this).addClass("active");
            $("#pjCurrentPalette").val(paletteId);
            updatePreview();
        });

        // Reset buttons
        $(document).on("click", ".pj-color-reset", function () {
            var target = $(this).data("target");
            var def = $(this).data("default");
            $("#" + target).val(def);
            $("#" + target + "Hex").val(def);
            detectActivePalette();
            updatePreview();
        });

        // Font change
        $("#fontFamily").on("change", function () {
            updatePreview();
        });

        // Randomizer
        $("#pjRandomize").on("click", function () {
            var $btn = $(this);
            $btn.addClass("pj-spinning");
            setTimeout(function () { $btn.removeClass("pj-spinning"); }, 500);

            var p = generateRandomPalette();

            // Smooth transition on color inputs
            $(".pj-color-input, .pj-color-hex").css("transition", "all 0.3s");

            $("#brandColor").val(p.brand);
            $("#brandColorHex").val(p.brand);
            $("#accentColor").val(p.accent);
            $("#accentColorHex").val(p.accent);
            $("#textColor").val(p.text);
            $("#textColorHex").val(p.text);
            $("#bgColor").val(p.bg);
            $("#bgColorHex").val(p.bg);
            $("#priceColor").val(p.price);
            $("#priceColorHex").val(p.price);

            // Random font if checkbox is checked
            if ($("#pjRandomFont").is(":checked")) {
                var randomFont = availableFonts[Math.floor(Math.random() * availableFonts.length)];
                $("#fontFamily").val(randomFont);
            }

            detectActivePalette();
            updatePreview();
        });

        // Device preview
        $(".pj-device-btn[data-width]").on("click", function () {
            $(".pj-device-btn").removeClass("active");
            $(this).addClass("active");
            var width = $(this).data("width");
            $("#pjPreviewFrame").css({
                "max-width": width,
                "margin": width === "100%" ? "0" : "0 auto",
                "display": "block"
            });
        });

        // Save
        $("#pjSaveTheme").on("click", function () {
            var $btn = $(this);
            $btn.prop("disabled", true).html('<i class="fa fa-spinner fa-spin m-r-xs"></i> Saving...');

            var v = getValues();
            $.ajax({
                url: $("#pjSaveUrl").val(),
                type: "POST",
                dataType: "json",
                data: {
                    csrf_token: $("#pjThemeCsrfToken").val() || getCsrfToken(),
                    o_brand_color: v.brand,
                    o_accent_color: v.accent,
                    o_text_color: v.text,
                    o_background_color: v.bg,
                    o_price_color: v.price,
                    o_page_background_color: v.pageBg,
                    o_font_family: v.font,
                    o_color_palette: $("#pjCurrentPalette").val()
                },
                success: function (resp) {
                    $btn.prop("disabled", false).html('<i class="fa fa-check m-r-xs"></i> Save');
                    if (resp && resp.status === "OK") {
                        $("#pjSaveMsg").text("Saved!").fadeIn().delay(2000).fadeOut();
                    } else {
                        $("#pjSaveMsg").text("Save failed").css("color", "#e74c3c").fadeIn().delay(3000).fadeOut();
                    }
                },
                error: function () {
                    $btn.prop("disabled", false).html('<i class="fa fa-check m-r-xs"></i> Save');
                    $("#pjSaveMsg").text("Save failed").css("color", "#e74c3c").fadeIn().delay(3000).fadeOut();
                }
            });
        });

        // Initial palette detection
        detectActivePalette();

        // Initial preview update after iframe loads
        $("#pjPreviewFrame").on("load", function () {
            updatePreview();
        });
    });

})(jQuery);
