// ============================================
// Brand Manager - ScriptUI Panel (Ultra Simple)
// ============================================

#target aftereffects

// ========== متغيرات عامة ==========
var SAVE_FILE = new File(Folder.userData.fsName + "/BrandManager_Data.json");
var BRANDS = [];

// ========== دوال الحفظ ==========
function saveData() {
    try {
        var f = new File(SAVE_FILE.fsName);
        f.encoding = "UTF-8";
        f.open("w");
        f.write(BRANDS.toSource());
        f.close();
    } catch(e) {}
}

function loadData() {
    try {
        var f = new File(SAVE_FILE.fsName);
        if (f.exists) {
            f.encoding = "UTF-8";
            f.open("r");
            var content = f.read();
            f.close();
            if (content && content.length > 0) {
                BRANDS = eval(content);
            }
        }
    } catch(e) {
        alert("Load Error (old save file may be corrupted, resetting): " + e.toString());
        BRANDS = [];
    }
}

// ========== دوال مساعدة ==========
function trimStr(s) {
    if (s === null || s === undefined) return "";
    return String(s).replace(/^\s+|\s+$/g, "");
}

function jsonEscape(s) {
    s = String(s);
    return s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
}

function brandsToJSON(brands) {
    var parts = [];
    for (var i = 0; i < brands.length; i++) {
        var b = brands[i];
        var colorParts = [];
        for (var j = 0; j < b.colors.length; j++) {
            colorParts.push('"' + jsonEscape(b.colors[j]) + '"');
        }
        parts.push('  {"name":"' + jsonEscape(b.name) + '","colors":[' + colorParts.join(",") + '],"logo":"' + jsonEscape(b.logo || "") + '"}');
    }
    return "[\n" + parts.join(",\n") + "\n]";
}

function hexToRGB(hex) {
    hex = hex.replace("#", "").replace(/ /g, "");
    if (hex.length === 3) {
        hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
    }
    var r = parseInt(hex.substr(0, 2), 16) / 255;
    var g = parseInt(hex.substr(2, 2), 16) / 255;
    var b = parseInt(hex.substr(4, 2), 16) / 255;
    return [r, g, b, 1];
}

function applyColor(hex) {
    var comp = app.project.activeItem;
    if (!comp || !(comp instanceof CompItem)) {
        alert("Open a Comp first!");
        return;
    }
    if (comp.selectedLayers.length === 0) {
        alert("Select a layer first!");
        return;
    }
    
    app.beginUndoGroup("Apply Fill Color");
    try {
        var rgb = hexToRGB(hex);
        var layer = comp.selectedLayers[0];
        var effects = layer.property("ADBE Effect Parade");
        var fill = effects.addProperty("ADBE Fill");
        fill.property("Color").setValue(rgb);
    } catch(e) {
        alert("Error: " + e);
    }
    app.endUndoGroup();
}

function applyLogo(path) {
    var comp = app.project.activeItem;
    if (!comp || !(comp instanceof CompItem)) {
        alert("Open a Comp first!");
        return;
    }
    
    app.beginUndoGroup("Apply Logo");
    try {
        var file = new File(path);
        if (!file.exists) {
            alert("File not found!");
            app.endUndoGroup();
            return;
        }
        var importOptions = new ImportOptions(file);
        var footage = app.project.importFile(importOptions);
        var layer = comp.layers.add(footage);
        layer.name = "Brand Logo";
        layer.property("Position").setValue([comp.width / 2, comp.height / 2]);
    } catch(e) {
        alert("Error: " + e);
    }
    app.endUndoGroup();
}

function removeAllEffects() {
    var comp = app.project.activeItem;
    if (!comp || !(comp instanceof CompItem)) {
        alert("Open a Comp first!");
        return;
    }
    if (comp.selectedLayers.length === 0) {
        alert("Select a layer first!");
        return;
    }
    
    app.beginUndoGroup("Remove All Effects");
    try {
        var layer = comp.selectedLayers[0];
        var effects = layer.property("ADBE Effect Parade");
        for (var i = effects.numProperties; i >= 1; i--) {
            effects.property(i).remove();
        }
    } catch(e) {
        alert("Error: " + e);
    }
    app.endUndoGroup();
}

