var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { Component, ViewChild } from '@angular/core';
import { RegisterClass } from '@memberjunction/global';
import { BaseFormComponent } from '@memberjunction/ng-base-forms';
import { TemplateFormComponent } from '../../generated/Entities/Template/template.form.component';
import { Metadata, RunView } from '@memberjunction/core';
import { TemplateEngineBase } from '@memberjunction/templates-base-types';
import { Subject } from 'rxjs';
import { MJNotificationService } from '@memberjunction/ng-notifications';
import { languages } from '@codemirror/language-data';
import * as i0 from "@angular/core";
import * as i1 from "@angular/forms";
import * as i2 from "@progress/kendo-angular-inputs";
import * as i3 from "@progress/kendo-angular-dropdowns";
import * as i4 from "@memberjunction/ng-user-view-grid";
import * as i5 from "@memberjunction/ng-base-forms";
import * as i6 from "@memberjunction/ng-form-toolbar";
import * as i7 from "@memberjunction/ng-tabstrip";
import * as i8 from "./template-param-dialog.component";
import * as i9 from "./template-params-grid.component";
import * as i10 from "../../shared/components/template-editor.component";
const _c0 = ["codeEditor"];
function TemplatesFormExtendedComponent_Conditional_1_Conditional_9_Template(rf, ctx) { if (rf & 1) {
    const _r2 = i0.ɵɵgetCurrentView();
    i0.ɵɵelementStart(0, "kendo-textbox", 46);
    i0.ɵɵtwoWayListener("ngModelChange", function TemplatesFormExtendedComponent_Conditional_1_Conditional_9_Template_kendo_textbox_ngModelChange_0_listener($event) { i0.ɵɵrestoreView(_r2); const ctx_r2 = i0.ɵɵnextContext(2); i0.ɵɵtwoWayBindingSet(ctx_r2.record.Name, $event) || (ctx_r2.record.Name = $event); return i0.ɵɵresetView($event); });
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const ctx_r2 = i0.ɵɵnextContext(2);
    i0.ɵɵtwoWayProperty("ngModel", ctx_r2.record.Name);
} }
function TemplatesFormExtendedComponent_Conditional_1_Conditional_10_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "div", 10);
    i0.ɵɵtext(1);
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const ctx_r2 = i0.ɵɵnextContext(2);
    i0.ɵɵadvance();
    i0.ɵɵtextInterpolate1(" ", ctx_r2.record.Name || "Unnamed Template", " ");
} }
function TemplatesFormExtendedComponent_Conditional_1_Conditional_15_Template(rf, ctx) { if (rf & 1) {
    const _r4 = i0.ɵɵgetCurrentView();
    i0.ɵɵelementStart(0, "kendo-textarea", 47);
    i0.ɵɵtwoWayListener("ngModelChange", function TemplatesFormExtendedComponent_Conditional_1_Conditional_15_Template_kendo_textarea_ngModelChange_0_listener($event) { i0.ɵɵrestoreView(_r4); const ctx_r2 = i0.ɵɵnextContext(2); i0.ɵɵtwoWayBindingSet(ctx_r2.record.Description, $event) || (ctx_r2.record.Description = $event); return i0.ɵɵresetView($event); });
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const ctx_r2 = i0.ɵɵnextContext(2);
    i0.ɵɵtwoWayProperty("ngModel", ctx_r2.record.Description);
    i0.ɵɵproperty("rows", 2);
} }
function TemplatesFormExtendedComponent_Conditional_1_Conditional_16_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "div", 13);
    i0.ɵɵtext(1);
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const ctx_r2 = i0.ɵɵnextContext(2);
    i0.ɵɵadvance();
    i0.ɵɵtextInterpolate1(" ", ctx_r2.record.Description || "No description provided", " ");
} }
function TemplatesFormExtendedComponent_Conditional_1_Conditional_21_Template(rf, ctx) { if (rf & 1) {
    const _r5 = i0.ɵɵgetCurrentView();
    i0.ɵɵelementStart(0, "kendo-combobox", 48);
    i0.ɵɵtwoWayListener("ngModelChange", function TemplatesFormExtendedComponent_Conditional_1_Conditional_21_Template_kendo_combobox_ngModelChange_0_listener($event) { i0.ɵɵrestoreView(_r5); const ctx_r2 = i0.ɵɵnextContext(2); i0.ɵɵtwoWayBindingSet(ctx_r2.record.CategoryID, $event) || (ctx_r2.record.CategoryID = $event); return i0.ɵɵresetView($event); });
    i0.ɵɵlistener("valueChange", function TemplatesFormExtendedComponent_Conditional_1_Conditional_21_Template_kendo_combobox_valueChange_0_listener($event) { i0.ɵɵrestoreView(_r5); const ctx_r2 = i0.ɵɵnextContext(2); return i0.ɵɵresetView(ctx_r2.onCategoryChange($event)); });
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const ctx_r2 = i0.ɵɵnextContext(2);
    i0.ɵɵtwoWayProperty("ngModel", ctx_r2.record.CategoryID);
    i0.ɵɵproperty("data", ctx_r2.categoryOptions)("valuePrimitive", true)("allowCustom", true);
} }
function TemplatesFormExtendedComponent_Conditional_1_Conditional_22_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "div", 16);
    i0.ɵɵtext(1);
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const ctx_r2 = i0.ɵɵnextContext(2);
    i0.ɵɵadvance();
    i0.ɵɵtextInterpolate1(" ", ctx_r2.record.Category || "Uncategorized", " ");
} }
function TemplatesFormExtendedComponent_Conditional_1_Conditional_24_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "span", 18);
    i0.ɵɵelement(1, "i", 49);
    i0.ɵɵtext(2, " Active ");
    i0.ɵɵelementEnd();
} }
function TemplatesFormExtendedComponent_Conditional_1_Conditional_25_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "span", 19);
    i0.ɵɵelement(1, "i", 50);
    i0.ɵɵtext(2, " Inactive ");
    i0.ɵɵelementEnd();
} }
function TemplatesFormExtendedComponent_Conditional_1_Template(rf, ctx) { if (rf & 1) {
    const _r1 = i0.ɵɵgetCurrentView();
    i0.ɵɵelementStart(0, "form", 2, 0);
    i0.ɵɵelement(2, "mj-form-toolbar", 3);
    i0.ɵɵelementStart(3, "div", 4)(4, "div", 5)(5, "div", 6)(6, "label", 7);
    i0.ɵɵelement(7, "i", 8);
    i0.ɵɵtext(8, " Template Name ");
    i0.ɵɵelementEnd();
    i0.ɵɵtemplate(9, TemplatesFormExtendedComponent_Conditional_1_Conditional_9_Template, 1, 1, "kendo-textbox", 9)(10, TemplatesFormExtendedComponent_Conditional_1_Conditional_10_Template, 2, 1, "div", 10);
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(11, "div", 6)(12, "label", 7);
    i0.ɵɵelement(13, "i", 11);
    i0.ɵɵtext(14, " Description ");
    i0.ɵɵelementEnd();
    i0.ɵɵtemplate(15, TemplatesFormExtendedComponent_Conditional_1_Conditional_15_Template, 1, 2, "kendo-textarea", 12)(16, TemplatesFormExtendedComponent_Conditional_1_Conditional_16_Template, 2, 1, "div", 13);
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(17, "div", 6)(18, "label", 7);
    i0.ɵɵelement(19, "i", 14);
    i0.ɵɵtext(20, " Category ");
    i0.ɵɵelementEnd();
    i0.ɵɵtemplate(21, TemplatesFormExtendedComponent_Conditional_1_Conditional_21_Template, 1, 4, "kendo-combobox", 15)(22, TemplatesFormExtendedComponent_Conditional_1_Conditional_22_Template, 2, 1, "div", 16);
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(23, "div", 17);
    i0.ɵɵtemplate(24, TemplatesFormExtendedComponent_Conditional_1_Conditional_24_Template, 3, 0, "span", 18)(25, TemplatesFormExtendedComponent_Conditional_1_Conditional_25_Template, 3, 0, "span", 19);
    i0.ɵɵelementEnd()()();
    i0.ɵɵelementStart(26, "mj-tabstrip", 20);
    i0.ɵɵlistener("TabSelected", function TemplatesFormExtendedComponent_Conditional_1_Template_mj_tabstrip_TabSelected_26_listener($event) { i0.ɵɵrestoreView(_r1); const ctx_r2 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r2.onTabSelect($event)); })("ResizeContainer", function TemplatesFormExtendedComponent_Conditional_1_Template_mj_tabstrip_ResizeContainer_26_listener() { i0.ɵɵrestoreView(_r1); const ctx_r2 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r2.InvokeManualResize()); });
    i0.ɵɵelementStart(27, "mj-tab", 21);
    i0.ɵɵelement(28, "i", 22);
    i0.ɵɵtext(29, " Contents ");
    i0.ɵɵelementStart(30, "span", 23);
    i0.ɵɵtext(31);
    i0.ɵɵelementEnd()();
    i0.ɵɵelementStart(32, "mj-tab-body")(33, "div", 24)(34, "mj-template-editor", 25);
    i0.ɵɵlistener("contentChange", function TemplatesFormExtendedComponent_Conditional_1_Template_mj_template_editor_contentChange_34_listener($event) { i0.ɵɵrestoreView(_r1); const ctx_r2 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r2.onSharedTemplateContentChange($event)); })("runTemplate", function TemplatesFormExtendedComponent_Conditional_1_Template_mj_template_editor_runTemplate_34_listener($event) { i0.ɵɵrestoreView(_r1); const ctx_r2 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r2.onSharedTemplateRun($event)); });
    i0.ɵɵelementEnd()()();
    i0.ɵɵelementStart(35, "mj-tab", 26);
    i0.ɵɵelement(36, "i", 27);
    i0.ɵɵtext(37, " Details ");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(38, "mj-tab-body")(39, "div", 28)(40, "div", 2);
    i0.ɵɵelement(41, "mj-form-field", 29)(42, "mj-form-field", 30)(43, "mj-form-field", 31)(44, "mj-form-field", 32)(45, "mj-form-field", 33)(46, "mj-form-field", 34)(47, "mj-form-field", 35)(48, "mj-form-field", 36)(49, "mj-form-field", 37);
    i0.ɵɵelementEnd()()();
    i0.ɵɵelementStart(50, "mj-tab", 38);
    i0.ɵɵelement(51, "i", 39);
    i0.ɵɵtext(52, " Parameters ");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(53, "mj-tab-body");
    i0.ɵɵelement(54, "mj-template-params-grid", 40);
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(55, "mj-tab", 41);
    i0.ɵɵelement(56, "i", 42);
    i0.ɵɵtext(57, " AI Prompts ");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(58, "mj-tab-body");
    i0.ɵɵelement(59, "mj-user-view-grid", 43);
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(60, "mj-tab", 44);
    i0.ɵɵelement(61, "i", 8);
    i0.ɵɵtext(62, " Documents ");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(63, "mj-tab-body");
    i0.ɵɵelement(64, "mj-user-view-grid", 43);
    i0.ɵɵelementEnd()()();
    i0.ɵɵelementStart(65, "mj-template-param-dialog", 45);
    i0.ɵɵtwoWayListener("isVisibleChange", function TemplatesFormExtendedComponent_Conditional_1_Template_mj_template_param_dialog_isVisibleChange_65_listener($event) { i0.ɵɵrestoreView(_r1); const ctx_r2 = i0.ɵɵnextContext(); i0.ɵɵtwoWayBindingSet(ctx_r2.showParamDialog, $event) || (ctx_r2.showParamDialog = $event); return i0.ɵɵresetView($event); });
    i0.ɵɵlistener("onClose", function TemplatesFormExtendedComponent_Conditional_1_Template_mj_template_param_dialog_onClose_65_listener() { i0.ɵɵrestoreView(_r1); const ctx_r2 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r2.onParamDialogClose()); });
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const ctx_r2 = i0.ɵɵnextContext();
    i0.ɵɵadvance(2);
    i0.ɵɵproperty("form", ctx_r2);
    i0.ɵɵadvance(7);
    i0.ɵɵconditional(ctx_r2.EditMode ? 9 : 10);
    i0.ɵɵadvance(6);
    i0.ɵɵconditional(ctx_r2.EditMode ? 15 : 16);
    i0.ɵɵadvance(6);
    i0.ɵɵconditional(ctx_r2.EditMode ? 21 : 22);
    i0.ɵɵadvance(3);
    i0.ɵɵconditional(ctx_r2.record.IsActive ? 24 : 25);
    i0.ɵɵadvance(7);
    i0.ɵɵtextInterpolate1(" ", ctx_r2.templateContents.length, " ");
    i0.ɵɵadvance(3);
    i0.ɵɵproperty("template", ctx_r2.record)("config", ctx_r2.templateEditorConfig);
    i0.ɵɵadvance(7);
    i0.ɵɵproperty("record", ctx_r2.record)("ShowLabel", true)("EditMode", ctx_r2.EditMode);
    i0.ɵɵadvance();
    i0.ɵɵproperty("record", ctx_r2.record)("ShowLabel", true)("EditMode", ctx_r2.EditMode);
    i0.ɵɵadvance();
    i0.ɵɵproperty("record", ctx_r2.record)("ShowLabel", true)("EditMode", ctx_r2.EditMode);
    i0.ɵɵadvance();
    i0.ɵɵproperty("record", ctx_r2.record)("ShowLabel", true)("EditMode", ctx_r2.EditMode);
    i0.ɵɵadvance();
    i0.ɵɵproperty("record", ctx_r2.record)("ShowLabel", true)("EditMode", ctx_r2.EditMode);
    i0.ɵɵadvance();
    i0.ɵɵproperty("record", ctx_r2.record)("ShowLabel", true)("EditMode", ctx_r2.EditMode);
    i0.ɵɵadvance();
    i0.ɵɵproperty("record", ctx_r2.record)("ShowLabel", true)("EditMode", ctx_r2.EditMode);
    i0.ɵɵadvance();
    i0.ɵɵproperty("record", ctx_r2.record)("ShowLabel", true)("EditMode", ctx_r2.EditMode);
    i0.ɵɵadvance();
    i0.ɵɵproperty("record", ctx_r2.record)("ShowLabel", true)("EditMode", ctx_r2.EditMode);
    i0.ɵɵadvance();
    i0.ɵɵproperty("Visible", ctx_r2.record.IsSaved);
    i0.ɵɵadvance(4);
    i0.ɵɵproperty("template", ctx_r2.record)("editMode", ctx_r2.EditMode);
    i0.ɵɵadvance();
    i0.ɵɵproperty("Visible", ctx_r2.record.IsSaved);
    i0.ɵɵadvance(4);
    i0.ɵɵproperty("Params", ctx_r2.BuildRelationshipViewParamsByEntityName("AI Prompts", "TemplateID"))("NewRecordValues", ctx_r2.NewRecordValues("AI Prompts"))("AllowLoad", ctx_r2.IsCurrentTab("AI Prompts"))("EditMode", ctx_r2.GridEditMode());
    i0.ɵɵadvance();
    i0.ɵɵproperty("Visible", ctx_r2.record.IsSaved);
    i0.ɵɵadvance(4);
    i0.ɵɵproperty("Params", ctx_r2.BuildRelationshipViewParamsByEntityName("Entity Documents", "TemplateID"))("NewRecordValues", ctx_r2.NewRecordValues("Entity Documents"))("AllowLoad", ctx_r2.IsCurrentTab("Entity Documents"))("EditMode", ctx_r2.GridEditMode());
    i0.ɵɵadvance();
    i0.ɵɵproperty("template", ctx_r2.record);
    i0.ɵɵtwoWayProperty("isVisible", ctx_r2.showParamDialog);
} }
let TemplatesFormExtendedComponent = class TemplatesFormExtendedComponent extends TemplateFormComponent {
    constructor() {
        super(...arguments);
        this.templateContents = [];
        this.selectedContentIndex = 0;
        this.isAddingNewContent = false;
        this.newTemplateContent = null;
        this.hasUnsavedChanges = false;
        this.templateInfoExpanded = true;
        this.templateContentsExpanded = true;
        this.categoryOptions = [
            { text: 'Select Category...', value: '' },
            // TODO: Load from database
        ];
        this.contentTypeOptions = [];
        this.supportedLanguages = languages;
        this.codeEditor = null;
        this.isUpdatingEditorValue = false;
        this.isRunningTemplate = false;
        this.templateTestResult = null;
        this.templateTestError = null;
        this.showParamDialog = false;
        // Template editor configuration for shared component
        this.templateEditorConfig = {
            allowEdit: true,
            showRunButton: true,
            compactMode: false
        };
        this.destroy$ = new Subject();
        this.activeTimeouts = [];
    }
    async ngOnInit() {
        await super.ngOnInit();
        await this.loadTemplateContents();
        await this.loadCategories();
        this.loadContentTypes();
    }
    ngOnDestroy() {
        this.destroy$.next();
        this.destroy$.complete();
        // Clean up any active timeouts
        this.activeTimeouts.forEach(timeoutId => clearTimeout(timeoutId));
        this.activeTimeouts.length = 0;
    }
    ngAfterViewInit() {
        // Initial sync when view is ready
        this.syncEditorValue();
    }
    async loadTemplateContents() {
        if (this.record && this.record.ID) {
            try {
                const rv = new RunView();
                const results = await rv.RunView({
                    EntityName: 'Template Contents',
                    ExtraFilter: `TemplateID='${this.record.ID}'`,
                    OrderBy: 'Priority ASC, __mj_CreatedAt ASC',
                    ResultType: 'entity_object'
                });
                this.templateContents = results.Results;
                // If we have contents but no selection, select the first one
                if (this.templateContents.length > 0 && this.selectedContentIndex === 0) {
                    this.selectedContentIndex = 0;
                }
                // If no template contents exist, create a default one for single-content optimization
                if (this.templateContents.length === 0) {
                    await this.createDefaultTemplateContent();
                }
                // Entity change tracking is handled automatically by BaseEntity
                // Sync editor value after loading content
                this.syncEditorValue();
            }
            catch (error) {
                console.error('Error loading template contents:', error);
            }
        }
    }
    async createDefaultTemplateContent() {
        const md = new Metadata();
        const defaultContent = await md.GetEntityObject('Template Contents');
        defaultContent.TemplateID = this.record.ID;
        defaultContent.Priority = 1;
        defaultContent.IsActive = true;
        // Set default to first real content type (skip "Select Type..." if it exists)
        const validContentTypes = this.contentTypeOptions.filter(option => option.value !== '');
        if (validContentTypes.length > 0) {
            defaultContent.TypeID = validContentTypes[0].value;
        }
        this.templateContents = [defaultContent];
        this.selectedContentIndex = 0;
        // Sync editor value after creating default content
        this.syncEditorValue();
    }
    selectTemplateContent(index, confirmSwitch = true) {
        // If we're adding new content and user clicks on existing content, ask for confirmation
        if (this.isAddingNewContent && confirmSwitch) {
            if (!confirm('You have unsaved changes to a new content version. Are you sure you want to switch? Your changes will be lost.')) {
                return;
            }
        }
        if (index >= 0 && index < this.templateContents.length) {
            this.selectedContentIndex = index;
            this.isAddingNewContent = false;
            // Don't clear newTemplateContent to preserve the work in progress
            // Sync editor value when switching content
            this.syncEditorValue();
        }
    }
    async loadCategories() {
        try {
            const rv = new RunView();
            const results = await rv.RunView({
                EntityName: 'Template Categories'
            });
            this.categoryOptions = [
                { text: 'Select Category...', value: '' },
                ...results.Results.map((cat) => ({
                    text: cat.Name,
                    value: cat.ID
                }))
            ];
        }
        catch (error) {
            console.error('Error loading categories:', error);
            this.categoryOptions = [{ text: 'Select Category...', value: '' }];
        }
    }
    loadContentTypes() {
        try {
            // Get content types from TemplateEngine cache
            const contentTypes = TemplateEngineBase.Instance.TemplateContentTypes;
            this.contentTypeOptions = [
                { text: 'Select Type...', value: '' },
                ...contentTypes.map(ct => ({
                    text: ct.Name,
                    value: ct.ID
                }))
            ];
        }
        catch (error) {
            console.error('Error loading content types:', error);
            // Fallback to basic types
            this.contentTypeOptions = [
                { text: 'Select Type...', value: '' },
                { text: 'HTML', value: 'HTML' },
                { text: 'Plain Text', value: 'Text' },
                { text: 'Markdown', value: 'Markdown' }
            ];
        }
    }
    async onCategoryChange(value) {
        // If it's a new category (string but not in existing options)
        if (value && !this.categoryOptions.find(opt => opt.value === value)) {
            // Check for duplicate category names (case-insensitive, trimmed)
            if (this.isDuplicateCategory(value)) {
                const existingCategory = this.categoryOptions.find(option => option.text && option.text.trim().toLowerCase() === value.trim().toLowerCase());
                if (existingCategory) {
                    // Use the existing category instead
                    this.record.CategoryID = existingCategory.value;
                    MJNotificationService.Instance.CreateSimpleNotification(`Category "${existingCategory.text}" already exists. Using existing category.`, 'warning');
                }
                return;
            }
            try {
                // Create new category with trimmed name
                const md = new Metadata();
                const newCategory = await md.GetEntityObject('Template Categories');
                newCategory.Name = value.trim();
                newCategory.UserID = this.record.UserID || md.CurrentUser.ID;
                const saved = await newCategory.Save();
                if (saved) {
                    // Add to options and set the ID
                    this.categoryOptions.push({
                        text: newCategory.Name,
                        value: newCategory.ID
                    });
                    this.record.CategoryID = newCategory.ID;
                    MJNotificationService.Instance.CreateSimpleNotification(`New category "${newCategory.Name}" created successfully.`, 'success');
                }
                else {
                    MJNotificationService.Instance.CreateSimpleNotification(`Failed to create new category. ${newCategory.LatestResult?.Message || ''}`, 'error');
                }
            }
            catch (error) {
                console.error('Error creating new category:', error);
                MJNotificationService.Instance.CreateSimpleNotification('Error creating new category. Please try again.', 'error');
            }
        }
    }
    async addNewTemplateContent() {
        const md = new Metadata();
        this.newTemplateContent = await md.GetEntityObject('Template Contents');
        this.newTemplateContent.TemplateID = this.record.ID;
        this.newTemplateContent.Priority = this.templateContents.length + 1;
        this.newTemplateContent.IsActive = true;
        // Set default to first real content type (skip "Select Type..." if it exists)
        const validContentTypes = this.contentTypeOptions.filter(option => option.value !== '');
        if (validContentTypes.length > 0) {
            this.newTemplateContent.TypeID = validContentTypes[0].value;
        }
        this.newTemplateContent.TemplateText = '';
        // Add immediately to the array
        this.templateContents.push(this.newTemplateContent);
        this.selectedContentIndex = this.templateContents.length - 1;
        this.isAddingNewContent = true;
        // Sync editor value when adding new content
        this.syncEditorValue();
    }
    cancelNewTemplateContent() {
        this.isAddingNewContent = false;
        this.newTemplateContent = null;
    }
    async deleteTemplateContent(index) {
        console.log('deleteTemplateContent called with index:', index);
        console.log('templateContents length:', this.templateContents.length);
        if (index >= 0 && index < this.templateContents.length) {
            const contentToDelete = this.templateContents[index];
            console.log('Content to delete:', contentToDelete);
            if (contentToDelete.ID) {
                try {
                    console.log('Attempting to delete content with ID:', contentToDelete.ID);
                    const result = await contentToDelete.Delete();
                    console.log('Delete result:', result);
                    if (result) {
                        this.templateContents.splice(index, 1);
                        // Adjust selected index if necessary
                        if (this.selectedContentIndex >= this.templateContents.length) {
                            this.selectedContentIndex = Math.max(0, this.templateContents.length - 1);
                        }
                        // If no contents remain, create a default one
                        if (this.templateContents.length === 0) {
                            await this.createDefaultTemplateContent();
                        }
                        console.log('Content deleted successfully');
                    }
                    else {
                        console.error('Delete returned false');
                        MJNotificationService.Instance.CreateSimpleNotification(`Failed to delete template content. ${contentToDelete.LatestResult.Message}`, 'error');
                    }
                }
                catch (error) {
                    console.error('Error deleting template content:', error);
                }
            }
            else {
                // Not saved yet, just remove from array
                console.log('Removing unsaved content from array');
                this.templateContents.splice(index, 1);
                if (this.selectedContentIndex >= this.templateContents.length) {
                    this.selectedContentIndex = Math.max(0, this.templateContents.length - 1);
                }
                // Reset adding new content state if we're deleting the new content
                if (this.isAddingNewContent && index === this.templateContents.length) {
                    this.isAddingNewContent = false;
                    this.newTemplateContent = null;
                }
                console.log('Unsaved content removed successfully');
            }
        }
        else {
            console.error('Invalid index for deletion:', index);
        }
    }
    get currentTemplateContent() {
        if (this.isAddingNewContent) {
            return this.newTemplateContent;
        }
        return this.templateContents[this.selectedContentIndex] || null;
    }
    get hasMultipleContents() {
        return this.templateContents.length > 1 || this.isAddingNewContent;
    }
    onContentTypeChange() {
        // Content type changes just modify the current content, no new record creation
        this.updateUnsavedChangesFlag();
    }
    onContentChange() {
        this.updateUnsavedChangesFlag();
    }
    /**
     * Updates the hasUnsavedChanges flag based on entity dirty states
     */
    updateUnsavedChangesFlag() {
        this.hasUnsavedChanges = this.templateContents.some(content => content.Dirty) ||
            this.isAddingNewContent ||
            this.record?.Dirty || false;
    }
    onTemplateTextChange(event) {
        if (this.isUpdatingEditorValue) {
            // Ignore change events when we're programmatically updating the editor
            return;
        }
        if (this.currentTemplateContent) {
            // Extract value from event - might be event.target.value or just event depending on component
            const value = typeof event === 'string' ? event : (event.target?.value || event);
            this.currentTemplateContent.TemplateText = value;
            // hasUnsavedChanges is automatically handled by entity's IsDirty flag
            this.updateUnsavedChangesFlag();
        }
    }
    /**
     * Helper method to track setTimeout calls for cleanup
     */
    setTrackedTimeout(callback, delay) {
        const timeoutId = setTimeout(() => {
            // Remove from tracking when it executes
            const index = this.activeTimeouts.indexOf(timeoutId);
            if (index > -1) {
                this.activeTimeouts.splice(index, 1);
            }
            callback();
        }, delay);
        this.activeTimeouts.push(timeoutId);
        return timeoutId;
    }
    /**
     * Manually sync the editor value without triggering change events
     */
    syncEditorValue() {
        // Use Promise.resolve() to wait for the next microtask after any pending changes
        Promise.resolve().then(() => {
            // Then tracked setTimeout for the next macrotask to ensure DOM is updated
            this.setTrackedTimeout(() => {
                if (!this.codeEditor) {
                    console.log('Code editor ViewChild is null - element may not be rendered yet');
                    console.log('currentTemplateContent exists:', !!this.currentTemplateContent);
                    return;
                }
                this.isUpdatingEditorValue = true;
                const newValue = this.currentTemplateContent?.TemplateText || '';
                // Use the setValue method from mj-code-editor component
                this.codeEditor.setValue(newValue);
                this.isUpdatingEditorValue = false;
            }, 0);
        });
    }
    async saveTemplateContents() {
        try {
            // Save all template contents that have changes
            for (const content of this.templateContents) {
                content.TemplateID = this.record.ID; // Ensure FK is set
                if (content.Dirty || !content.ID) {
                    const contentResult = await content.Save();
                    if (!contentResult) {
                        console.error('Failed to save template content:', content);
                        return false;
                    }
                }
            }
            this.isAddingNewContent = false;
            this.newTemplateContent = null;
            this.updateUnsavedChangesFlag(); // Update based on current entity states
            return true;
        }
        catch (error) {
            console.error('Error saving template contents:', error);
            return false;
        }
    }
    async SaveRecord(StopEditModeAfterSave = true) {
        // Check if we need to create a new category first
        if (this.record.CategoryID && !this.categoryOptions.find(opt => opt.value === this.record.CategoryID)) {
            // Check for duplicate category names (case-insensitive, trimmed)
            if (this.isDuplicateCategory(this.record.CategoryID)) {
                const existingCategory = this.categoryOptions.find(option => option.text && option.text.trim().toLowerCase() === this.record.CategoryID?.trim().toLowerCase());
                if (existingCategory) {
                    // Use the existing category instead
                    this.record.CategoryID = existingCategory.value;
                    MJNotificationService.Instance.CreateSimpleNotification(`Category "${existingCategory.text}" already exists. Using existing category.`, 'warning');
                }
            }
            else {
                try {
                    // Create new category with trimmed name
                    const md = new Metadata();
                    const newCategory = await md.GetEntityObject('Template Categories');
                    newCategory.Name = this.record.CategoryID.trim(); // CategoryID contains the new category name, trim it
                    newCategory.UserID = this.record.UserID || md.CurrentUser.ID;
                    const saved = await newCategory.Save();
                    if (saved) {
                        // Add to options and set the ID
                        this.categoryOptions.push({
                            text: newCategory.Name,
                            value: newCategory.ID
                        });
                        this.record.CategoryID = newCategory.ID;
                    }
                    else {
                        console.error('Failed to create new category');
                        MJNotificationService.Instance.CreateSimpleNotification(`Failed to create new category. ${newCategory.LatestResult?.Message || ''}`, 'error');
                        return false;
                    }
                }
                catch (error) {
                    console.error('Error creating new category during save:', error);
                    MJNotificationService.Instance.CreateSimpleNotification('Error creating new category during save. Please try again.', 'error');
                    return false;
                }
            }
        }
        // Call the parent save method to save the template
        // Before saving, if a new record, make sure the UserID is set
        if (!this.record.IsSaved && !this.record.UserID) {
            const md = new Metadata();
            this.record.UserID = md.CurrentUser.ID;
        }
        const templateSaved = await super.SaveRecord(StopEditModeAfterSave);
        if (templateSaved) {
            // Then save all template contents
            return await this.saveTemplateContents();
        }
        return false;
    }
    getContentTypeDisplayText(typeId) {
        if (!typeId)
            return '-';
        const option = this.contentTypeOptions.find(opt => opt.value === typeId);
        return option ? option.text : typeId;
    }
    getEditorLanguage() {
        if (!this.currentTemplateContent?.TypeID) {
            return 'jinja2'; // default to jinja2 for template syntax (compatible with Nunjucks)
        }
        const contentType = this.currentTemplateContent.TypeID.toLowerCase();
        // Map content types to CodeMirror language modes
        switch (contentType) {
            case 'html':
                return 'jinja2'; // Use jinja2 for HTML templates to get template syntax highlighting
            case 'markdown':
            case 'md':
                return 'markdown';
            case 'javascript':
            case 'js':
                return 'javascript';
            case 'css':
                return 'css';
            case 'json':
                return 'json';
            case 'xml':
                return 'xml';
            case 'sql':
                return 'sql';
            case 'text':
            case 'plain':
            default:
                return 'jinja2'; // Default to jinja2 since templates often contain template syntax
        }
    }
    isDuplicateCategory(categoryName) {
        const normalizedName = categoryName.trim().toLowerCase();
        return this.categoryOptions.some(option => option.text && option.text.trim().toLowerCase() === normalizedName);
    }
    /**
     * Test run the current template using the parameter dialog
     */
    async runTemplate() {
        if (!this.record?.IsSaved || !this.currentTemplateContent) {
            MJNotificationService.Instance.CreateSimpleNotification('Please save the template before running it.', 'warning');
            return;
        }
        // Save any unsaved changes first
        if (this.hasUnsavedChanges) {
            const saveResult = await this.SaveRecord(false); // Don't exit edit mode
            if (!saveResult) {
                MJNotificationService.Instance.CreateSimpleNotification('Failed to save template changes.', 'error');
                return;
            }
        }
        // Show the parameter dialog
        this.showParamDialog = true;
    }
    /**
     * Handle parameter dialog close
     */
    onParamDialogClose() {
        this.showParamDialog = false;
    }
    getContentTypeOptionsForContent() {
        // Always exclude "Select Type..." option for all content
        return this.contentTypeOptions.filter(option => option.value !== '');
    }
    /**
     * Handles template content changes from the shared editor
     */
    onSharedTemplateContentChange(content) {
        this.templateContents = content;
        this.updateUnsavedChangesFlag();
    }
    /**
     * Handles template run requests from the shared editor
     */
    onSharedTemplateRun(template) {
        this.runTemplate();
    }
    static { this.ɵfac = /*@__PURE__*/ (() => { let ɵTemplatesFormExtendedComponent_BaseFactory; return function TemplatesFormExtendedComponent_Factory(t) { return (ɵTemplatesFormExtendedComponent_BaseFactory || (ɵTemplatesFormExtendedComponent_BaseFactory = i0.ɵɵgetInheritedFactory(TemplatesFormExtendedComponent)))(t || TemplatesFormExtendedComponent); }; })(); }
    static { this.ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: TemplatesFormExtendedComponent, selectors: [["mj-templates-form"]], viewQuery: function TemplatesFormExtendedComponent_Query(rf, ctx) { if (rf & 1) {
            i0.ɵɵviewQuery(_c0, 5);
        } if (rf & 2) {
            let _t;
            i0.ɵɵqueryRefresh(_t = i0.ɵɵloadQuery()) && (ctx.codeEditor = _t.first);
        } }, features: [i0.ɵɵInheritDefinitionFeature], decls: 2, vars: 1, consts: [["form", "ngForm"], [1, "record-form-container"], [1, "record-form"], [3, "form"], [1, "template-header", 2, "background", "#f8f9fa", "border-bottom", "1px solid #dee2e6", "padding", "8px 20px"], [2, "display", "grid", "grid-template-columns", "1fr 2fr 1fr auto", "gap", "12px", "align-items", "start"], [1, "form-group", 2, "margin", "0"], [1, "form-label", 2, "font-weight", "500", "margin-bottom", "3px", "color", "#495057", "font-size", "0.85em"], [1, "fa-solid", "fa-file-text"], ["name", "templateName", "placeholder", "Enter template name...", 3, "ngModel"], [1, "form-control-plaintext", 2, "font-size", "1em", "font-weight", "500", "padding", "6px 0"], [1, "fa-solid", "fa-align-left"], ["name", "description", "placeholder", "Enter template description...", 3, "ngModel", "rows"], [1, "form-control-plaintext", 2, "padding", "8px 0", "color", "#6c757d"], [1, "fa-solid", "fa-folder"], ["name", "categoryId", "textField", "text", "valueField", "value", "placeholder", "Select or enter new category...", 3, "ngModel", "data", "valuePrimitive", "allowCustom"], [1, "form-control-plaintext", 2, "padding", "8px 0"], [2, "display", "flex", "flex-direction", "column", "align-items", "flex-end", "justify-content", "center"], [1, "badge", "badge-success", 2, "background", "#28a745", "color", "white", "padding", "6px 12px", "border-radius", "4px", "font-size", "0.85em"], [1, "badge", "badge-secondary", 2, "background", "#6c757d", "color", "white", "padding", "6px 12px", "border-radius", "4px", "font-size", "0.85em"], [3, "TabSelected", "ResizeContainer"], ["Name", "Contents"], [1, "fa-solid", "fa-file-lines"], [1, "badge", "badge-info", 2, "background", "#17a2b8", "color", "white", "padding", "2px 6px", "border-radius", "3px", "font-size", "0.7em", "margin-left", "6px"], [1, "template-contents-main", "content-margin"], [2, "height", "100%", "display", "block", 3, "contentChange", "runTemplate", "template", "config"], ["Name", "Details"], [1, "fa-solid", "fa-cogs"], [2, "padding", "20px"], ["FieldName", "UserPrompt", "Type", "textarea", 3, "record", "ShowLabel", "EditMode"], ["FieldName", "UserID", "Type", "textbox", "LinkType", "Record", "LinkComponentType", "Search", 3, "record", "ShowLabel", "EditMode"], ["FieldName", "ActiveAt", "Type", "datepicker", 3, "record", "ShowLabel", "EditMode"], ["FieldName", "DisabledAt", "Type", "datepicker", 3, "record", "ShowLabel", "EditMode"], ["FieldName", "IsActive", "Type", "checkbox", 3, "record", "ShowLabel", "EditMode"], ["FieldName", "__mj_CreatedAt", "Type", "textbox", 3, "record", "ShowLabel", "EditMode"], ["FieldName", "__mj_UpdatedAt", "Type", "textbox", 3, "record", "ShowLabel", "EditMode"], ["FieldName", "Category", "Type", "textbox", 3, "record", "ShowLabel", "EditMode"], ["FieldName", "User", "Type", "textbox", 3, "record", "ShowLabel", "EditMode"], ["Name", "Template Params", 3, "Visible"], [1, "fa-solid", "fa-sliders"], [3, "template", "editMode"], ["Name", "AI Prompts", 3, "Visible"], [1, "fa-solid", "fa-robot"], [3, "Params", "NewRecordValues", "AllowLoad", "EditMode"], ["Name", "Entity Documents", 3, "Visible"], [3, "isVisibleChange", "onClose", "template", "isVisible"], ["name", "templateName", "placeholder", "Enter template name...", 3, "ngModelChange", "ngModel"], ["name", "description", "placeholder", "Enter template description...", 3, "ngModelChange", "ngModel", "rows"], ["name", "categoryId", "textField", "text", "valueField", "value", "placeholder", "Select or enter new category...", 3, "ngModelChange", "valueChange", "ngModel", "data", "valuePrimitive", "allowCustom"], [1, "fa-solid", "fa-check-circle"], [1, "fa-solid", "fa-pause-circle"]], template: function TemplatesFormExtendedComponent_Template(rf, ctx) { if (rf & 1) {
            i0.ɵɵelementStart(0, "div", 1);
            i0.ɵɵtemplate(1, TemplatesFormExtendedComponent_Conditional_1_Template, 66, 50);
            i0.ɵɵelementEnd();
        } if (rf & 2) {
            i0.ɵɵadvance();
            i0.ɵɵconditional(ctx.record ? 1 : -1);
        } }, dependencies: [i1.ɵNgNoValidate, i1.NgControlStatus, i1.NgControlStatusGroup, i1.NgModel, i1.NgForm, i2.TextAreaComponent, i2.TextBoxComponent, i3.ComboBoxComponent, i4.UserViewGridComponent, i5.MJFormField, i6.FormToolbarComponent, i7.MJTabStripComponent, i7.MJTabBodyComponent, i7.MJTabComponent, i8.TemplateParamDialogComponent, i9.TemplateParamsGridComponent, i10.TemplateEditorComponent], styles: [".k-pane[_ngcontent-%COMP%] {\n  background-color: #F5F6FA;\n}\n\n.content-margin[_ngcontent-%COMP%] {\n  margin: 10px;\n} \n\n\na[_ngcontent-%COMP%] {\n  font-size: 14px;\n  font-weight: bolder;\n}\n\n.tab-header-icon[_ngcontent-%COMP%] {\n  margin-right: 5px;\n}\n\n.record-form[_ngcontent-%COMP%] {\n  display: block;\n  flex-direction: column;\n  background-color: #F5F6FA;\n  padding: 0;\n  min-height: 100vh;\n}\n\n.record-form-group[_ngcontent-%COMP%] {\n  margin-top: 0px;\n  background-color: #F5F6FA;\n}\n\nbutton[_ngcontent-%COMP%] {\n  margin-right: 5px;\n}\n\n.record-form[_ngcontent-%COMP%]   h2[_ngcontent-%COMP%] {\n  margin-bottom: 10px;\n}\n\n.k-splitter[_ngcontent-%COMP%] {\n  border-width: 0px;\n}\n\n.record-form-row[_ngcontent-%COMP%] {\n  display: grid;\n  grid-template-columns: auto 1fr;\n  align-items: start;\n  gap: 10px;\n  margin-bottom: 12px;\n  padding-top: 5px;\n  padding-bottom: 5px;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n.record-form[_ngcontent-%COMP%]   .record-form-row[_ngcontent-%COMP%]    > [_ngcontent-%COMP%]:first-child {\n  font-weight: bold;\n  padding-right: 10px;\n} \n\n.record-form[_ngcontent-%COMP%]   .record-form-row[_ngcontent-%COMP%]    > span[_ngcontent-%COMP%] {\n  white-space: pre-line;\n  max-height: 300px;\n  overflow: auto;\n}\n\n \n\n@media (min-width: 768px) {\n  .record-form-row[_ngcontent-%COMP%] {\n    flex-direction: row;\n    align-items: center;\n  }\n\n  .record-form-row[_ngcontent-%COMP%]   label[_ngcontent-%COMP%] {\n    width: 240px;\n    margin-bottom: 0;\n  }\n}\n\n\n\n.form-panels-container[_ngcontent-%COMP%] {\n  display: flex;\n  flex-direction: column;\n  gap: 16px;\n  padding: 16px;\n  background-color: #F5F6FA;\n}\n\n\n\n.form-panels-container[_ngcontent-%COMP%]    > .form-card[_ngcontent-%COMP%] {\n  width: 100%;\n}\n\n\n\n.form-panels-container[_ngcontent-%COMP%]   .related-entity-grid[_ngcontent-%COMP%] {\n  display: grid;\n  grid-template-columns: 1fr;\n  gap: 16px;\n  width: 100%;\n}\n\n\n\n@media (min-width: 1400px) {\n  .form-panels-container[_ngcontent-%COMP%]   .related-entity-grid[_ngcontent-%COMP%] {\n    grid-template-columns: repeat(auto-fit, minmax(600px, 1fr));\n  }\n}\n\n.form-card[_ngcontent-%COMP%] {\n  background: white;\n  border-radius: 8px;\n  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);\n  overflow: hidden;\n}\n\n.collapsible-card[_ngcontent-%COMP%] {\n  overflow: hidden;\n}\n\n.collapsible-header[_ngcontent-%COMP%] {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  padding: 20px 24px;\n  background: linear-gradient(135deg, #f9fafb 0%, #ffffff 100%);\n  border-bottom: 2px solid #e5e7eb;\n  cursor: pointer;\n  user-select: none;\n  transition: all 0.3s ease;\n}\n\n.collapsible-header[_ngcontent-%COMP%]:hover {\n  background: linear-gradient(135deg, #f3f4f6 0%, #f9fafb 100%);\n  border-bottom-color: #667eea;\n}\n\n.collapsible-title[_ngcontent-%COMP%] {\n  display: flex;\n  align-items: center;\n  gap: 12px;\n  flex: 1;\n}\n\n.collapsible-title[_ngcontent-%COMP%]   i[_ngcontent-%COMP%] {\n  font-size: 20px;\n  color: #667eea;\n}\n\n.collapsible-title[_ngcontent-%COMP%]   h3[_ngcontent-%COMP%] {\n  margin: 0;\n  font-size: 18px;\n  font-weight: 600;\n  color: #1f2937;\n}\n\n.collapsible-header[_ngcontent-%COMP%]   .collapse-icon[_ngcontent-%COMP%] {\n  color: #6b7280;\n  transition: transform 0.3s ease;\n}\n\n.collapsible-body[_ngcontent-%COMP%] {\n  max-height: 2000px;\n  overflow: hidden;\n  transition: max-height 0.4s ease, padding 0.4s ease, opacity 0.3s ease;\n  opacity: 1;\n}\n\n.collapsible-body.collapsed[_ngcontent-%COMP%] {\n  max-height: 0;\n  padding: 0;\n  opacity: 0;\n}\n\n.form-body[_ngcontent-%COMP%] {\n  padding: 24px;\n}\n\n\n\n.form-card.related-entity[_ngcontent-%COMP%] {\n  background: linear-gradient(135deg, #f0f9ff 0%, #ffffff 100%);\n  border-left: 3px solid #3b82f6;\n}\n\n.form-card.related-entity[_ngcontent-%COMP%]   .collapsible-header[_ngcontent-%COMP%] {\n  background: linear-gradient(135deg, #e0f2fe 0%, #f0f9ff 100%);\n}\n\n.form-card.related-entity[_ngcontent-%COMP%]   .collapsible-header[_ngcontent-%COMP%]:hover {\n  background: linear-gradient(135deg, #bfdbfe 0%, #e0f2fe 100%);\n  border-bottom-color: #3b82f6;\n}\n\n.form-card.related-entity[_ngcontent-%COMP%]   .collapsible-title[_ngcontent-%COMP%]   i[_ngcontent-%COMP%] {\n  color: #3b82f6;\n}\n\n\n\n.form-section-controls[_ngcontent-%COMP%] {\n  display: flex;\n  gap: 10px;\n  padding: 14px 18px;\n  background: linear-gradient(135deg, #f9fafb 0%, #ffffff 100%);\n  border-bottom: 2px solid #e5e7eb;\n  align-items: center;\n  flex-wrap: wrap;\n  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);\n}\n\n.form-section-controls[_ngcontent-%COMP%]   .control-group[_ngcontent-%COMP%] {\n  display: flex;\n  gap: 8px;\n  align-items: center;\n}\n\n.form-section-controls[_ngcontent-%COMP%]   button[_ngcontent-%COMP%] {\n  padding: 8px 14px;\n  font-size: 13px;\n  border: 1px solid #d1d5db;\n  background: white;\n  color: #374151;\n  border-radius: 6px;\n  cursor: pointer;\n  transition: all 0.2s;\n  margin-right: 0;\n  display: inline-flex;\n  align-items: center;\n  gap: 6px;\n  font-weight: 500;\n}\n\n.form-section-controls[_ngcontent-%COMP%]   button[_ngcontent-%COMP%]:hover {\n  background: #667eea;\n  color: white;\n  border-color: #667eea;\n  transform: translateY(-1px);\n  box-shadow: 0 2px 4px rgba(102, 126, 234, 0.2);\n}\n\n.form-section-controls[_ngcontent-%COMP%]   button[_ngcontent-%COMP%]:active {\n  transform: translateY(0);\n}\n\n.form-section-controls[_ngcontent-%COMP%]   button[_ngcontent-%COMP%]   i[_ngcontent-%COMP%] {\n  margin-right: 0;\n  font-size: 14px;\n}\n\n.form-section-controls[_ngcontent-%COMP%]   .section-search[_ngcontent-%COMP%] {\n  padding: 8px 14px;\n  font-size: 13px;\n  border: 1px solid #d1d5db;\n  border-radius: 6px;\n  width: 240px;\n  transition: all 0.2s;\n  background: white;\n}\n\n.form-section-controls[_ngcontent-%COMP%]   .section-search[_ngcontent-%COMP%]:focus {\n  outline: none;\n  border-color: #667eea;\n  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);\n}\n\n.form-section-controls[_ngcontent-%COMP%]   .section-search[_ngcontent-%COMP%]::placeholder {\n  color: #9ca3af;\n  font-style: italic;\n}\n\n.form-section-controls[_ngcontent-%COMP%]   .section-count[_ngcontent-%COMP%] {\n  font-size: 13px;\n  color: #6b7280;\n  margin-left: auto;\n  font-weight: 500;\n}\n\n\n\n.form-card.search-hidden[_ngcontent-%COMP%] {\n  display: none;\n}\n\n\n\n.section-count-badge[_ngcontent-%COMP%] {\n  background: #667eea;\n  color: white;\n  padding: 2px 8px;\n  border-radius: 12px;\n  font-size: 12px;\n  font-weight: 600;\n}\n\n\n\n.collapsible-title[_ngcontent-%COMP%]   h3[_ngcontent-%COMP%]   .search-highlight[_ngcontent-%COMP%] {\n  background-color: #fef08a;\n  color: #854d0e;\n  padding: 2px 4px;\n  border-radius: 3px;\n  font-weight: 700;\n}\n\n\n\n.collapsible-title[_ngcontent-%COMP%]   .row-count-badge[_ngcontent-%COMP%] {\n  background: #10b981;\n  color: white;\n  padding: 3px 6px 2px 6px;\n  border-radius: 12px;\n  font-size: 12px;\n  font-weight: 600;\n  margin-left: 8px;\n  vertical-align: middle;\n  position: relative;\n  top: -2px;\n  display: inline-block;\n  line-height: 1;\n}\n\n\n\n.collapsible-title[_ngcontent-%COMP%]   .row-count-badge.zero-rows[_ngcontent-%COMP%] {\n  background: #9ca3af;\n}"] }); }
};
TemplatesFormExtendedComponent = __decorate([
    RegisterClass(BaseFormComponent, 'Templates')
], TemplatesFormExtendedComponent);
export { TemplatesFormExtendedComponent };
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(TemplatesFormExtendedComponent, [{
        type: Component,
        args: [{ selector: 'mj-templates-form', template: "<div class=\"record-form-container\">\n    @if (record) {\n        <form class=\"record-form\" #form=\"ngForm\" >\n        <mj-form-toolbar [form]=\"this\"></mj-form-toolbar>\n\n        <!-- Top Section - Key Fields -->\n        <div class=\"template-header\" style=\"background: #f8f9fa; border-bottom: 1px solid #dee2e6; padding: 8px 20px;\">\n            <div style=\"display: grid; grid-template-columns: 1fr 2fr 1fr auto; gap: 12px; align-items: start;\">\n                \n                <!-- Name -->\n                <div class=\"form-group\" style=\"margin: 0;\">\n                    <label class=\"form-label\" style=\"font-weight: 500; margin-bottom: 3px; color: #495057; font-size: 0.85em;\">\n                        <i class=\"fa-solid fa-file-text\"></i> Template Name\n                    </label>\n                    @if (EditMode) {\n                        <kendo-textbox [(ngModel)]=\"record.Name\" name=\"templateName\" placeholder=\"Enter template name...\"></kendo-textbox>\n                    } @else {\n                        <div class=\"form-control-plaintext\" style=\"font-size: 1em; font-weight: 500; padding: 6px 0;\">\n                            {{ record.Name || 'Unnamed Template' }}\n                        </div>\n                    }\n                </div>\n\n                <!-- Description -->\n                <div class=\"form-group\" style=\"margin: 0;\">\n                    <label class=\"form-label\" style=\"font-weight: 500; margin-bottom: 3px; color: #495057; font-size: 0.85em;\">\n                        <i class=\"fa-solid fa-align-left\"></i> Description\n                    </label>\n                    @if (EditMode) {\n                        <kendo-textarea [(ngModel)]=\"record.Description\" \n                                       name=\"description\"\n                                       [rows]=\"2\"\n                                       placeholder=\"Enter template description...\"></kendo-textarea>\n                    } @else {\n                        <div class=\"form-control-plaintext\" style=\"padding: 8px 0; color: #6c757d;\">\n                            {{ record.Description || 'No description provided' }}\n                        </div>\n                    }\n                </div>\n\n                <!-- Category -->\n                <div class=\"form-group\" style=\"margin: 0;\">\n                    <label class=\"form-label\" style=\"font-weight: 500; margin-bottom: 3px; color: #495057; font-size: 0.85em;\">\n                        <i class=\"fa-solid fa-folder\"></i> Category\n                    </label>\n                    @if (EditMode) {\n                        <kendo-combobox [(ngModel)]=\"record.CategoryID\" \n                                       name=\"categoryId\"\n                                       [data]=\"categoryOptions\"\n                                       textField=\"text\"\n                                       valueField=\"value\"\n                                       [valuePrimitive]=\"true\"\n                                       [allowCustom]=\"true\"\n                                       (valueChange)=\"onCategoryChange($event)\"\n                                       placeholder=\"Select or enter new category...\">\n                        </kendo-combobox>\n                    } @else {\n                        <div class=\"form-control-plaintext\" style=\"padding: 8px 0;\">\n                            {{ record.Category || 'Uncategorized' }}\n                        </div>\n                    }\n                </div>\n\n                <!-- Template Status -->\n                <div style=\"display: flex; flex-direction: column; align-items: flex-end; justify-content: center;\">\n                    @if (record.IsActive) {\n                        <span class=\"badge badge-success\" style=\"background: #28a745; color: white; padding: 6px 12px; border-radius: 4px; font-size: 0.85em;\">\n                            <i class=\"fa-solid fa-check-circle\"></i> Active\n                        </span>\n                    } @else {\n                        <span class=\"badge badge-secondary\" style=\"background: #6c757d; color: white; padding: 6px 12px; border-radius: 4px; font-size: 0.85em;\">\n                            <i class=\"fa-solid fa-pause-circle\"></i> Inactive\n                        </span>\n                    }\n                </div>\n            </div>\n        </div>\n\n        <mj-tabstrip (TabSelected)=\"onTabSelect($event)\"  (ResizeContainer)=\"InvokeManualResize()\">\n            \n            <!-- Contents Tab - Main Focus -->\n            <mj-tab Name=\"Contents\">\n                <i class=\"fa-solid fa-file-lines\"></i> Contents \n                <span class=\"badge badge-info\" style=\"background: #17a2b8; color: white; padding: 2px 6px; border-radius: 3px; font-size: 0.7em; margin-left: 6px;\">\n                    {{ templateContents.length }}\n                </span>\n            </mj-tab>\n            <mj-tab-body>\n                <div class=\"template-contents-main content-margin\">\n                    <!-- Shared Template Editor -->\n                    <mj-template-editor \n                        [template]=\"record\"\n                        [config]=\"templateEditorConfig\"\n                        (contentChange)=\"onSharedTemplateContentChange($event)\"\n                        (runTemplate)=\"onSharedTemplateRun($event)\"\n                        style=\"height: 100%; display: block;\">\n                    </mj-template-editor>\n                </div>\n            </mj-tab-body>\n\n            <!-- Details Tab - Extra Fields -->\n            <mj-tab Name=\"Details\">\n                <i class=\"fa-solid fa-cogs\"></i> Details\n            </mj-tab>\n            <mj-tab-body>\n                <div style=\"padding: 20px;\">\n                    <div class=\"record-form\">\n                        <mj-form-field \n                            [record]=\"record\"\n                            [ShowLabel]=\"true\"\n                            FieldName=\"UserPrompt\"\n                            Type=\"textarea\"\n                            [EditMode]=\"EditMode\">\n                        </mj-form-field>\n                        <mj-form-field \n                            [record]=\"record\"\n                            [ShowLabel]=\"true\"\n                            FieldName=\"UserID\"\n                            Type=\"textbox\"\n                            [EditMode]=\"EditMode\"\n                            LinkType=\"Record\"\n                            LinkComponentType=\"Search\">\n                        </mj-form-field>\n                        <mj-form-field \n                            [record]=\"record\"\n                            [ShowLabel]=\"true\"\n                            FieldName=\"ActiveAt\"\n                            Type=\"datepicker\"\n                            [EditMode]=\"EditMode\">\n                        </mj-form-field>\n                        <mj-form-field \n                            [record]=\"record\"\n                            [ShowLabel]=\"true\"\n                            FieldName=\"DisabledAt\"\n                            Type=\"datepicker\"\n                            [EditMode]=\"EditMode\">\n                        </mj-form-field>\n                        <mj-form-field \n                            [record]=\"record\"\n                            [ShowLabel]=\"true\"\n                            FieldName=\"IsActive\"\n                            Type=\"checkbox\"\n                            [EditMode]=\"EditMode\">\n                        </mj-form-field>\n                        <mj-form-field \n                            [record]=\"record\"\n                            [ShowLabel]=\"true\"\n                            FieldName=\"__mj_CreatedAt\"\n                            Type=\"textbox\"\n                            [EditMode]=\"EditMode\">\n                        </mj-form-field>\n                        <mj-form-field \n                            [record]=\"record\"\n                            [ShowLabel]=\"true\"\n                            FieldName=\"__mj_UpdatedAt\"\n                            Type=\"textbox\"\n                            [EditMode]=\"EditMode\">\n                        </mj-form-field>\n                        <mj-form-field \n                            [record]=\"record\"\n                            [ShowLabel]=\"true\"\n                            FieldName=\"Category\"\n                            Type=\"textbox\"\n                            [EditMode]=\"EditMode\">\n                        </mj-form-field>\n                        <mj-form-field \n                            [record]=\"record\"\n                            [ShowLabel]=\"true\"\n                            FieldName=\"User\"\n                            Type=\"textbox\"\n                            [EditMode]=\"EditMode\">\n                        </mj-form-field>\n                    </div>\n                </div>\n            </mj-tab-body>\n\n            <!-- Template Params Tab -->\n            <mj-tab Name=\"Template Params\" [Visible]=\"record.IsSaved\"> \n                <i class=\"fa-solid fa-sliders\"></i> Parameters\n            </mj-tab>\n            <mj-tab-body>\n                <mj-template-params-grid \n                    [template]=\"record\"\n                    [editMode]=\"EditMode\">\n                </mj-template-params-grid>                    \n            </mj-tab-body>\n\n            <!-- AI Prompts Tab -->\n            <mj-tab Name=\"AI Prompts\" [Visible]=\"record.IsSaved\"> \n                <i class=\"fa-solid fa-robot\"></i> AI Prompts\n            </mj-tab>\n            <mj-tab-body>\n                <mj-user-view-grid \n                    [Params]=\"BuildRelationshipViewParamsByEntityName('AI Prompts','TemplateID')\"  \n                    [NewRecordValues]=\"NewRecordValues('AI Prompts')\"\n                    [AllowLoad]=\"IsCurrentTab('AI Prompts')\"  \n                    [EditMode]=\"GridEditMode()\"  \n                >\n                </mj-user-view-grid>                    \n            </mj-tab-body>\n\n            <!-- Entity Documents Tab -->\n            <mj-tab Name=\"Entity Documents\" [Visible]=\"record.IsSaved\"> \n                <i class=\"fa-solid fa-file-text\"></i> Documents\n            </mj-tab>\n            <mj-tab-body>\n                <mj-user-view-grid \n                    [Params]=\"BuildRelationshipViewParamsByEntityName('Entity Documents','TemplateID')\"  \n                    [NewRecordValues]=\"NewRecordValues('Entity Documents')\"\n                    [AllowLoad]=\"IsCurrentTab('Entity Documents')\"  \n                    [EditMode]=\"GridEditMode()\"  \n                >\n                </mj-user-view-grid>                    \n            </mj-tab-body>\n        </mj-tabstrip>\n        </form>\n\n        <!-- Template Parameter Dialog -->\n        <mj-template-param-dialog \n            [template]=\"record\"\n            [(isVisible)]=\"showParamDialog\"\n            (onClose)=\"onParamDialogClose()\">\n        </mj-template-param-dialog>\n    }\n</div>", styles: [".k-pane {\n  background-color: #F5F6FA;\n}\n\n.content-margin {\n  margin: 10px;\n} \n\n\na {\n  font-size: 14px;\n  font-weight: bolder;\n}\n\n.tab-header-icon {\n  margin-right: 5px;\n}\n\n.record-form {\n  display: block;\n  flex-direction: column;\n  background-color: #F5F6FA;\n  padding: 0;\n  min-height: 100vh;\n}\n\n.record-form-group {\n  margin-top: 0px;\n  background-color: #F5F6FA;\n}\n\nbutton {\n  margin-right: 5px;\n}\n\n.record-form h2 {\n  margin-bottom: 10px;\n}\n\n.k-splitter {\n  border-width: 0px;\n}\n\n.record-form-row {\n  display: grid;\n  grid-template-columns: auto 1fr;\n  align-items: start;\n  gap: 10px;\n  margin-bottom: 12px;\n  padding-top: 5px;\n  padding-bottom: 5px;\n}\n\n\n/* .record-form .record-form-row:nth-child(odd) {\n  background-color: #f2f2f2; \n} */\n\n/* \n.record-form .record-form-row:nth-child(even) {\n  background-color: #ffffff;  \n} */\n\n.record-form .record-form-row > :first-child {\n  font-weight: bold;\n  padding-right: 10px;\n} \n\n.record-form .record-form-row > span {\n  white-space: pre-line;\n  max-height: 300px;\n  overflow: auto;\n}\n\n \n\n@media (min-width: 768px) {\n  .record-form-row {\n    flex-direction: row;\n    align-items: center;\n  }\n\n  .record-form-row label {\n    width: 240px;\n    margin-bottom: 0;\n  }\n}\n\n/* Collapsible Panel Styles */\n.form-panels-container {\n  display: flex;\n  flex-direction: column;\n  gap: 16px;\n  padding: 16px;\n  background-color: #F5F6FA;\n}\n\n/* All field sections take full width */\n.form-panels-container > .form-card {\n  width: 100%;\n}\n\n/* Related entity grid container - responsive layout */\n.form-panels-container .related-entity-grid {\n  display: grid;\n  grid-template-columns: 1fr;\n  gap: 16px;\n  width: 100%;\n}\n\n/* Responsive multi-column layout for related entities on wider screens */\n@media (min-width: 1400px) {\n  .form-panels-container .related-entity-grid {\n    grid-template-columns: repeat(auto-fit, minmax(600px, 1fr));\n  }\n}\n\n.form-card {\n  background: white;\n  border-radius: 8px;\n  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);\n  overflow: hidden;\n}\n\n.collapsible-card {\n  overflow: hidden;\n}\n\n.collapsible-header {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  padding: 20px 24px;\n  background: linear-gradient(135deg, #f9fafb 0%, #ffffff 100%);\n  border-bottom: 2px solid #e5e7eb;\n  cursor: pointer;\n  user-select: none;\n  transition: all 0.3s ease;\n}\n\n.collapsible-header:hover {\n  background: linear-gradient(135deg, #f3f4f6 0%, #f9fafb 100%);\n  border-bottom-color: #667eea;\n}\n\n.collapsible-title {\n  display: flex;\n  align-items: center;\n  gap: 12px;\n  flex: 1;\n}\n\n.collapsible-title i {\n  font-size: 20px;\n  color: #667eea;\n}\n\n.collapsible-title h3 {\n  margin: 0;\n  font-size: 18px;\n  font-weight: 600;\n  color: #1f2937;\n}\n\n.collapsible-header .collapse-icon {\n  color: #6b7280;\n  transition: transform 0.3s ease;\n}\n\n.collapsible-body {\n  max-height: 2000px;\n  overflow: hidden;\n  transition: max-height 0.4s ease, padding 0.4s ease, opacity 0.3s ease;\n  opacity: 1;\n}\n\n.collapsible-body.collapsed {\n  max-height: 0;\n  padding: 0;\n  opacity: 0;\n}\n\n.form-body {\n  padding: 24px;\n}\n\n/* Related Entity Sections - Visual Distinction */\n.form-card.related-entity {\n  background: linear-gradient(135deg, #f0f9ff 0%, #ffffff 100%);\n  border-left: 3px solid #3b82f6;\n}\n\n.form-card.related-entity .collapsible-header {\n  background: linear-gradient(135deg, #e0f2fe 0%, #f0f9ff 100%);\n}\n\n.form-card.related-entity .collapsible-header:hover {\n  background: linear-gradient(135deg, #bfdbfe 0%, #e0f2fe 100%);\n  border-bottom-color: #3b82f6;\n}\n\n.form-card.related-entity .collapsible-title i {\n  color: #3b82f6;\n}\n\n/* Section Controls */\n.form-section-controls {\n  display: flex;\n  gap: 10px;\n  padding: 14px 18px;\n  background: linear-gradient(135deg, #f9fafb 0%, #ffffff 100%);\n  border-bottom: 2px solid #e5e7eb;\n  align-items: center;\n  flex-wrap: wrap;\n  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);\n}\n\n.form-section-controls .control-group {\n  display: flex;\n  gap: 8px;\n  align-items: center;\n}\n\n.form-section-controls button {\n  padding: 8px 14px;\n  font-size: 13px;\n  border: 1px solid #d1d5db;\n  background: white;\n  color: #374151;\n  border-radius: 6px;\n  cursor: pointer;\n  transition: all 0.2s;\n  margin-right: 0;\n  display: inline-flex;\n  align-items: center;\n  gap: 6px;\n  font-weight: 500;\n}\n\n.form-section-controls button:hover {\n  background: #667eea;\n  color: white;\n  border-color: #667eea;\n  transform: translateY(-1px);\n  box-shadow: 0 2px 4px rgba(102, 126, 234, 0.2);\n}\n\n.form-section-controls button:active {\n  transform: translateY(0);\n}\n\n.form-section-controls button i {\n  margin-right: 0;\n  font-size: 14px;\n}\n\n.form-section-controls .section-search {\n  padding: 8px 14px;\n  font-size: 13px;\n  border: 1px solid #d1d5db;\n  border-radius: 6px;\n  width: 240px;\n  transition: all 0.2s;\n  background: white;\n}\n\n.form-section-controls .section-search:focus {\n  outline: none;\n  border-color: #667eea;\n  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);\n}\n\n.form-section-controls .section-search::placeholder {\n  color: #9ca3af;\n  font-style: italic;\n}\n\n.form-section-controls .section-count {\n  font-size: 13px;\n  color: #6b7280;\n  margin-left: auto;\n  font-weight: 500;\n}\n\n/* Hidden sections for search filter */\n.form-card.search-hidden {\n  display: none;\n}\n\n/* Section count badge */\n.section-count-badge {\n  background: #667eea;\n  color: white;\n  padding: 2px 8px;\n  border-radius: 12px;\n  font-size: 12px;\n  font-weight: 600;\n}\n\n/* Search highlighting in section names */\n.collapsible-title h3 .search-highlight {\n  background-color: #fef08a;\n  color: #854d0e;\n  padding: 2px 4px;\n  border-radius: 3px;\n  font-weight: 700;\n}\n\n/* Row count badge in section headers */\n.collapsible-title .row-count-badge {\n  background: #10b981;\n  color: white;\n  padding: 3px 6px 2px 6px;\n  border-radius: 12px;\n  font-size: 12px;\n  font-weight: 600;\n  margin-left: 8px;\n  vertical-align: middle;\n  position: relative;\n  top: -2px;\n  display: inline-block;\n  line-height: 1;\n}\n\n/* Gray badge for zero rows (loaded but empty) */\n.collapsible-title .row-count-badge.zero-rows {\n  background: #9ca3af;\n}\n"] }]
    }], null, { codeEditor: [{
            type: ViewChild,
            args: ['codeEditor']
        }] }); })();
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(TemplatesFormExtendedComponent, { className: "TemplatesFormExtendedComponent", filePath: "src/lib/custom/Templates/templates-form.component.ts", lineNumber: 22 }); })();
export function LoadTemplatesFormExtendedComponent() {
    // prevents tree shaking
}
//# sourceMappingURL=templates-form.component.js.map