
(function () {
    function formatGmt6Timestamp() {
        var now = new Date();
        var offsetMs = -6 * 60 * 60 * 1000;
        var d = new Date(now.getTime() + offsetMs);
        function pad(n) { return (n < 10) ? ("0" + n) : String(n); }
        return d.getUTCFullYear() + "-" + pad(d.getUTCMonth() + 1) + "-" + pad(d.getUTCDate()) +
            " " + pad(d.getUTCHours()) + ":" + pad(d.getUTCMinutes()) + ":" + pad(d.getUTCSeconds()) + " GMT-06";
    }

    var loggerAvailable = false;
    
    var detectedProduction = false;
    try {
        var testLoggerPath = ($.global.PRLB_SCRIPT_DIR || "").replace(/\\/g, "/") + "/lib/00_logger.jsxbin";
        if (!testLoggerPath || testLoggerPath === "/lib/00_logger.jsxbin") {
            if ($.fileName) {
                var testFile = new File($.fileName);
                if (testFile.exists) {
                    testLoggerPath = testFile.parent.fsName.replace(/\\/g, "/") + "/lib/00_logger.jsxbin";
                }
            }
        }
        if (testLoggerPath && testLoggerPath !== "/lib/00_logger.jsxbin") {
            var testLoggerFile = new File(testLoggerPath);
            detectedProduction = testLoggerFile.exists;
        }
    } catch (e) {
    }
    
    function earlyLog(message) {
        if (loggerAvailable && typeof prlbLogger !== "undefined") {
            prlbLogger.log("SWATCH_LOADER", "DEBUG", message);
            return;
        }
        if (detectedProduction || ($.global && $.global.PRLB_PRODUCTION === true)) {
            return; // Skip early DEBUG logging in production
        }
        try {
            $.writeln("[SWATCH_LOADER][DEBUG][" + formatGmt6Timestamp() + "] " + message);
        } catch (e) {
        }
    }

    earlyLog("=== SWATCH_PANEL_LOADER STARTING ===");
    earlyLog("$.fileName: " + ($.fileName || "undefined"));
    earlyLog("PRLB_SCRIPT_DIR: " + ($.global.PRLB_SCRIPT_DIR || "undefined"));

    var scriptDirPath = null;

    if ($.global.PRLB_SCRIPT_DIR && $.global.PRLB_SCRIPT_DIR !== "") {
        scriptDirPath = $.global.PRLB_SCRIPT_DIR.replace(/\\/g, "/");
        earlyLog("Using PRLB_SCRIPT_DIR: " + scriptDirPath);
    }

    if (!scriptDirPath && $.fileName && $.fileName !== "") {
        try {
            var scriptFile = new File($.fileName);
            if (scriptFile.exists) {
                scriptDirPath = scriptFile.parent.fsName.replace(/\\/g, "/");
                earlyLog("Using $.fileName parent: " + scriptDirPath);
            } else {
                earlyLog("$.fileName file does not exist: " + $.fileName);
            }
        } catch (e) {
            earlyLog("Error reading $.fileName: " + e.toString());
        }
    }

    if (!scriptDirPath) {
        earlyLog("ERROR: Cannot determine script directory");
        alert("Error: Cannot determine script directory for SwatchesSettingsLauncher.jsx.\n\n" +
            "Please ensure the script is loaded correctly from ProofLab.jsx.\n\n" +
            "Current $.fileName: " + ($.fileName || "undefined") + "\n" +
            "PRLB_SCRIPT_DIR: " + ($.global.PRLB_SCRIPT_DIR || "undefined"));
        return;
    }

    earlyLog("Final scriptDirPath: " + scriptDirPath);

    var modules = [
        "lib/00_logger",
        "lib/06_versioning",
        "lib/01_json_polyfill",
        "lib/i18n/en_us",
        "lib/i18n/es_hn",
        "lib/07_i18n",
        "lib/05_security", // <-- ADDED FOR SECURITY
        "lib/02_settings",
        "lib/ColorChipsLibrary",  // Load BEFORE SwatchGenerator (dependency)
        "lib/SwatchGenerator"
    ];

    var isProduction = true;

    earlyLog("Building scriptDirFile from: " + scriptDirPath);
    var scriptDirFile = new File(scriptDirPath.replace(/\//g, "\\"));
    earlyLog("scriptDirFile (backslashes) exists: " + scriptDirFile.exists + ", fsName: " + scriptDirFile.fsName);

    if (!scriptDirFile.exists) {
        scriptDirFile = new File(scriptDirPath);
        earlyLog("scriptDirFile (forward slashes) exists: " + scriptDirFile.exists + ", fsName: " + scriptDirFile.fsName);
    }

    if (!scriptDirFile.exists) {
        earlyLog("ERROR: scriptDirFile does not exist!");
        alert("Error: Script directory does not exist.\n\n" +
            "Script directory: " + scriptDirPath + "\n\n" +
            "Please check the path is correct.");
        return;
    }

    earlyLog("Using scriptDirFile.fsName: " + scriptDirFile.fsName);
    earlyLog("Loading " + modules.length + " module(s)...");

    for (var i = 0; i < modules.length; i++) {
        earlyLog("--- Loading module " + (i + 1) + "/" + modules.length + ": " + modules[i] + " ---");

        var moduleBin = new File(scriptDirPath + "/" + modules[i] + ".jsxbin");
        var moduleJsx = new File(scriptDirPath + "/" + modules[i] + ".jsx");
        
        var moduleFile = null;
        if (moduleBin.exists) {
            moduleFile = moduleBin;
            earlyLog("  Found .jsxbin: " + moduleBin.fsName);
        } else if (moduleJsx.exists) {
            moduleFile = moduleJsx;
            isProduction = false; // Using .jsx = dev mode
            earlyLog("  Found .jsx (fallback): " + moduleJsx.fsName);
        } else {
            earlyLog("  ERROR: Neither .jsxbin nor .jsx found");
            alert("Error: Required module not found.\n\n" +
                "Missing: " + modules[i] + "\n\n" +
                "Tried:\n" +
                "  - " + moduleBin.fsName + "\n" +
                "  - " + moduleJsx.fsName + "\n\n" +
                "No JSXBIN files found. Please contact your administrator.");
            return;
        }

        earlyLog("  Attempting to load module...");

        try {
            $.evalFile(moduleFile);
            earlyLog("  ✓ Module loaded successfully");

            if (modules[i] === "lib/00_logger" && typeof prlbLogger !== "undefined") {
                loggerAvailable = true;
                prlbLogger.log("SWATCH_LOADER", "INFO", "Logger module loaded, switching to prlbLogger");
            }
        } catch (e) {
            earlyLog("  ✗ ERROR loading module: " + e.toString());
            alert("Error loading module: " + modules[i] + "\n\n" +
                "Path: " + moduleFile.fsName + "\n\n" +
                "Error: " + e.toString());
            return;
        }
    }

    $.global.PRLB_PRODUCTION = isProduction;

    earlyLog("All modules loaded successfully");

    var securityResult = security.check();
    if (!securityResult.ok) {
        security.showActivationError(securityResult.machineID);
        prlbLogger.log("SECURITY", "WARN", "Access denied (Swatches Panel) - Machine ID: " + securityResult.machineID);
        return;
    }
    prlbLogger.log("SECURITY", "INFO", "License check passed (Swatches Panel) - Machine ID: " + securityResult.machineID);

    var licenseRole = "UNKNOWN";
    if (typeof security !== "undefined" && security.getRoleFromLicense) {
        licenseRole = security.getRoleFromLicense();
    }

    var devModeActive = false;
    if (typeof security !== "undefined" && security.checkDevelopmentMode) {
        devModeActive = security.checkDevelopmentMode();
    }

    var uiMode = "USER"; // Default to USER for safety
    if (devModeActive) {
        uiMode = "ADMIN"; // Dev mode gets full access
    } else if (licenseRole === "ADMIN") {
        uiMode = "ADMIN";
    } else {
        uiMode = "USER"; // USER or unknown -> USER mode
    }

    $.global.PRLB_MODE = uiMode;
    prlbLogger.log("SWATCH_LOADER", "INFO", "UI Mode: " + $.global.PRLB_MODE + " (License Role: " + licenseRole + (devModeActive ? ", Dev Mode Active" : "") + ")");

    earlyLog("--- Loading SwatchesSettings ---");

    var swatchPanelBin = new File(scriptDirPath + "/SwatchesSettings.jsxbin");
    var swatchPanelJsx = new File(scriptDirPath + "/SwatchesSettings.jsx");
    
    var swatchPanelFile = null;
    if (swatchPanelBin.exists) {
        swatchPanelFile = swatchPanelBin;
        earlyLog("  Found .jsxbin: " + swatchPanelBin.fsName);
    } else if (swatchPanelJsx.exists) {
        swatchPanelFile = swatchPanelJsx;
        $.global.PRLB_PRODUCTION = false; // Using .jsx = dev mode
        earlyLog("  Found .jsx (fallback): " + swatchPanelJsx.fsName);
    } else {
        earlyLog("ERROR: SwatchesSettings not found");
        alert("Error: SwatchesSettings script not found.\n\n" +
            "Tried:\n" +
            "  - " + swatchPanelBin.fsName + "\n" +
            "  - " + swatchPanelJsx.fsName + "\n\n" +
            "No JSXBIN files found. Please contact your administrator.");
        return;
    }

    earlyLog("  Attempting to load swatch settings...");

    try {
        $.evalFile(swatchPanelFile);
        earlyLog("✓ SwatchesSettings loaded successfully");

        if (typeof prlbLogger !== "undefined") {
            prlbLogger.log("SWATCH_LOADER", "INFO", "Swatch settings loader completed successfully");
        }
    } catch (e) {
        earlyLog("✗ ERROR loading swatch settings: " + e.toString());
        if (typeof prlbLogger !== "undefined") {
            prlbLogger.log("SWATCH_LOADER", "ERROR", "Failed to load swatch settings: " + e.toString());
        }
        alert("Error loading swatch settings: " + e.toString());
        return;
    }

    earlyLog("=== SWATCH_SETTINGS_LOADER COMPLETE ===");
})();