function copyToClipboard(text) {
    try {
        var w = new Window("dialog", "Copy Color Code");
        w.orientation = "column";
        w.alignChildren = ["fill", "top"];
        w.margins = 14;
        w.spacing = 8;
        
        w.add("statictext", undefined, "الكود جاهز ومحدّد، بس اضغط Ctrl+C:");
        
        var et = w.add("edittext", undefined, text);
        et.preferredSize.width = 200;
        
        var okBtn = w.add("button", undefined, "OK", {name: "ok"});
        okBtn.onClick = function() { w.close(); };
        
        w.onShow = function() {
            et.active = true;
            et.textselection = text;
        };
        
        w.show();
    } catch(e) {
        alert("Copy Error: " + e.toString() + "\nCode: " + text);
    }
}

// ========== بناء الـ Panel ==========
function buildUI(thisObj) {
    var win = (thisObj instanceof Panel) ? thisObj : new Window("palette", "Brand Manager", undefined, {resizeable: true});
    win.orientation = "column";
    win.alignChildren = ["fill", "top"];
    win.spacing = 6;
    win.margins = 10;
    
    // عنوان
    win.add("statictext", undefined, "BRAND MANAGER").justify = "center";
    
    // === قسم الإضافة ===
    var addP = win.add("panel", undefined, "Add New Brand");
    addP.orientation = "column";
    addP.alignChildren = ["fill", "top"];
    addP.margins = 8;
    
    // Name
    var g1 = addP.add("group");
    g1.orientation = "row";
    g1.add("statictext", undefined, "Name:").preferredSize.width = 40;
    var nameField = g1.add("edittext", undefined, "");
    nameField.preferredSize.width = 138;
    var addBtn = g1.add("button", undefined, "ADD");
    addBtn.preferredSize.width = 42;
    
    // Colors
    var g2 = addP.add("group");
    g2.orientation = "row";
    g2.add("statictext", undefined, "Colors:").preferredSize.width = 40;
    var colorsField = g2.add("edittext", undefined, "#FF0000, #00FF00, #0000FF");
    colorsField.preferredSize.width = 180;
    colorsField.helpTip = "Max 8 colors, separated by commas";
    
    // Logo
    var g3 = addP.add("group");
    g3.orientation = "row";
    g3.add("statictext", undefined, "Logo:").preferredSize.width = 40;
    var logoField = g3.add("edittext", undefined, "");
    logoField.preferredSize.width = 130;
    var browseBtn = g3.add("button", undefined, "Browse");
    
    browseBtn.onClick = function() {
        var f = File.openDialog("Select Logo", "*.png;*.jpg;*.jpeg;*.ai;*.eps;*.svg");
        if (f) logoField.text = f.fsName;
    };
    
    // Status
    var status = addP.add("statictext", undefined, "Ready");
    status.justify = "center";
    
    // === قائمة البراندات ===
    var listP = win.add("panel", undefined, "Your Brands");
    listP.orientation = "column";
    listP.alignChildren = ["fill", "top"];
    listP.margins = 8;
    
    var brandDropdown = listP.add("dropdownlist", undefined, []);
    brandDropdown.preferredSize.width = 260;
    
    var listContainer = listP.add("group");
    listContainer.orientation = "column";
    listContainer.alignChildren = ["fill", "top"];
    
    var selectedIndex = 0;
    var editingIndex = null;
    
    // === شريط أزرار مضغوط ===
    var toolbarP = win.add("panel", undefined, undefined);
    toolbarP.orientation = "row";
    toolbarP.alignChildren = ["center", "center"];
    toolbarP.margins = 6;
    toolbarP.spacing = 4;
    
    var infoBtn = toolbarP.add("button", undefined, "\u24D8");
    infoBtn.preferredSize = [26, 24];
    infoBtn.helpTip = "Info";
    
    var exportBtn = toolbarP.add("button", undefined, "Export");
    exportBtn.preferredSize.width = 50;
    
    var importBtn = toolbarP.add("button", undefined, "Import");
    importBtn.preferredSize.width = 50;
    
    var editBtn = toolbarP.add("button", undefined, "Edit");
    editBtn.preferredSize.width = 40;
    
    var webBtn = toolbarP.add("button", undefined, "Update");
    webBtn.preferredSize.width = 55;
    webBtn.helpTip = "www.khoudrsheha.com";
    
    // === زر مسح كل التأثيرات ===
    var removeAllBtn = win.add("button", undefined, "REMOVE ALL EFFECTS");
    removeAllBtn.preferredSize.height = 28;
    
    // ========== دوال الرسم ==========
    function renderCard(idx) {
        // امسح القديم
        while (listContainer.children.length > 0) {
            listContainer.remove(listContainer.children[0]);
        }
        
        var b = BRANDS[idx];
        
        var card = listContainer.add("panel", undefined, b.name);
        card.orientation = "column";
        card.alignChildren = ["fill", "top"];
        card.margins = 6;
        
        // Colors - 4 بكل سطر
        var cRow = null;
        var colsPerRow = 4;
        
        for (var j = 0; j < b.colors.length; j++) {
            if (j % colsPerRow === 0) {
                cRow = card.add("group");
                cRow.orientation = "row";
                cRow.alignChildren = ["left", "top"];
                cRow.spacing = 6;
            }
            
            var hex = trimStr(b.colors[j]);
            var rgb = hexToRGB(hex);
            
            var itemGroup = cRow.add("group");
            itemGroup.orientation = "column";
            itemGroup.alignChildren = ["center", "top"];
            itemGroup.spacing = 2;
            
            var swatch = itemGroup.add("group");
            swatch.preferredSize = [34, 24];
            swatch.helpTip = hex + " (click to apply)";
            
            var copyLink = itemGroup.add("button", undefined, "Copy");
            copyLink.preferredSize = [34, 16];
            copyLink.helpTip = "Copy " + hex;
            
            (function(color, rgbColor, sw, cpLink) {
                sw.onDraw = function() {
                    var gr = this.graphics;
                    var brush = gr.newBrush(gr.BrushType.SOLID_COLOR, rgbColor);
                    gr.newPath();
                    gr.rectPath(0, 0, this.size[0], this.size[1]);
                    gr.fillPath(brush);
                };
                sw.addEventListener("mousedown", function() {
                    applyColor(color);
                    status.text = "Applied: " + color;
                });
                cpLink.onClick = function() {
                    copyToClipboard(color);
                    status.text = "Copied: " + color;
                };
            })(hex, rgb, swatch, copyLink);
        }
        
        // Actions row: Add Logo + Delete Brand جنب بعض
        var actionsRow = card.add("group");
        actionsRow.orientation = "row";
        actionsRow.alignChildren = ["fill", "center"];
        actionsRow.spacing = 4;
        
        if (b.logo && b.logo !== "") {
            var lBtn = actionsRow.add("button", undefined, "Add Logo");
            lBtn.preferredSize.width = 90;
            (function(path) {
                lBtn.onClick = function() {
                    applyLogo(path);
                    status.text = "Logo added!";
                };
            })(b.logo);
        }
        
        var dBtn = actionsRow.add("button", undefined, "Delete Brand");
        (function(idx2) {
            dBtn.onClick = function() {
                BRANDS.splice(idx2, 1);
                if (selectedIndex >= BRANDS.length) selectedIndex = BRANDS.length - 1;
                saveData();
                drawBrands();
                status.text = "Deleted";
            };
        })(idx);
        
        win.layout.layout(true);
    }
    
    function drawBrands() {
      try {
        // إعادة بناء القائمة المنسدلة
        while (brandDropdown.items.length > 0) {
            brandDropdown.remove(0);
        }
        
        if (BRANDS.length === 0) {
            while (listContainer.children.length > 0) {
                listContainer.remove(listContainer.children[0]);
            }
            listContainer.add("statictext", undefined, "No brands yet. Add one above!").justify = "center";
            win.layout.layout(true);
            return;
        }
        
        for (var i = 0; i < BRANDS.length; i++) {
            brandDropdown.add("item", BRANDS[i].name);
        }
        
        if (selectedIndex < 0) selectedIndex = 0;
        if (selectedIndex >= BRANDS.length) selectedIndex = BRANDS.length - 1;
        
        brandDropdown.selection = selectedIndex;
        renderCard(selectedIndex);
      } catch (e) {
          alert("Draw Error: " + e.toString() + "\nLine: " + e.line);
      }
    }
    
    brandDropdown.onChange = function() {
        if (brandDropdown.selection) {
            selectedIndex = brandDropdown.selection.index;
            renderCard(selectedIndex);
        }
    };
    
    // ========== أزرار الشريط ==========
    infoBtn.onClick = function() {
        alert("Brand Manager v1.0\nLast Update: July 2026\nkhoudrsheha.com", "Brand Manager");
    };
    
    exportBtn.onClick = function() {
        if (BRANDS.length === 0) {
            alert("No brands to export!");
            return;
        }
        try {
            var f = File.saveDialog("Save Brands as JSON", "*.json");
            if (!f) return;
            if (f.fsName.toLowerCase().indexOf(".json") === -1) {
                f = new File(f.fsName + ".json");
            }
            f.encoding = "UTF-8";
            f.open("w");
            f.write(brandsToJSON(BRANDS));
            f.close();
            status.text = "Exported!";
        } catch (e) {
            alert("Export Error: " + e.toString());
        }
    };
    
    importBtn.onClick = function() {
        try {
            var f = File.openDialog("Select Brands JSON File", "*.json");
            if (!f) return;
            f.encoding = "UTF-8";
            f.open("r");
            var content = f.read();
            f.close();
            var imported = eval("(" + content + ")");
            if (!imported || imported.length === undefined) {
                alert("Invalid JSON file!");
                return;
            }
            BRANDS = imported;
            selectedIndex = 0;
            editingIndex = null;
            saveData();
            drawBrands();
            status.text = "Imported " + BRANDS.length + " brand(s)";
        } catch (e) {
            alert("Import Error: " + e.toString());
        }
    };
    
    editBtn.onClick = function() {
        if (BRANDS.length === 0) {
            alert("No brand selected!");
            return;
        }
        editingIndex = selectedIndex;
        var b = BRANDS[editingIndex];
        nameField.text = b.name;
        colorsField.text = b.colors.join(", ");
        logoField.text = b.logo || "";
        addBtn.text = "SAVE";
        status.text = "Editing: " + b.name;
    };
    
    webBtn.onClick = function() {
        var url = "https://www.khoudrsheha.com";
        try {
            if ($.os.indexOf("Windows") !== -1) {
                system.callSystem('cmd /c start "" "' + url + '"');
            } else {
                system.callSystem('open "' + url + '"');
            }
        } catch (e) {
            alert("افتح المتصفح وزور: " + url);
        }
    };
    
    removeAllBtn.onClick = function() {
        removeAllEffects();
        status.text = "All effects removed";
    };
    
    // ========== ربط زر الإضافة ==========
    // نستخدم function داخلية مع closure صحيحة
    addBtn.onClick = function() {
        try {
            var n = trimStr(nameField.text);
            var c = trimStr(colorsField.text);
            var l = trimStr(logoField.text);

            if (!n) {
                alert("Enter brand name!");
                return;
            }

            var cols = [];
            var parts = c.split(",");
            for (var i = 0; i < parts.length; i++) {
                var col = trimStr(parts[i]);
                if (col) cols.push(col);
            }

            if (cols.length === 0) {
                alert("Enter at least one color!");
                return;
            }

            if (cols.length > 8) {
                cols = cols.slice(0, 8);
                alert("Max 8 colors allowed. Only the first 8 were kept.");
            }

            if (editingIndex !== null) {
                BRANDS[editingIndex] = { name: n, colors: cols, logo: l };
                selectedIndex = editingIndex;
                editingIndex = null;
                addBtn.text = "ADD";
                status.text = "Updated: " + n;
            } else {
                BRANDS.push({
                    name: n,
                    colors: cols,
                    logo: l
                });
                selectedIndex = BRANDS.length - 1;
                status.text = "Added: " + n;
            }

            saveData();
            drawBrands();

            nameField.text = "";
            colorsField.text = "#FF0000, #00FF00, #0000FF";
            logoField.text = "";
        } catch (e) {
            alert("Add Brand Error: " + e.toString() + "\nLine: " + e.line);
        }
    };
    
    // ========== تحميل وعرض ==========
    loadData();
    drawBrands();
    
    // ========== عرض ==========
    if (win instanceof Window) {
        win.center();
        win.show();
    } else {
        win.layout.layout(true);
    }
    
    return win;
}

// شغّل
buildUI(this);