import { Component, Input } from '@angular/core';
import { Metadata, RunView } from '@memberjunction/core';
import { MJNotificationService } from '@memberjunction/ng-notifications';
import { ModuleRegistry, AllCommunityModule, themeAlpine, colorSchemeVariable } from 'ag-grid-community';
import * as i0 from "@angular/core";
import * as i1 from "ag-grid-angular";
import * as i2 from "@memberjunction/ng-ui-components";
function TemplateParamsGridComponent_Conditional_7_Template(rf, ctx) { if (rf & 1) {
    const _r1 = i0.ɵɵgetCurrentView();
    i0.ɵɵelementStart(0, "div", 4)(1, "button", 7);
    i0.ɵɵlistener("click", function TemplateParamsGridComponent_Conditional_7_Template_button_click_1_listener() { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r1.addNewParam()); });
    i0.ɵɵelement(2, "i", 8);
    i0.ɵɵtext(3, " Add Parameter ");
    i0.ɵɵelementEnd()();
} }
function TemplateParamsGridComponent_Conditional_9_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "div", 6)(1, "h4");
    i0.ɵɵelement(2, "i", 9);
    i0.ɵɵtext(3, " Parameter Types");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(4, "ul")(5, "li")(6, "strong");
    i0.ɵɵtext(7, "Scalar:");
    i0.ɵɵelementEnd();
    i0.ɵɵtext(8, " Single value like text, number, or boolean");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(9, "li")(10, "strong");
    i0.ɵɵtext(11, "Array:");
    i0.ɵɵelementEnd();
    i0.ɵɵtext(12, " List of values");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(13, "li")(14, "strong");
    i0.ɵɵtext(15, "Object:");
    i0.ɵɵelementEnd();
    i0.ɵɵtext(16, " JSON object with multiple properties");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(17, "li")(18, "strong");
    i0.ɵɵtext(19, "Record:");
    i0.ɵɵelementEnd();
    i0.ɵɵtext(20, " Single record from a MemberJunction entity");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(21, "li")(22, "strong");
    i0.ɵɵtext(23, "Entity:");
    i0.ɵɵelementEnd();
    i0.ɵɵtext(24, " Multiple records from a MemberJunction entity (can be filtered)");
    i0.ɵɵelementEnd()();
    i0.ɵɵelementStart(25, "p", 10);
    i0.ɵɵelement(26, "i", 11);
    i0.ɵɵtext(27, " Use parameters in your template with the syntax: ");
    i0.ɵɵelementStart(28, "code");
    i0.ɵɵtext(29);
    i0.ɵɵelementEnd()()();
} if (rf & 2) {
    i0.ɵɵadvance(29);
    i0.ɵɵtextInterpolate2("", "{{", " parameterName ", "}}");
} }
// Register AG Grid modules
ModuleRegistry.registerModules([AllCommunityModule]);
export class TemplateParamsGridComponent {
    constructor() {
        this.template = null;
        this.editMode = false;
        this.templateParams = [];
        this.isLoading = false;
        // Type options for dropdown
        this.typeOptions = ['Scalar', 'Array', 'Object', 'Record', 'Entity'];
        // AG Grid configuration
        this.ColumnDefs = [];
        this.DefaultColDef = {
            sortable: true,
            resizable: true,
            filter: false,
            flex: 1
        };
        this.GridTheme = themeAlpine.withPart(colorSchemeVariable);
        this.gridApi = null;
        /** Row currently being edited (for cancel/revert) */
        this.editingRowBackup = null;
        this.editingRowId = null;
        this.noRowsTemplate = `
        <div style="text-align: center; padding: 40px 20px; color: var(--mj-text-muted);">
            <i class="fa-solid fa-info-circle" style="font-size: 2em; margin-bottom: 10px;"></i>
            <p>No parameters defined for this template.</p>
        </div>
    `;
        this.getRowId = (params) => {
            // Use entity ID if saved, otherwise use a temporary key
            return params.data.ID || `new_${params.data.Name}_${Date.now()}`;
        };
    }
    ngOnInit() {
        this.buildColumnDefs();
        if (this.template?.ID) {
            this.loadTemplateParams();
        }
    }
    ngOnChanges(changes) {
        if (changes['template'] && this.template?.ID) {
            this.loadTemplateParams();
        }
        if (changes['editMode']) {
            this.buildColumnDefs();
        }
    }
    onGridReady(event) {
        this.gridApi = event.api;
    }
    async loadTemplateParams() {
        if (!this.template?.ID)
            return;
        this.isLoading = true;
        try {
            const rv = new RunView();
            const results = await rv.RunView({
                EntityName: 'MJ: Template Params',
                ExtraFilter: `TemplateID='${this.template.ID}'`,
                OrderBy: 'Name ASC',
                ResultType: 'entity_object'
            });
            if (results.Success) {
                const entities = results.Results || [];
                this.templateParams = entities.map(e => this.entityToRowData(e));
            }
            else {
                console.error('Failed to load template params:', results.ErrorMessage);
                MJNotificationService.Instance.CreateSimpleNotification('Failed to load template parameters', 'error');
            }
        }
        catch (error) {
            console.error('Error loading template params:', error);
            MJNotificationService.Instance.CreateSimpleNotification('Error loading template parameters', 'error');
        }
        finally {
            this.isLoading = false;
        }
    }
    // -- Grid editing lifecycle --
    async addNewParam() {
        if (!this.editMode || !this.template?.ID)
            return;
        // Cancel any in-progress edit first
        this.cancelCurrentEdit();
        const newEntity = await this.createNewParamEntity();
        if (!newEntity)
            return;
        const newRow = this.entityToRowData(newEntity);
        newRow.IsNew = true;
        // Prepend the new row
        this.templateParams = [newRow, ...this.templateParams];
        // Wait for grid to process the new row, then start editing it
        setTimeout(() => {
            if (!this.gridApi)
                return;
            const rowNode = this.gridApi.getDisplayedRowAtIndex(0);
            if (rowNode) {
                this.editingRowId = rowNode.id ?? null;
                this.editingRowBackup = { ...newRow };
                this.gridApi.startEditingCell({
                    rowIndex: 0,
                    colKey: 'Name'
                });
                this.gridApi.refreshCells({ columns: ['actions'], force: true });
            }
        });
    }
    startEditRow(params) {
        if (!this.gridApi || !this.editMode)
            return;
        // Cancel any in-progress edit first
        this.cancelCurrentEdit();
        const rowIndex = params.node.rowIndex;
        if (rowIndex == null)
            return;
        this.editingRowId = params.node.id ?? null;
        this.editingRowBackup = { ...params.data };
        this.gridApi.startEditingCell({
            rowIndex,
            colKey: 'Name'
        });
        this.gridApi.refreshCells({ columns: ['actions'], force: true });
    }
    cancelEditRow() {
        this.cancelCurrentEdit();
    }
    saveEditRow() {
        if (!this.gridApi)
            return;
        // stopEditing triggers onRowEditingStopped, which handles the save
        this.gridApi.stopEditing(false);
        this.gridApi.refreshCells({ columns: ['actions'], force: true });
    }
    async onRowEditingStopped(event) {
        const rowData = event.data;
        if (!rowData)
            return;
        // If the user cancelled (via Escape or cancel button backup restore), skip save
        if (this.editingRowBackup === null)
            return;
        // Validate: Name is required
        if (!rowData.Name || rowData.Name.trim().length === 0) {
            MJNotificationService.Instance.CreateSimpleNotification('Parameter name is required', 'error');
            // If it was a new unsaved row, remove it
            if (rowData.IsNew) {
                this.templateParams = this.templateParams.filter(p => p !== rowData);
            }
            else if (this.editingRowBackup) {
                // Revert to backup
                this.revertRow(event.node, this.editingRowBackup);
            }
            this.clearEditState();
            return;
        }
        await this.saveParamRow(rowData);
        this.clearEditState();
    }
    async deleteRow(params) {
        if (!this.editMode)
            return;
        const rowData = params.data;
        const entity = rowData.Entity;
        if (!confirm(`Are you sure you want to delete the parameter "${rowData.Name}"?`)) {
            return;
        }
        try {
            if (entity.ID) {
                const deleted = await entity.Delete();
                if (deleted) {
                    MJNotificationService.Instance.CreateSimpleNotification(`Parameter "${rowData.Name}" deleted successfully`, 'success');
                    this.templateParams = this.templateParams.filter(p => p !== rowData);
                }
                else {
                    MJNotificationService.Instance.CreateSimpleNotification(`Failed to delete parameter: ${entity.LatestResult?.Message || 'Unknown error'}`, 'error');
                }
            }
            else {
                // Not yet saved -- just remove from the array
                this.templateParams = this.templateParams.filter(p => p !== rowData);
            }
        }
        catch (error) {
            console.error('Error deleting parameter:', error);
            MJNotificationService.Instance.CreateSimpleNotification('Error deleting parameter', 'error');
        }
    }
    // -- Helpers --
    getTypeIcon(type) {
        switch (type) {
            case 'Scalar': return 'fa-font';
            case 'Array': return 'fa-list';
            case 'Object': return 'fa-cube';
            case 'Record': return 'fa-file';
            case 'Entity': return 'fa-table';
            default: return 'fa-question';
        }
    }
    entityToRowData(entity) {
        return {
            Entity: entity,
            ID: entity.ID || '',
            Name: entity.Name || '',
            Type: entity.Type || 'Scalar',
            IsRequired: entity.IsRequired || false,
            Description: entity.Description || '',
            DefaultValue: entity.DefaultValue || '',
            LinkedParameterName: entity.LinkedParameterName || '',
            LinkedParameterField: entity.LinkedParameterField || '',
            IsNew: false
        };
    }
    async saveParamRow(rowData) {
        const entity = rowData.Entity;
        entity.Name = rowData.Name;
        entity.Type = rowData.Type;
        entity.IsRequired = rowData.IsRequired;
        entity.Description = rowData.Description;
        entity.DefaultValue = rowData.DefaultValue;
        // Handle linked parameter fields for Entity type
        if (rowData.Type === 'Entity') {
            entity.LinkedParameterName = rowData.LinkedParameterName;
            entity.LinkedParameterField = rowData.LinkedParameterField;
        }
        else {
            entity.LinkedParameterName = null;
            entity.LinkedParameterField = null;
        }
        try {
            const saved = await entity.Save();
            if (saved) {
                MJNotificationService.Instance.CreateSimpleNotification(`Parameter "${entity.Name}" saved successfully`, 'success');
                // Update the row data with the saved entity ID
                rowData.ID = entity.ID;
                rowData.IsNew = false;
                // Refresh the grid to pick up the new ID
                this.templateParams = [...this.templateParams];
            }
            else {
                MJNotificationService.Instance.CreateSimpleNotification(`Failed to save parameter: ${entity.LatestResult?.Message || 'Unknown error'}`, 'error');
                await this.loadTemplateParams();
            }
        }
        catch (error) {
            console.error('Error saving parameter:', error);
            MJNotificationService.Instance.CreateSimpleNotification('Error saving parameter', 'error');
            await this.loadTemplateParams();
        }
    }
    async createNewParamEntity() {
        if (!this.template?.ID)
            return null;
        try {
            const md = new Metadata();
            const newParam = await md.GetEntityObject('MJ: Template Params');
            newParam.TemplateID = this.template.ID;
            newParam.Type = 'Scalar';
            newParam.IsRequired = false;
            return newParam;
        }
        catch (error) {
            console.error('Error creating new parameter:', error);
            return null;
        }
    }
    cancelCurrentEdit() {
        if (!this.gridApi)
            return;
        if (this.editingRowBackup && this.editingRowId) {
            const rowNode = this.gridApi.getRowNode(this.editingRowId);
            if (rowNode) {
                // If the row was new and unsaved, remove it
                if (this.editingRowBackup.IsNew) {
                    const backup = this.editingRowBackup;
                    this.clearEditState();
                    this.gridApi.stopEditing(true);
                    this.templateParams = this.templateParams.filter(p => p.Entity !== backup.Entity);
                    return;
                }
                // Revert to backup
                this.revertRow(rowNode, this.editingRowBackup);
            }
        }
        this.clearEditState();
        this.gridApi.stopEditing(true);
        this.gridApi.refreshCells({ columns: ['actions'], force: true });
    }
    revertRow(rowNode, backup) {
        rowNode.setData(backup);
    }
    clearEditState() {
        this.editingRowBackup = null;
        this.editingRowId = null;
    }
    buildColumnDefs() {
        const self = this;
        const cols = [
            {
                field: 'Name',
                headerName: 'Parameter Name',
                width: 200,
                editable: this.editMode,
                cellRenderer: (params) => {
                    if (!params.value)
                        return '';
                    const row = params.data;
                    let html = `<strong>${params.value}</strong>`;
                    if (row.IsRequired) {
                        html += ` <span style="display: inline-flex; align-items: center; gap: 4px; background-color: var(--mj-status-error); color: var(--mj-text-inverse); padding: 2px 8px; border-radius: 12px; font-size: 0.75em; font-weight: 500;"><i class="fa-solid fa-asterisk" style="font-size: 0.6em;"></i> Required</span>`;
                    }
                    return html;
                }
            },
            {
                field: 'Type',
                headerName: 'Type',
                width: 140,
                editable: this.editMode,
                cellEditor: 'agSelectCellEditor',
                cellEditorParams: {
                    values: this.typeOptions
                },
                cellRenderer: (params) => {
                    if (!params.value)
                        return '';
                    const icon = self.getTypeIcon(params.value);
                    return `<span style="display: flex; align-items: center; gap: 6px; color: var(--mj-text-secondary);"><i class="fa-solid ${icon}" style="color: var(--mj-text-muted);"></i> ${params.value}</span>`;
                }
            },
            {
                field: 'IsRequired',
                headerName: 'Required',
                width: 100,
                editable: this.editMode,
                cellDataType: 'boolean',
                cellRenderer: (params) => {
                    if (params.value) {
                        return `<div style="text-align: center;"><i class="fa-solid fa-check" style="color: var(--mj-status-success);"></i></div>`;
                    }
                    return `<div style="text-align: center;"><i class="fa-solid fa-times" style="color: var(--mj-text-muted);"></i></div>`;
                }
            },
            {
                field: 'Description',
                headerName: 'Description',
                width: 300,
                editable: this.editMode,
                cellRenderer: (params) => {
                    return params.value || '<span style="color: var(--mj-text-muted); font-style: italic; font-size: 0.9em;">(No description)</span>';
                }
            },
            {
                field: 'DefaultValue',
                headerName: 'Default Value',
                width: 200,
                editable: this.editMode,
                cellRenderer: (params) => {
                    if (params.value) {
                        return `<code style="background-color: var(--mj-bg-surface-card); padding: 2px 6px; border-radius: 3px; font-size: 0.85em; color: var(--mj-text-secondary);">${params.value}</code>`;
                    }
                    return '<span style="color: var(--mj-text-muted); font-style: italic; font-size: 0.9em;">(No default)</span>';
                }
            }
        ];
        if (this.editMode) {
            cols.push({
                headerName: 'Actions',
                width: 120,
                sortable: false,
                resizable: false,
                editable: false,
                cellRenderer: ActionsCellRenderer,
                cellRendererParams: {
                    componentRef: self
                }
            });
        }
        this.ColumnDefs = cols;
    }
    static { this.ɵfac = function TemplateParamsGridComponent_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || TemplateParamsGridComponent)(); }; }
    static { this.ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: TemplateParamsGridComponent, selectors: [["mj-template-params-grid"]], inputs: { template: "template", editMode: "editMode" }, standalone: false, features: [i0.ɵɵNgOnChangesFeature], decls: 10, vars: 10, consts: [[1, "template-params-grid"], [1, "params-header"], [1, "fa-solid", "fa-sliders"], [1, "params-description"], [1, "params-toolbar"], [1, "params-ag-grid", 2, "width", "100%", "height", "400px", 3, "gridReady", "rowEditingStopped", "theme", "rowData", "columnDefs", "defaultColDef", "editType", "getRowId", "suppressClickEdit", "overlayNoRowsTemplate"], [1, "params-help"], ["mjButton", "", "variant", "primary", 3, "click"], [1, "fa-solid", "fa-plus"], [1, "fa-solid", "fa-question-circle"], [1, "help-note"], [1, "fa-solid", "fa-lightbulb"]], template: function TemplateParamsGridComponent_Template(rf, ctx) { if (rf & 1) {
            i0.ɵɵelementStart(0, "div", 0)(1, "div", 1)(2, "h3");
            i0.ɵɵelement(3, "i", 2);
            i0.ɵɵtext(4, " Template Parameters");
            i0.ɵɵelementEnd();
            i0.ɵɵelementStart(5, "p", 3);
            i0.ɵɵtext(6, " Define the parameters that can be used within this template. Parameters allow dynamic content injection at runtime. ");
            i0.ɵɵelementEnd()();
            i0.ɵɵconditionalCreate(7, TemplateParamsGridComponent_Conditional_7_Template, 4, 0, "div", 4);
            i0.ɵɵelementStart(8, "ag-grid-angular", 5);
            i0.ɵɵlistener("gridReady", function TemplateParamsGridComponent_Template_ag_grid_angular_gridReady_8_listener($event) { return ctx.onGridReady($event); })("rowEditingStopped", function TemplateParamsGridComponent_Template_ag_grid_angular_rowEditingStopped_8_listener($event) { return ctx.onRowEditingStopped($event); });
            i0.ɵɵelementEnd();
            i0.ɵɵconditionalCreate(9, TemplateParamsGridComponent_Conditional_9_Template, 30, 2, "div", 6);
            i0.ɵɵelementEnd();
        } if (rf & 2) {
            i0.ɵɵadvance(7);
            i0.ɵɵconditional(ctx.editMode ? 7 : -1);
            i0.ɵɵadvance();
            i0.ɵɵproperty("theme", ctx.GridTheme)("rowData", ctx.templateParams)("columnDefs", ctx.ColumnDefs)("defaultColDef", ctx.DefaultColDef)("editType", "fullRow")("getRowId", ctx.getRowId)("suppressClickEdit", true)("overlayNoRowsTemplate", ctx.noRowsTemplate);
            i0.ɵɵadvance();
            i0.ɵɵconditional(ctx.editMode ? 9 : -1);
        } }, dependencies: [i1.AgGridAngular, i2.MJButtonDirective], styles: [".template-params-grid[_ngcontent-%COMP%] {\n    padding: 20px;\n}\n\n.params-header[_ngcontent-%COMP%] {\n    margin-bottom: 20px;\n}\n\n.params-header[_ngcontent-%COMP%]   h3[_ngcontent-%COMP%] {\n    margin: 0 0 8px 0;\n    color: var(--mj-text-primary);\n    font-size: 1.2em;\n}\n\n.params-header[_ngcontent-%COMP%]   h3[_ngcontent-%COMP%]   i[_ngcontent-%COMP%] {\n    margin-right: 8px;\n    color: var(--mj-brand-primary);\n}\n\n.params-description[_ngcontent-%COMP%] {\n    margin: 0;\n    color: var(--mj-text-secondary);\n    font-size: 0.9em;\n}\n\n\n\n.params-toolbar[_ngcontent-%COMP%] {\n    margin-bottom: 12px;\n    padding: 12px;\n    background-color: var(--mj-bg-surface-card);\n    border: 1px solid var(--mj-border-default);\n    border-radius: 6px 6px 0 0;\n}\n\n\n\n.params-ag-grid[_ngcontent-%COMP%] {\n    border: 1px solid var(--mj-border-default);\n    border-radius: 0 0 6px 6px;\n}\n\n.params-toolbar[_ngcontent-%COMP%]    + .params-ag-grid[_ngcontent-%COMP%] {\n    border-top: none;\n}\n\n\n\n.params-help[_ngcontent-%COMP%] {\n    margin-top: 30px;\n    padding: 20px;\n    background-color: var(--mj-bg-surface-card);\n    border-radius: 8px;\n    border: 1px solid var(--mj-border-default);\n}\n\n.params-help[_ngcontent-%COMP%]   h4[_ngcontent-%COMP%] {\n    margin: 0 0 15px 0;\n    color: var(--mj-text-primary);\n    font-size: 1em;\n}\n\n.params-help[_ngcontent-%COMP%]   h4[_ngcontent-%COMP%]   i[_ngcontent-%COMP%] {\n    margin-right: 6px;\n    color: var(--mj-brand-primary);\n}\n\n.params-help[_ngcontent-%COMP%]   ul[_ngcontent-%COMP%] {\n    margin: 10px 0;\n    padding-left: 25px;\n}\n\n.params-help[_ngcontent-%COMP%]   li[_ngcontent-%COMP%] {\n    margin-bottom: 8px;\n    color: var(--mj-text-secondary);\n    font-size: 0.9em;\n}\n\n.params-help[_ngcontent-%COMP%]   strong[_ngcontent-%COMP%] {\n    color: var(--mj-text-primary);\n}\n\n.help-note[_ngcontent-%COMP%] {\n    margin-top: 15px;\n    padding: 10px 15px;\n    background-color: color-mix(in srgb, var(--mj-brand-primary) 8%, var(--mj-bg-surface));\n    border-left: 4px solid var(--mj-brand-primary);\n    border-radius: 4px;\n    font-size: 0.9em;\n}\n\n.help-note[_ngcontent-%COMP%]   i[_ngcontent-%COMP%] {\n    margin-right: 6px;\n    color: var(--mj-brand-primary);\n}\n\n.help-note[_ngcontent-%COMP%]   code[_ngcontent-%COMP%] {\n    background-color: var(--mj-bg-surface);\n    padding: 2px 4px;\n    border-radius: 3px;\n    font-family: 'Courier New', monospace;\n    color: var(--mj-status-error);\n}\n\n\n\n@media (max-width: 768px) {\n    .template-params-grid[_ngcontent-%COMP%] {\n        padding: 10px;\n    }\n\n    .params-help[_ngcontent-%COMP%] {\n        padding: 15px;\n    }\n}"] }); }
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(TemplateParamsGridComponent, [{
        type: Component,
        args: [{ standalone: false, selector: 'mj-template-params-grid', template: "<div class=\"template-params-grid\">\n  <div class=\"params-header\">\n    <h3><i class=\"fa-solid fa-sliders\"></i> Template Parameters</h3>\n    <p class=\"params-description\">\n      Define the parameters that can be used within this template. Parameters allow dynamic content injection at runtime.\n    </p>\n  </div>\n\n  @if (editMode) {\n    <div class=\"params-toolbar\">\n      <button mjButton variant=\"primary\" (click)=\"addNewParam()\">\n        <i class=\"fa-solid fa-plus\"></i> Add Parameter\n      </button>\n    </div>\n  }\n\n  <ag-grid-angular\n    class=\"params-ag-grid\"\n    [theme]=\"GridTheme\"\n    [rowData]=\"templateParams\"\n    [columnDefs]=\"ColumnDefs\"\n    [defaultColDef]=\"DefaultColDef\"\n    [editType]=\"'fullRow'\"\n    [getRowId]=\"getRowId\"\n    [suppressClickEdit]=\"true\"\n    [overlayNoRowsTemplate]=\"noRowsTemplate\"\n    (gridReady)=\"onGridReady($event)\"\n    (rowEditingStopped)=\"onRowEditingStopped($event)\"\n    style=\"width: 100%; height: 400px;\">\n  </ag-grid-angular>\n\n  <!-- Help Section -->\n  @if (editMode) {\n    <div class=\"params-help\">\n      <h4><i class=\"fa-solid fa-question-circle\"></i> Parameter Types</h4>\n      <ul>\n        <li><strong>Scalar:</strong> Single value like text, number, or boolean</li>\n        <li><strong>Array:</strong> List of values</li>\n        <li><strong>Object:</strong> JSON object with multiple properties</li>\n        <li><strong>Record:</strong> Single record from a MemberJunction entity</li>\n        <li><strong>Entity:</strong> Multiple records from a MemberJunction entity (can be filtered)</li>\n      </ul>\n      <p class=\"help-note\">\n        <i class=\"fa-solid fa-lightbulb\"></i>\n        Use parameters in your template with the syntax: <code>{{ '{{' }} parameterName {{ '}}' }}</code>\n      </p>\n    </div>\n  }\n</div>\n", styles: [".template-params-grid {\n    padding: 20px;\n}\n\n.params-header {\n    margin-bottom: 20px;\n}\n\n.params-header h3 {\n    margin: 0 0 8px 0;\n    color: var(--mj-text-primary);\n    font-size: 1.2em;\n}\n\n.params-header h3 i {\n    margin-right: 8px;\n    color: var(--mj-brand-primary);\n}\n\n.params-description {\n    margin: 0;\n    color: var(--mj-text-secondary);\n    font-size: 0.9em;\n}\n\n/* Toolbar */\n.params-toolbar {\n    margin-bottom: 12px;\n    padding: 12px;\n    background-color: var(--mj-bg-surface-card);\n    border: 1px solid var(--mj-border-default);\n    border-radius: 6px 6px 0 0;\n}\n\n/* AG Grid wrapper */\n.params-ag-grid {\n    border: 1px solid var(--mj-border-default);\n    border-radius: 0 0 6px 6px;\n}\n\n.params-toolbar + .params-ag-grid {\n    border-top: none;\n}\n\n/* Help Section */\n.params-help {\n    margin-top: 30px;\n    padding: 20px;\n    background-color: var(--mj-bg-surface-card);\n    border-radius: 8px;\n    border: 1px solid var(--mj-border-default);\n}\n\n.params-help h4 {\n    margin: 0 0 15px 0;\n    color: var(--mj-text-primary);\n    font-size: 1em;\n}\n\n.params-help h4 i {\n    margin-right: 6px;\n    color: var(--mj-brand-primary);\n}\n\n.params-help ul {\n    margin: 10px 0;\n    padding-left: 25px;\n}\n\n.params-help li {\n    margin-bottom: 8px;\n    color: var(--mj-text-secondary);\n    font-size: 0.9em;\n}\n\n.params-help strong {\n    color: var(--mj-text-primary);\n}\n\n.help-note {\n    margin-top: 15px;\n    padding: 10px 15px;\n    background-color: color-mix(in srgb, var(--mj-brand-primary) 8%, var(--mj-bg-surface));\n    border-left: 4px solid var(--mj-brand-primary);\n    border-radius: 4px;\n    font-size: 0.9em;\n}\n\n.help-note i {\n    margin-right: 6px;\n    color: var(--mj-brand-primary);\n}\n\n.help-note code {\n    background-color: var(--mj-bg-surface);\n    padding: 2px 4px;\n    border-radius: 3px;\n    font-family: 'Courier New', monospace;\n    color: var(--mj-status-error);\n}\n\n/* Responsive adjustments */\n@media (max-width: 768px) {\n    .template-params-grid {\n        padding: 10px;\n    }\n\n    .params-help {\n        padding: 15px;\n    }\n}\n"] }]
    }], null, { template: [{
            type: Input
        }], editMode: [{
            type: Input
        }] }); })();
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(TemplateParamsGridComponent, { className: "TemplateParamsGridComponent", filePath: "src/lib/custom/Templates/template-params-grid.component.ts", lineNumber: 48 }); })();
/**
 * Inline cell renderer for edit/delete/save/cancel action buttons.
 * This is a plain-JS AG Grid cell renderer (not an Angular component)
 * because the grid doesn't support Angular component renderers without
 * the AG Grid Enterprise "Framework Components" feature.
 */
