import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy } from '@angular/core';
import { trigger, transition, style, animate } from '@angular/animations';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { LogError } from '@memberjunction/core';
import { UUIDsEqual } from '@memberjunction/global';
import { BaseAngularComponent } from '@memberjunction/ng-base-types';
import * as i0 from "@angular/core";
import * as i1 from "../../services/action-explorer-state.service";
import * as i2 from "@angular/forms";
import * as i3 from "@memberjunction/ng-ui-components";
function NewCategoryPanelComponent_Conditional_0_Conditional_9_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "mj-alert", 8);
    i0.ɵɵtext(1);
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const ctx_r1 = i0.ɵɵnextContext(2);
    i0.ɵɵadvance();
    i0.ɵɵtextInterpolate(ctx_r1.Errors["general"]);
} }
function NewCategoryPanelComponent_Conditional_0_Conditional_14_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "span", 12);
    i0.ɵɵtext(1);
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const ctx_r1 = i0.ɵɵnextContext(2);
    i0.ɵɵadvance();
    i0.ɵɵtextInterpolate(ctx_r1.Errors["name"]);
} }
function NewCategoryPanelComponent_Conditional_0_Conditional_27_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelement(0, "i", 21);
    i0.ɵɵtext(1, " Creating... ");
} }
function NewCategoryPanelComponent_Conditional_0_Conditional_28_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelement(0, "i", 22);
    i0.ɵɵtext(1, " Create Category ");
} }
function NewCategoryPanelComponent_Conditional_0_Template(rf, ctx) { if (rf & 1) {
    const _r1 = i0.ɵɵgetCurrentView();
    i0.ɵɵelementStart(0, "div", 1);
    i0.ɵɵlistener("click", function NewCategoryPanelComponent_Conditional_0_Template_div_click_0_listener($event) { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r1.onBackdropClick($event)); });
    i0.ɵɵelementStart(1, "div", 2)(2, "div", 3)(3, "h2");
    i0.ɵɵelement(4, "i", 4);
    i0.ɵɵtext(5, " New Category ");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(6, "button", 5);
    i0.ɵɵlistener("click", function NewCategoryPanelComponent_Conditional_0_Template_button_click_6_listener() { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r1.onClose()); });
    i0.ɵɵelement(7, "i", 6);
    i0.ɵɵelementEnd()();
    i0.ɵɵelementStart(8, "div", 7);
    i0.ɵɵconditionalCreate(9, NewCategoryPanelComponent_Conditional_0_Conditional_9_Template, 2, 1, "mj-alert", 8);
    i0.ɵɵelementStart(10, "div", 9)(11, "label", 10);
    i0.ɵɵtext(12, " Category Name ");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(13, "input", 11);
    i0.ɵɵtwoWayListener("ngModelChange", function NewCategoryPanelComponent_Conditional_0_Template_input_ngModelChange_13_listener($event) { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); i0.ɵɵtwoWayBindingSet(ctx_r1.Name, $event) || (ctx_r1.Name = $event); return i0.ɵɵresetView($event); });
    i0.ɵɵelementEnd();
    i0.ɵɵconditionalCreate(14, NewCategoryPanelComponent_Conditional_0_Conditional_14_Template, 2, 1, "span", 12);
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(15, "div", 9)(16, "label", 13);
    i0.ɵɵtext(17, " Description ");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(18, "textarea", 14);
    i0.ɵɵtwoWayListener("ngModelChange", function NewCategoryPanelComponent_Conditional_0_Template_textarea_ngModelChange_18_listener($event) { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); i0.ɵɵtwoWayBindingSet(ctx_r1.Description, $event) || (ctx_r1.Description = $event); return i0.ɵɵresetView($event); });
    i0.ɵɵelementEnd()();
    i0.ɵɵelementStart(19, "div", 9)(20, "label", 15);
    i0.ɵɵtext(21, " Parent Category ");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(22, "mj-dropdown", 16);
    i0.ɵɵtwoWayListener("ngModelChange", function NewCategoryPanelComponent_Conditional_0_Template_mj_dropdown_ngModelChange_22_listener($event) { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); i0.ɵɵtwoWayBindingSet(ctx_r1.ParentID, $event) || (ctx_r1.ParentID = $event); return i0.ɵɵresetView($event); });
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(23, "span", 17);
    i0.ɵɵtext(24, " Leave empty to create a root-level category ");
    i0.ɵɵelementEnd()()();
    i0.ɵɵelementStart(25, "div", 18)(26, "button", 19);
    i0.ɵɵlistener("click", function NewCategoryPanelComponent_Conditional_0_Template_button_click_26_listener() { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r1.onSave()); });
    i0.ɵɵconditionalCreate(27, NewCategoryPanelComponent_Conditional_0_Conditional_27_Template, 2, 0)(28, NewCategoryPanelComponent_Conditional_0_Conditional_28_Template, 2, 0);
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(29, "button", 20);
    i0.ɵɵlistener("click", function NewCategoryPanelComponent_Conditional_0_Template_button_click_29_listener() { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r1.onClose()); });
    i0.ɵɵtext(30, " Cancel ");
    i0.ɵɵelementEnd()()()();
} if (rf & 2) {
    const ctx_r1 = i0.ɵɵnextContext();
    i0.ɵɵadvance();
    i0.ɵɵproperty("@slideIn", undefined);
    i0.ɵɵadvance(8);
    i0.ɵɵconditional(ctx_r1.Errors["general"] ? 9 : -1);
    i0.ɵɵadvance(4);
    i0.ɵɵclassProp("invalid", ctx_r1.Errors["name"]);
    i0.ɵɵtwoWayProperty("ngModel", ctx_r1.Name);
    i0.ɵɵproperty("maxlength", 200);
    i0.ɵɵadvance();
    i0.ɵɵconditional(ctx_r1.Errors["name"] ? 14 : -1);
    i0.ɵɵadvance(4);
    i0.ɵɵtwoWayProperty("ngModel", ctx_r1.Description);
    i0.ɵɵproperty("rows", 3)("maxlength", 1000);
    i0.ɵɵadvance(4);
    i0.ɵɵtwoWayProperty("ngModel", ctx_r1.ParentID);
    i0.ɵɵproperty("Data", ctx_r1.getParentOptions())("ValuePrimitive", true);
    i0.ɵɵadvance(4);
    i0.ɵɵproperty("disabled", ctx_r1.IsSaving);
    i0.ɵɵadvance();
    i0.ɵɵconditional(ctx_r1.IsSaving ? 27 : 28);
    i0.ɵɵadvance(2);
    i0.ɵɵproperty("disabled", ctx_r1.IsSaving);
} }
export class NewCategoryPanelComponent extends BaseAngularComponent {
    StateService;
    cdr;
    Categories = [];
    PreselectedParentId = null;
    CategoryCreated = new EventEmitter();
    Close = new EventEmitter();
    IsOpen = false;
    IsSaving = false;
    // Form fields
    Name = '';
    Description = '';
    ParentID = null;
    // Validation
    Errors = {};
    destroy$ = new Subject();
    constructor(StateService, cdr) {
        super();
        this.StateService = StateService;
        this.cdr = cdr;
    }
    ngOnInit() {
        this.StateService.NewCategoryPanelOpen$.pipe(takeUntil(this.destroy$)).subscribe(isOpen => {
            this.IsOpen = isOpen;
            if (isOpen) {
                this.resetForm();
                if (this.PreselectedParentId) {
                    this.ParentID = this.PreselectedParentId;
                }
            }
            this.cdr.markForCheck();
        });
    }
    ngOnDestroy() {
        this.destroy$.next();
        this.destroy$.complete();
    }
    resetForm() {
        this.Name = '';
        this.Description = '';
        this.ParentID = this.PreselectedParentId;
        this.Errors = {};
        this.IsSaving = false;
    }
    onClose() {
        this.StateService.closeNewCategoryPanel();
        this.Close.emit();
    }
    onBackdropClick(event) {
        if (event.target.classList.contains('panel-backdrop')) {
            this.onClose();
        }
    }
    validate() {
        this.Errors = {};
        if (!this.Name || this.Name.trim().length === 0) {
            this.Errors['name'] = 'Category name is required';
        }
        else if (this.Name.trim().length < 2) {
            this.Errors['name'] = 'Category name must be at least 2 characters';
        }
        else if (this.Name.trim().length > 200) {
            this.Errors['name'] = 'Category name must be less than 200 characters';
        }
        // Check for duplicate names within same parent
        const existingCategory = this.Categories.find(c => c.Name.toLowerCase() === this.Name.trim().toLowerCase() &&
            (c.ParentID || null) === (this.ParentID || null));
        if (existingCategory) {
            this.Errors['name'] = 'A category with this name already exists at this level';
        }
        return Object.keys(this.Errors).length === 0;
    }
    async onSave() {
        if (!this.validate()) {
            this.cdr.markForCheck();
            return;
        }
        this.IsSaving = true;
        this.cdr.markForCheck();
        try {
            const md = this.ProviderToUse;
            const category = await md.GetEntityObject('MJ: Action Categories');
            category.Name = this.Name.trim();
            category.Description = this.Description.trim() || null;
            category.ParentID = this.ParentID || null;
            const saved = await category.Save();
            if (saved) {
                this.CategoryCreated.emit(category);
                this.StateService.closeNewCategoryPanel();
            }
            else {
                this.Errors['general'] = 'Failed to save category. Please try again.';
            }
        }
        catch (error) {
            LogError('Failed to create category', undefined, error);
            this.Errors['general'] = 'An error occurred while creating the category.';
        }
        finally {
            this.IsSaving = false;
            this.cdr.markForCheck();
        }
    }
    getParentOptions() {
        const options = [
            { text: '(No Parent - Root Category)', value: null }
        ];
        // Sort categories by name for easier selection
        const sortedCategories = [...this.Categories].sort((a, b) => a.Name.localeCompare(b.Name));
        sortedCategories.forEach(category => {
            options.push({
                text: this.getCategoryPath(category),
                value: category.ID
            });
        });
        return options;
    }
    getCategoryPath(category) {
        const path = [category.Name];
        let currentParentId = category.ParentID;
        while (currentParentId) {
            const parent = this.Categories.find(c => UUIDsEqual(c.ID, currentParentId));
            if (parent) {
                path.unshift(parent.Name);
                currentParentId = parent.ParentID || null;
            }
            else {
                break;
            }
        }
        return path.join(' / ');
    }
    static ɵfac = function NewCategoryPanelComponent_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || NewCategoryPanelComponent)(i0.ɵɵdirectiveInject(i1.ActionExplorerStateService), i0.ɵɵdirectiveInject(i0.ChangeDetectorRef)); };
    static ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: NewCategoryPanelComponent, selectors: [["mj-new-category-panel"]], inputs: { Categories: "Categories", PreselectedParentId: "PreselectedParentId" }, outputs: { CategoryCreated: "CategoryCreated", Close: "Close" }, standalone: false, features: [i0.ɵɵInheritDefinitionFeature], decls: 1, vars: 1, consts: [[1, "panel-backdrop"], [1, "panel-backdrop", 3, "click"], [1, "slide-panel"], [1, "panel-header"], [1, "fa-solid", "fa-folder-plus"], ["mjButton", "", "variant", "flat", 3, "click"], [1, "fa-solid", "fa-times"], [1, "panel-content"], ["Variant", "error"], [1, "form-group"], ["for", "categoryName", 1, "form-label", "required"], ["type", "text", "id", "categoryName", "placeholder", "Enter category name", 1, "mj-input", 3, "ngModelChange", "ngModel", "maxlength"], [1, "error-text"], ["for", "categoryDescription", 1, "form-label"], ["id", "categoryDescription", "placeholder", "Optional description for this category", 1, "mj-textarea", 3, "ngModelChange", "ngModel", "rows", "maxlength"], ["for", "categoryParent", 1, "form-label"], ["TextField", "text", "ValueField", "value", 3, "ngModelChange", "ngModel", "Data", "ValuePrimitive"], [1, "help-text"], [1, "panel-footer"], ["mjButton", "", "variant", "primary", 3, "click", "disabled"], ["mjButton", "", "variant", "outline", 3, "click", "disabled"], [1, "fa-solid", "fa-spinner", "fa-spin"], [1, "fa-solid", "fa-check"]], template: function NewCategoryPanelComponent_Template(rf, ctx) { if (rf & 1) {
            i0.ɵɵconditionalCreate(0, NewCategoryPanelComponent_Conditional_0_Template, 31, 16, "div", 0);
        } if (rf & 2) {
            i0.ɵɵconditional(ctx.IsOpen ? 0 : -1);
        } }, dependencies: [i2.DefaultValueAccessor, i2.NgControlStatus, i2.MaxLengthValidator, i2.NgModel, i3.MJButtonDirective, i3.MJDropdownComponent, i3.MJAlertComponent], styles: [".panel-backdrop[_ngcontent-%COMP%] {\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background: var(--mj-bg-overlay);\n  z-index: 1000;\n  display: flex;\n  justify-content: flex-end;\n}\n\n.slide-panel[_ngcontent-%COMP%] {\n  width: 450px;\n  max-width: 100%;\n  height: 100%;\n  background: var(--mj-bg-surface-card);\n  box-shadow: -4px 0 24px rgba(0, 0, 0, 0.15);\n  display: flex;\n  flex-direction: column;\n}\n\n.panel-header[_ngcontent-%COMP%] {\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  padding: 20px 24px;\n  border-bottom: 1px solid var(--mj-border-default);\n}\n\n.panel-header[_ngcontent-%COMP%]   h2[_ngcontent-%COMP%] {\n  margin: 0;\n  font-size: 18px;\n  font-weight: 600;\n  display: flex;\n  align-items: center;\n  gap: 10px;\n  color: var(--mj-text-primary);\n}\n\n.panel-header[_ngcontent-%COMP%]   h2[_ngcontent-%COMP%]   i[_ngcontent-%COMP%] {\n  color: var(--mj-brand-primary);\n}\n\n.panel-content[_ngcontent-%COMP%] {\n  flex: 1;\n  padding: 24px;\n  overflow-y: auto;\n}\n\n\n.form-group[_ngcontent-%COMP%] {\n  margin-bottom: 20px;\n}\n\n.form-label[_ngcontent-%COMP%] {\n  display: block;\n  margin-bottom: 6px;\n  font-size: 13px;\n  font-weight: 600;\n  color: var(--mj-text-primary);\n}\n\n.form-label.required[_ngcontent-%COMP%]::after {\n  content: ' *';\n  color: var(--mj-status-error);\n}\n\n.error-text[_ngcontent-%COMP%] {\n  display: block;\n  margin-top: 4px;\n  font-size: 12px;\n  color: var(--mj-status-error);\n}\n\n.help-text[_ngcontent-%COMP%] {\n  display: block;\n  margin-top: 4px;\n  font-size: 12px;\n  color: var(--mj-text-muted);\n}\n\n.panel-footer[_ngcontent-%COMP%] {\n  display: flex;\n  gap: 12px;\n  padding: 16px 24px;\n  border-top: 1px solid var(--mj-border-default);\n  background: var(--mj-bg-page);\n}\n\n.panel-footer[_ngcontent-%COMP%]   button[_ngcontent-%COMP%] {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n}\n\n\n\n@media (max-width: 480px) {\n  .slide-panel[_ngcontent-%COMP%] {\n    width: 100%;\n  }\n}"], data: { animation: [
                trigger('slideIn', [
                    transition(':enter', [
                        style({ transform: 'translateX(100%)', opacity: 0 }),
                        animate('250ms ease-out', style({ transform: 'translateX(0)', opacity: 1 }))
                    ]),
                    transition(':leave', [
                        animate('200ms ease-in', style({ transform: 'translateX(100%)', opacity: 0 }))
                    ])
                ])
            ] }, changeDetection: 0 });
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(NewCategoryPanelComponent, [{
        type: Component,
        args: [{ standalone: false, selector: 'mj-new-category-panel', changeDetection: ChangeDetectionStrategy.OnPush, animations: [
                    trigger('slideIn', [
                        transition(':enter', [
                            style({ transform: 'translateX(100%)', opacity: 0 }),
                            animate('250ms ease-out', style({ transform: 'translateX(0)', opacity: 1 }))
                        ]),
                        transition(':leave', [
                            animate('200ms ease-in', style({ transform: 'translateX(100%)', opacity: 0 }))
                        ])
                    ])
                ], template: "@if (IsOpen) {\n  <div class=\"panel-backdrop\" (click)=\"onBackdropClick($event)\">\n    <div class=\"slide-panel\" @slideIn>\n      <div class=\"panel-header\">\n        <h2>\n          <i class=\"fa-solid fa-folder-plus\"></i>\n          New Category\n        </h2>\n        <button mjButton\n          variant=\"flat\"\n          (click)=\"onClose()\">\n          <i class=\"fa-solid fa-times\"></i>\n        </button>\n      </div>\n\n      <div class=\"panel-content\">\n        @if (Errors['general']) {\n          <mj-alert Variant=\"error\">{{ Errors['general'] }}</mj-alert>\n        }\n\n        <div class=\"form-group\">\n          <label for=\"categoryName\" class=\"form-label required\">\n            Category Name\n          </label>\n          <input type=\"text\" class=\"mj-input\"\n            id=\"categoryName\"\n            [(ngModel)]=\"Name\"\n            placeholder=\"Enter category name\"\n            [maxlength]=\"200\"\n            [class.invalid]=\"Errors['name']\" />\n          @if (Errors['name']) {\n            <span class=\"error-text\">{{ Errors['name'] }}</span>\n          }\n        </div>\n\n        <div class=\"form-group\">\n          <label for=\"categoryDescription\" class=\"form-label\">\n            Description\n          </label>\n          <textarea class=\"mj-textarea\"\n            id=\"categoryDescription\"\n            [(ngModel)]=\"Description\"\n            placeholder=\"Optional description for this category\"\n            [rows]=\"3\"\n            [maxlength]=\"1000\"></textarea>\n        </div>\n\n        <div class=\"form-group\">\n          <label for=\"categoryParent\" class=\"form-label\">\n            Parent Category\n          </label>\n          <mj-dropdown\n            [(ngModel)]=\"ParentID\"\n            [Data]=\"getParentOptions()\"\n            TextField=\"text\"\n            ValueField=\"value\"\n            [ValuePrimitive]=\"true\">\n          </mj-dropdown>\n          <span class=\"help-text\">\n            Leave empty to create a root-level category\n          </span>\n        </div>\n      </div>\n\n      <div class=\"panel-footer\">\n        <button mjButton\n          variant=\"primary\"\n          [disabled]=\"IsSaving\"\n          (click)=\"onSave()\">\n          @if (IsSaving) {\n            <i class=\"fa-solid fa-spinner fa-spin\"></i>\n            Creating...\n          } @else {\n            <i class=\"fa-solid fa-check\"></i>\n            Create Category\n          }\n        </button>\n        <button mjButton\n          variant=\"outline\"\n          [disabled]=\"IsSaving\"\n          (click)=\"onClose()\">\n          Cancel\n        </button>\n      </div>\n    </div>\n  </div>\n}\n", styles: [".panel-backdrop {\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background: var(--mj-bg-overlay);\n  z-index: 1000;\n  display: flex;\n  justify-content: flex-end;\n}\n\n.slide-panel {\n  width: 450px;\n  max-width: 100%;\n  height: 100%;\n  background: var(--mj-bg-surface-card);\n  box-shadow: -4px 0 24px rgba(0, 0, 0, 0.15);\n  display: flex;\n  flex-direction: column;\n}\n\n.panel-header {\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  padding: 20px 24px;\n  border-bottom: 1px solid var(--mj-border-default);\n}\n\n.panel-header h2 {\n  margin: 0;\n  font-size: 18px;\n  font-weight: 600;\n  display: flex;\n  align-items: center;\n  gap: 10px;\n  color: var(--mj-text-primary);\n}\n\n.panel-header h2 i {\n  color: var(--mj-brand-primary);\n}\n\n.panel-content {\n  flex: 1;\n  padding: 24px;\n  overflow-y: auto;\n}\n\n\n.form-group {\n  margin-bottom: 20px;\n}\n\n.form-label {\n  display: block;\n  margin-bottom: 6px;\n  font-size: 13px;\n  font-weight: 600;\n  color: var(--mj-text-primary);\n}\n\n.form-label.required::after {\n  content: ' *';\n  color: var(--mj-status-error);\n}\n\n.error-text {\n  display: block;\n  margin-top: 4px;\n  font-size: 12px;\n  color: var(--mj-status-error);\n}\n\n.help-text {\n  display: block;\n  margin-top: 4px;\n  font-size: 12px;\n  color: var(--mj-text-muted);\n}\n\n.panel-footer {\n  display: flex;\n  gap: 12px;\n  padding: 16px 24px;\n  border-top: 1px solid var(--mj-border-default);\n  background: var(--mj-bg-page);\n}\n\n.panel-footer button {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n}\n\n/* Mobile */\n@media (max-width: 480px) {\n  .slide-panel {\n    width: 100%;\n  }\n}\n"] }]
    }], () => [{ type: i1.ActionExplorerStateService }, { type: i0.ChangeDetectorRef }], { Categories: [{
            type: Input
        }], PreselectedParentId: [{
            type: Input
        }], CategoryCreated: [{
            type: Output
        }], Close: [{
            type: Output
        }] }); })();
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(NewCategoryPanelComponent, { className: "NewCategoryPanelComponent", filePath: "src/Actions/components/explorer/new-category-panel.component.ts", lineNumber: 38 }); })();
//# sourceMappingURL=new-category-panel.component.js.map