/**
 * @fileoverview Classify · Org-level domain-context editor.
 *
 * Reads and writes the `classify.org.context` `MJ: Application Settings` record
 * scoped to the Knowledge Hub application. This is the ORG scope of the
 * three-tier classification context (org → content-type → source) consumed by
 * the server-side `ClassificationContextResolver` during autotagging.
 *
 * Persists via `ApplicationSettingEngine.SetSetting`, which creates the record
 * if absent (or updates it) and checks the Save() result. The Knowledge Hub
 * application ID is resolved by name via the threaded provider.
 */
import { Component, ChangeDetectorRef, inject } from '@angular/core';
import { RunView } from '@memberjunction/core';
import { BaseAngularComponent } from '@memberjunction/ng-base-types';
import { MJNotificationService } from '@memberjunction/ng-notifications';
import { ApplicationSettingEngine } from '@memberjunction/core-entities';
import * as i0 from "@angular/core";
import * as i1 from "@angular/forms";
import * as i2 from "@memberjunction/ng-shared-generic";
import * as i3 from "@memberjunction/ng-ui-components";
function ClassifyOrgContextEditorComponent_Conditional_5_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "span", 4);
    i0.ɵɵtext(1, "Unsaved");
    i0.ɵɵelementEnd();
} }
function ClassifyOrgContextEditorComponent_Conditional_7_Conditional_1_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelement(0, "mj-loading", 7);
} }
function ClassifyOrgContextEditorComponent_Conditional_7_Conditional_2_Conditional_5_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelement(0, "i", 12);
    i0.ɵɵtext(1, " Saving\u2026 ");
} }
function ClassifyOrgContextEditorComponent_Conditional_7_Conditional_2_Conditional_6_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelement(0, "i", 13);
    i0.ɵɵtext(1, " Save ");
} }
function ClassifyOrgContextEditorComponent_Conditional_7_Conditional_2_Template(rf, ctx) { if (rf & 1) {
    const _r1 = i0.ɵɵgetCurrentView();
    i0.ɵɵelementStart(0, "p", 8);
    i0.ɵɵtext(1, " Applies to every source as the broadest classification-context scope. Source and content-type guidance combine with this at run time. ");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(2, "textarea", 9);
    i0.ɵɵtwoWayListener("ngModelChange", function ClassifyOrgContextEditorComponent_Conditional_7_Conditional_2_Template_textarea_ngModelChange_2_listener($event) { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(2); i0.ɵɵtwoWayBindingSet(ctx_r1.ContextText, $event) || (ctx_r1.ContextText = $event); return i0.ɵɵresetView($event); });
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(3, "div", 10)(4, "button", 11);
    i0.ɵɵlistener("click", function ClassifyOrgContextEditorComponent_Conditional_7_Conditional_2_Template_button_click_4_listener() { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(2); return i0.ɵɵresetView(ctx_r1.Save()); });
    i0.ɵɵconditionalCreate(5, ClassifyOrgContextEditorComponent_Conditional_7_Conditional_2_Conditional_5_Template, 2, 0)(6, ClassifyOrgContextEditorComponent_Conditional_7_Conditional_2_Conditional_6_Template, 2, 0);
    i0.ɵɵelementEnd()();
} if (rf & 2) {
    const ctx_r1 = i0.ɵɵnextContext(2);
    i0.ɵɵadvance(2);
    i0.ɵɵtwoWayProperty("ngModel", ctx_r1.ContextText);
    i0.ɵɵadvance(2);
    i0.ɵɵproperty("disabled", ctx_r1.IsSaving || !ctx_r1.HasUnsavedChanges);
    i0.ɵɵadvance();
    i0.ɵɵconditional(ctx_r1.IsSaving ? 5 : 6);
} }
function ClassifyOrgContextEditorComponent_Conditional_7_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "div", 6);
    i0.ɵɵconditionalCreate(1, ClassifyOrgContextEditorComponent_Conditional_7_Conditional_1_Template, 1, 0, "mj-loading", 7)(2, ClassifyOrgContextEditorComponent_Conditional_7_Conditional_2_Template, 7, 3);
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const ctx_r1 = i0.ɵɵnextContext();
    i0.ɵɵadvance();
    i0.ɵɵconditional(ctx_r1.IsLoading ? 1 : 2);
} }
const KNOWLEDGE_HUB_APPLICATION_NAME = 'Knowledge Hub';
const CLASSIFY_ORG_CONTEXT_SETTING_KEY = 'classify.org.context';
export class ClassifyOrgContextEditorComponent extends BaseAngularComponent {
    cdr = inject(ChangeDetectorRef);
    /** Whether the editor body is expanded. */
    Expanded = false;
    /** The org-context text bound to the textarea. */
    ContextText = '';
    /** The value last loaded/saved, used to detect unsaved edits. */
    savedText = '';
    /** Loading spinner while reading the setting. */
    IsLoading = false;
    /** Saving spinner. */
    IsSaving = false;
    /** Whether the initial load has run. */
    loaded = false;
    khApplicationID = undefined;
    /** True when the textarea differs from the persisted value. */
    get HasUnsavedChanges() {
        return this.ContextText !== this.savedText;
    }
    /** Toggle the editor open/closed, lazy-loading the value the first time. */
    async Toggle() {
        this.Expanded = !this.Expanded;
        if (this.Expanded && !this.loaded) {
            await this.load();
        }
        this.cdr.detectChanges();
    }
    async resolveKnowledgeHubApplicationID() {
        if (this.khApplicationID !== undefined)
            return this.khApplicationID;
        const rv = RunView.FromMetadataProvider(this.ProviderToUse);
        const result = await rv.RunView({
            EntityName: 'MJ: Applications',
            ExtraFilter: `Name = '${KNOWLEDGE_HUB_APPLICATION_NAME.replace(/'/g, "''")}'`,
            Fields: ['ID'],
            MaxRows: 1,
            ResultType: 'simple',
        });
        this.khApplicationID = result.Success && result.Results.length > 0 ? result.Results[0].ID : null;
        return this.khApplicationID;
    }
    async load() {
        this.IsLoading = true;
        this.cdr.detectChanges();
        try {
            const p = this.ProviderToUse;
            await ApplicationSettingEngine.Instance.Config(false, p.CurrentUser, p);
            const appID = await this.resolveKnowledgeHubApplicationID();
            const raw = ApplicationSettingEngine.Instance.GetSetting(CLASSIFY_ORG_CONTEXT_SETTING_KEY, appID ?? undefined);
            this.ContextText = raw ?? '';
            this.savedText = this.ContextText;
            this.loaded = true;
        }
        catch (error) {
            const msg = error instanceof Error ? error.message : String(error);
            MJNotificationService.Instance.CreateSimpleNotification(`Failed to load org context: ${msg}`, 'error', 4000);
        }
        finally {
            this.IsLoading = false;
            this.cdr.detectChanges();
        }
    }
    /** Persist the org-level context to the Knowledge Hub application scope. */
    async Save() {
        if (this.IsSaving)
            return;
        this.IsSaving = true;
        this.cdr.detectChanges();
        try {
            const p = this.ProviderToUse;
            const appID = await this.resolveKnowledgeHubApplicationID();
            const ok = await ApplicationSettingEngine.Instance.SetSetting(CLASSIFY_ORG_CONTEXT_SETTING_KEY, this.ContextText, appID ?? undefined, p.CurrentUser);
            if (ok) {
                this.savedText = this.ContextText;
                MJNotificationService.Instance.CreateSimpleNotification('Org context saved', 'success', 2500);
            }
            else {
                MJNotificationService.Instance.CreateSimpleNotification('Failed to save org context', 'error', 4000);
            }
        }
        catch (error) {
            const msg = error instanceof Error ? error.message : String(error);
            MJNotificationService.Instance.CreateSimpleNotification(`Error: ${msg}`, 'error', 4000);
        }
        finally {
            this.IsSaving = false;
            this.cdr.detectChanges();
        }
    }
    static ɵfac = /*@__PURE__*/ (() => { let ɵClassifyOrgContextEditorComponent_BaseFactory; return function ClassifyOrgContextEditorComponent_Factory(__ngFactoryType__) { return (ɵClassifyOrgContextEditorComponent_BaseFactory || (ɵClassifyOrgContextEditorComponent_BaseFactory = i0.ɵɵgetInheritedFactory(ClassifyOrgContextEditorComponent)))(__ngFactoryType__ || ClassifyOrgContextEditorComponent); }; })();
    static ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: ClassifyOrgContextEditorComponent, selectors: [["classify-org-context-editor"]], standalone: false, features: [i0.ɵɵInheritDefinitionFeature], decls: 8, vars: 6, consts: [[1, "cls-org-ctx"], [1, "cls-org-ctx-head", 3, "click"], [1, "fa-solid", "fa-building"], [1, "cls-org-ctx-title"], [1, "cls-org-ctx-dirty"], [1, "fa-solid"], [1, "cls-org-ctx-body"], ["text", "Loading org context\u2026", "size", "small"], [1, "cls-org-ctx-help"], ["rows", "5", "placeholder", "Org-wide guidance for the classifier \u2014 your organization's domain, audience, taxonomy conventions\u2026", 1, "mj-textarea", 3, "ngModelChange", "ngModel"], [1, "cls-org-ctx-actions"], ["mjButton", "", "variant", "primary", "size", "sm", 3, "click", "disabled"], [1, "fa-solid", "fa-spinner", "fa-spin"], [1, "fa-solid", "fa-check"]], template: function ClassifyOrgContextEditorComponent_Template(rf, ctx) { if (rf & 1) {
            i0.ɵɵelementStart(0, "div", 0)(1, "button", 1);
            i0.ɵɵlistener("click", function ClassifyOrgContextEditorComponent_Template_button_click_1_listener() { return ctx.Toggle(); });
            i0.ɵɵelement(2, "i", 2);
            i0.ɵɵelementStart(3, "span", 3);
            i0.ɵɵtext(4, "Organization domain context");
            i0.ɵɵelementEnd();
            i0.ɵɵconditionalCreate(5, ClassifyOrgContextEditorComponent_Conditional_5_Template, 2, 0, "span", 4);
            i0.ɵɵelement(6, "i", 5);
            i0.ɵɵelementEnd();
            i0.ɵɵconditionalCreate(7, ClassifyOrgContextEditorComponent_Conditional_7_Template, 3, 1, "div", 6);
            i0.ɵɵelementEnd();
        } if (rf & 2) {
            i0.ɵɵadvance(5);
            i0.ɵɵconditional(ctx.HasUnsavedChanges ? 5 : -1);
            i0.ɵɵadvance();
            i0.ɵɵclassProp("fa-chevron-down", !ctx.Expanded)("fa-chevron-up", ctx.Expanded);
            i0.ɵɵadvance();
            i0.ɵɵconditional(ctx.Expanded ? 7 : -1);
        } }, dependencies: [i1.DefaultValueAccessor, i1.NgControlStatus, i1.NgModel, i2.LoadingComponent, i3.MJButtonDirective], styles: [".cls-org-ctx[_ngcontent-%COMP%] {\n    border: 1px solid var(--mj-border-default);\n    border-radius: 8px;\n    background: var(--mj-bg-surface);\n    overflow: hidden;\n}\n.cls-org-ctx-head[_ngcontent-%COMP%] {\n    display: flex;\n    align-items: center;\n    gap: 10px;\n    width: 100%;\n    padding: 12px 14px;\n    background: var(--mj-bg-surface-card);\n    border: none;\n    cursor: pointer;\n    font-size: 0.88rem;\n    font-weight: 600;\n    color: var(--mj-text-primary);\n    text-align: left;\n}\n.cls-org-ctx-head[_ngcontent-%COMP%]    > i[_ngcontent-%COMP%]:first-child { color: var(--mj-brand-primary); }\n.cls-org-ctx-title[_ngcontent-%COMP%] { flex: 1; }\n.cls-org-ctx-dirty[_ngcontent-%COMP%] {\n    font-size: 0.72rem;\n    font-weight: 600;\n    color: var(--mj-status-warning-text);\n    background: color-mix(in srgb, var(--mj-status-warning) 12%, var(--mj-bg-surface));\n    border: 1px solid var(--mj-status-warning-border, var(--mj-border-default));\n    border-radius: 999px;\n    padding: 2px 8px;\n}\n.cls-org-ctx-body[_ngcontent-%COMP%] {\n    padding: 14px;\n    border-top: 1px solid var(--mj-border-subtle);\n}\n.cls-org-ctx-help[_ngcontent-%COMP%] {\n    margin: 0 0 10px;\n    font-size: 0.8rem;\n    color: var(--mj-text-muted);\n    line-height: 1.45;\n}\n.cls-org-ctx-actions[_ngcontent-%COMP%] {\n    margin-top: 10px;\n    display: flex;\n    gap: 8px;\n}"] });
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(ClassifyOrgContextEditorComponent, [{
        type: Component,
        args: [{ standalone: false, selector: 'classify-org-context-editor', template: "<div class=\"cls-org-ctx\">\n    <button class=\"cls-org-ctx-head\" (click)=\"Toggle()\">\n        <i class=\"fa-solid fa-building\"></i>\n        <span class=\"cls-org-ctx-title\">Organization domain context</span>\n        @if (HasUnsavedChanges) {\n            <span class=\"cls-org-ctx-dirty\">Unsaved</span>\n        }\n        <i class=\"fa-solid\" [class.fa-chevron-down]=\"!Expanded\" [class.fa-chevron-up]=\"Expanded\"></i>\n    </button>\n\n    @if (Expanded) {\n        <div class=\"cls-org-ctx-body\">\n            @if (IsLoading) {\n                <mj-loading text=\"Loading org context\u2026\" size=\"small\"></mj-loading>\n            } @else {\n                <p class=\"cls-org-ctx-help\">\n                    Applies to every source as the broadest classification-context scope. Source and\n                    content-type guidance combine with this at run time.\n                </p>\n                <textarea class=\"mj-textarea\" rows=\"5\"\n                          [(ngModel)]=\"ContextText\"\n                          placeholder=\"Org-wide guidance for the classifier \u2014 your organization's domain, audience, taxonomy conventions\u2026\"></textarea>\n                <div class=\"cls-org-ctx-actions\">\n                    <button mjButton variant=\"primary\" size=\"sm\" (click)=\"Save()\"\n                            [disabled]=\"IsSaving || !HasUnsavedChanges\">\n                        @if (IsSaving) { <i class=\"fa-solid fa-spinner fa-spin\"></i> Saving\u2026 }\n                        @else { <i class=\"fa-solid fa-check\"></i> Save }\n                    </button>\n                </div>\n            }\n        </div>\n    }\n</div>\n", styles: [".cls-org-ctx {\n    border: 1px solid var(--mj-border-default);\n    border-radius: 8px;\n    background: var(--mj-bg-surface);\n    overflow: hidden;\n}\n.cls-org-ctx-head {\n    display: flex;\n    align-items: center;\n    gap: 10px;\n    width: 100%;\n    padding: 12px 14px;\n    background: var(--mj-bg-surface-card);\n    border: none;\n    cursor: pointer;\n    font-size: 0.88rem;\n    font-weight: 600;\n    color: var(--mj-text-primary);\n    text-align: left;\n}\n.cls-org-ctx-head > i:first-child { color: var(--mj-brand-primary); }\n.cls-org-ctx-title { flex: 1; }\n.cls-org-ctx-dirty {\n    font-size: 0.72rem;\n    font-weight: 600;\n    color: var(--mj-status-warning-text);\n    background: color-mix(in srgb, var(--mj-status-warning) 12%, var(--mj-bg-surface));\n    border: 1px solid var(--mj-status-warning-border, var(--mj-border-default));\n    border-radius: 999px;\n    padding: 2px 8px;\n}\n.cls-org-ctx-body {\n    padding: 14px;\n    border-top: 1px solid var(--mj-border-subtle);\n}\n.cls-org-ctx-help {\n    margin: 0 0 10px;\n    font-size: 0.8rem;\n    color: var(--mj-text-muted);\n    line-height: 1.45;\n}\n.cls-org-ctx-actions {\n    margin-top: 10px;\n    display: flex;\n    gap: 8px;\n}\n"] }]
    }], null, null); })();
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(ClassifyOrgContextEditorComponent, { className: "ClassifyOrgContextEditorComponent", filePath: "src/AI/components/autotagging/components/classify-org-context-editor.component.ts", lineNumber: 28 }); })();
//# sourceMappingURL=classify-org-context-editor.component.js.map