function ActionsCellRenderer(params) {
    const container = document.createElement('div');
    container.style.display = 'flex';
    container.style.gap = '4px';
    container.style.alignItems = 'center';
    const comp = params.componentRef;
    const isEditing = params.node.rowIndex != null && params.api.getEditingCells().some(cell => cell.rowIndex === params.node.rowIndex);
    if (isEditing) {
        // Save button
        const saveBtn = createActionButton('fa-check', 'Save changes', 'var(--mj-brand-primary)');
        saveBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            comp.saveEditRow();
        });
        container.appendChild(saveBtn);
        // Cancel button
        const cancelBtn = createActionButton('fa-times', 'Cancel changes', 'var(--mj-text-secondary)');
        cancelBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            comp.cancelEditRow();
        });
        container.appendChild(cancelBtn);
    }
    else {
        // Edit button
        const editBtn = createActionButton('fa-edit', 'Edit parameter', 'var(--mj-text-secondary)');
        editBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            comp.startEditRow(params);
        });
        container.appendChild(editBtn);
        // Delete button
        const deleteBtn = createActionButton('fa-trash', 'Delete parameter', 'var(--mj-status-error)');
        deleteBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            comp.deleteRow(params);
        });
        container.appendChild(deleteBtn);
    }
    return container;
}
function createActionButton(iconClass, title, color) {
    const btn = document.createElement('button');
    btn.type = 'button';
    btn.title = title;
    btn.style.cssText = `
        border: 1px solid var(--mj-border-default);
        background: var(--mj-bg-surface);
        color: ${color};
        border-radius: 4px;
        padding: 4px 8px;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
    `;
    const icon = document.createElement('i');
    icon.className = `fa-solid ${iconClass}`;
    btn.appendChild(icon);
    return btn;
}
//# sourceMappingURL=template-params-grid.component.js.map