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 } from '@angular/core';
import { RegisterClass, UUIDsEqual } from '@memberjunction/global';
import { BaseResourceComponent } from '@memberjunction/ng-shared';
import { RunView } from '@memberjunction/core';
import { ActionEngineBase } from '@memberjunction/actions-base';
import * as i0 from "@angular/core";
import * as i1 from "@memberjunction/ng-notifications";
import * as i2 from "@angular/forms";
import * as i3 from "@memberjunction/ng-shared-generic";
import * as i4 from "@memberjunction/ng-list-management";
const _forTrack0 = ($index, $item) => $item.ID;
function CommunicationsNewMessageResource_Conditional_8_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelement(0, "i", 16);
    i0.ɵɵtext(1, " Previewing\u2026 ");
} }
function CommunicationsNewMessageResource_Conditional_9_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelement(0, "i", 17);
    i0.ɵɵtext(1, " Preview Audience ");
} }
function CommunicationsNewMessageResource_Conditional_11_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelement(0, "i", 16);
    i0.ɵɵtext(1, " Sending\u2026 ");
} }
function CommunicationsNewMessageResource_Conditional_12_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelement(0, "i", 18);
    i0.ɵɵtext(1, " Send ");
} }
function CommunicationsNewMessageResource_Conditional_20_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelement(0, "mj-loading", 12);
} }
function CommunicationsNewMessageResource_Conditional_21_For_6_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "option", 21);
    i0.ɵɵtext(1);
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const p_r3 = ctx.$implicit;
    i0.ɵɵproperty("ngValue", p_r3.ID);
    i0.ɵɵadvance();
    i0.ɵɵtextInterpolate(p_r3.Name);
} }
function CommunicationsNewMessageResource_Conditional_21_Conditional_7_For_6_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "option", 21);
    i0.ɵɵtext(1);
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const mt_r5 = ctx.$implicit;
    i0.ɵɵproperty("ngValue", mt_r5.ID);
    i0.ɵɵadvance();
    i0.ɵɵtextInterpolate(mt_r5.Name);
} }
function CommunicationsNewMessageResource_Conditional_21_Conditional_7_Template(rf, ctx) { if (rf & 1) {
    const _r4 = i0.ɵɵgetCurrentView();
    i0.ɵɵelementStart(0, "label", 19);
    i0.ɵɵtext(1, "Message type");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(2, "select", 20);
    i0.ɵɵtwoWayListener("ngModelChange", function CommunicationsNewMessageResource_Conditional_21_Conditional_7_Template_select_ngModelChange_2_listener($event) { i0.ɵɵrestoreView(_r4); const ctx_r1 = i0.ɵɵnextContext(2); i0.ɵɵtwoWayBindingSet(ctx_r1.selectedMessageTypeID, $event) || (ctx_r1.selectedMessageTypeID = $event); return i0.ɵɵresetView($event); });
    i0.ɵɵelementStart(3, "option", 21);
    i0.ɵɵtext(4, "Select a message type\u2026");
    i0.ɵɵelementEnd();
    i0.ɵɵrepeaterCreate(5, CommunicationsNewMessageResource_Conditional_21_Conditional_7_For_6_Template, 2, 2, "option", 21, _forTrack0);
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const ctx_r1 = i0.ɵɵnextContext(2);
    i0.ɵɵadvance(2);
    i0.ɵɵtwoWayProperty("ngModel", ctx_r1.selectedMessageTypeID);
    i0.ɵɵadvance();
    i0.ɵɵproperty("ngValue", null);
    i0.ɵɵadvance(2);
    i0.ɵɵrepeater(ctx_r1.filteredMessageTypes);
} }
function CommunicationsNewMessageResource_Conditional_21_Template(rf, ctx) { if (rf & 1) {
    const _r1 = i0.ɵɵgetCurrentView();
    i0.ɵɵelementStart(0, "label", 19);
    i0.ɵɵtext(1, "Channel");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(2, "select", 20);
    i0.ɵɵtwoWayListener("ngModelChange", function CommunicationsNewMessageResource_Conditional_21_Template_select_ngModelChange_2_listener($event) { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); i0.ɵɵtwoWayBindingSet(ctx_r1.selectedProviderID, $event) || (ctx_r1.selectedProviderID = $event); return i0.ɵɵresetView($event); });
    i0.ɵɵlistener("ngModelChange", function CommunicationsNewMessageResource_Conditional_21_Template_select_ngModelChange_2_listener() { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r1.onProviderChange()); });
    i0.ɵɵelementStart(3, "option", 21);
    i0.ɵɵtext(4, "Select a channel\u2026");
    i0.ɵɵelementEnd();
    i0.ɵɵrepeaterCreate(5, CommunicationsNewMessageResource_Conditional_21_For_6_Template, 2, 2, "option", 21, _forTrack0);
    i0.ɵɵelementEnd();
    i0.ɵɵconditionalCreate(7, CommunicationsNewMessageResource_Conditional_21_Conditional_7_Template, 7, 2);
    i0.ɵɵelementStart(8, "label", 19);
    i0.ɵɵtext(9, "From");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(10, "input", 22);
    i0.ɵɵtwoWayListener("ngModelChange", function CommunicationsNewMessageResource_Conditional_21_Template_input_ngModelChange_10_listener($event) { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); i0.ɵɵtwoWayBindingSet(ctx_r1.fromAddress, $event) || (ctx_r1.fromAddress = $event); return i0.ɵɵresetView($event); });
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(11, "label", 19);
    i0.ɵɵtext(12, "Subject");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(13, "input", 23);
    i0.ɵɵtwoWayListener("ngModelChange", function CommunicationsNewMessageResource_Conditional_21_Template_input_ngModelChange_13_listener($event) { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); i0.ɵɵtwoWayBindingSet(ctx_r1.subject, $event) || (ctx_r1.subject = $event); return i0.ɵɵresetView($event); });
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(14, "label", 19);
    i0.ɵɵtext(15, "Body");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(16, "textarea", 24);
    i0.ɵɵtwoWayListener("ngModelChange", function CommunicationsNewMessageResource_Conditional_21_Template_textarea_ngModelChange_16_listener($event) { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); i0.ɵɵtwoWayBindingSet(ctx_r1.body, $event) || (ctx_r1.body = $event); return i0.ɵɵresetView($event); });
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const ctx_r1 = i0.ɵɵnextContext();
    i0.ɵɵadvance(2);
    i0.ɵɵtwoWayProperty("ngModel", ctx_r1.selectedProviderID);
    i0.ɵɵadvance();
    i0.ɵɵproperty("ngValue", null);
    i0.ɵɵadvance(2);
    i0.ɵɵrepeater(ctx_r1.providers);
    i0.ɵɵadvance(2);
    i0.ɵɵconditional(ctx_r1.filteredMessageTypes.length > 0 ? 7 : -1);
    i0.ɵɵadvance(3);
    i0.ɵɵtwoWayProperty("ngModel", ctx_r1.fromAddress);
    i0.ɵɵadvance(3);
    i0.ɵɵtwoWayProperty("ngModel", ctx_r1.subject);
    i0.ɵɵadvance(3);
    i0.ɵɵproperty("placeholder", i0.ɵɵinterpolate1("Hi ", "{{FirstName}}", ",..."));
    i0.ɵɵtwoWayProperty("ngModel", ctx_r1.body);
} }
function CommunicationsNewMessageResource_Conditional_29_Template(rf, ctx) { if (rf & 1) {
    const _r6 = i0.ɵɵgetCurrentView();
    i0.ɵɵelementStart(0, "label", 25);
    i0.ɵɵtext(1, "Recipient field");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(2, "input", 26);
    i0.ɵɵtwoWayListener("ngModelChange", function CommunicationsNewMessageResource_Conditional_29_Template_input_ngModelChange_2_listener($event) { i0.ɵɵrestoreView(_r6); const ctx_r1 = i0.ɵɵnextContext(); i0.ɵɵtwoWayBindingSet(ctx_r1.recipientField, $event) || (ctx_r1.recipientField = $event); return i0.ɵɵresetView($event); });
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(3, "p", 27);
    i0.ɵɵtext(4, " Field on the audience entity that holds the recipient address. Records with no value will be skipped. ");
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const ctx_r1 = i0.ɵɵnextContext();
    i0.ɵɵadvance(2);
    i0.ɵɵtwoWayProperty("ngModel", ctx_r1.recipientField);
} }
function CommunicationsNewMessageResource_Conditional_30_Conditional_11_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "div", 33)(1, "span", 30);
    i0.ɵɵtext(2);
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(3, "span", 31);
    i0.ɵɵtext(4);
    i0.ɵɵelementEnd()();
} if (rf & 2) {
    const ctx_r1 = i0.ɵɵnextContext(2);
    i0.ɵɵadvance(2);
    i0.ɵɵtextInterpolate1("Skipped (missing ", ctx_r1.recipientField || "recipient", ")");
    i0.ɵɵadvance(2);
    i0.ɵɵtextInterpolate(ctx_r1.audienceSummary.SkippedCount);
} }
function CommunicationsNewMessageResource_Conditional_30_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "div", 28)(1, "div", 29)(2, "span", 30);
    i0.ɵɵtext(3, "Total audience");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(4, "span", 31);
    i0.ɵɵtext(5);
    i0.ɵɵelementEnd()();
    i0.ɵɵelementStart(6, "div", 32)(7, "span", 30);
    i0.ɵɵtext(8, "Will receive");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(9, "span", 31);
    i0.ɵɵtext(10);
    i0.ɵɵelementEnd()();
    i0.ɵɵconditionalCreate(11, CommunicationsNewMessageResource_Conditional_30_Conditional_11_Template, 5, 2, "div", 33);
    i0.ɵɵelementStart(12, "div", 34)(13, "span", 30);
    i0.ɵɵtext(14, "Entity");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(15, "span", 31);
    i0.ɵɵtext(16);
    i0.ɵɵelementEnd()()();
} if (rf & 2) {
    const ctx_r1 = i0.ɵɵnextContext();
    i0.ɵɵclassProp("summary-block--has-skips", ctx_r1.audienceSummary.SkippedCount > 0);
    i0.ɵɵadvance(5);
    i0.ɵɵtextInterpolate(ctx_r1.audienceSummary.TotalAudienceSize);
    i0.ɵɵadvance(5);
    i0.ɵɵtextInterpolate(ctx_r1.audienceSummary.WillReceiveCount);
    i0.ɵɵadvance();
    i0.ɵɵconditional(ctx_r1.audienceSummary.SkippedCount > 0 ? 11 : -1);
    i0.ɵɵadvance(5);
    i0.ɵɵtextInterpolate(ctx_r1.audienceSummary.EntityName);
} }
let CommunicationsNewMessageResource = class CommunicationsNewMessageResource extends BaseResourceComponent {
    cdr;
    notificationService;
    // BaseResourceComponent already exposes a protected `destroy$` Subject.
    // Don't re-declare it here — the import is kept only for the rxjs type.
    // (See base class comment.)
    // Local lifecycle goes through super.ngOnDestroy().
    // Channel state
    loadingProviders = true;
    providers = [];
    messageTypes = [];
    selectedProviderID = null;
    selectedMessageTypeID = null;
    // Message state
    fromAddress = '';
    subject = '';
    body = '';
    // Audience state
    audienceSource = null;
    recipientField = '';
    audienceSummary = null;
    // Action IDs — looked up lazily on first use to avoid an extra RunView
    // on every page open. Cached for the session.
    resolveAudienceActionID = null;
    sendToAudienceActionID = null;
    isResolvingAudience = false;
    isSending = false;
    constructor(cdr, notificationService) {
        super();
        this.cdr = cdr;
        this.notificationService = notificationService;
    }
    async ngOnInit() {
        super.ngOnInit();
        await this.loadChannelMetadata();
        this.NotifyLoadComplete();
    }
    ngOnDestroy() {
        super.ngOnDestroy();
    }
    get filteredMessageTypes() {
        if (!this.selectedProviderID)
            return [];
        return this.messageTypes.filter((mt) => mt.CommunicationProviderID === this.selectedProviderID);
    }
    get selectedProvider() {
        return this.providers.find((p) => UUIDsEqual(p.ID, this.selectedProviderID)) ?? null;
    }
    get selectedMessageType() {
        return this.messageTypes.find((mt) => UUIDsEqual(mt.ID, this.selectedMessageTypeID)) ?? null;
    }
    get canPreview() {
        return !!this.audienceSource && this.recipientField.trim().length > 0;
    }
    get canSend() {
        return this.canPreview
            && !!this.selectedProviderID
            && !!this.selectedMessageTypeID
            && this.fromAddress.trim().length > 0;
    }
    onProviderChange() {
        this.selectedMessageTypeID = null;
    }
    onAudienceSourceChange(source) {
        this.audienceSource = source;
        this.audienceSummary = null;
    }
    /**
     * Preview the audience without sending — calls "Send To Audience" with
     * PreviewOnly=true. Surfaces the same total/will-receive/skipped tile
     * mockup 21 shows. Cheaper than `Resolve Audience` for our purposes
     * because it also evaluates the recipient-field skip rule.
     */
    async onPreviewAudience() {
        if (!this.canPreview)
            return;
        this.isResolvingAudience = true;
        this.audienceSummary = null;
        this.cdr.detectChanges();
        try {
            const actionID = await this.getSendToAudienceActionID();
            if (!actionID) {
                this.notificationService.CreateSimpleNotification("Couldn't find the 'Send To Audience' action — make sure CodeGen has run.", 'error', 5000);
                return;
            }
            const result = await this.invokeAction(actionID, {
                Source: JSON.stringify(this.audienceSource),
                RecipientField: this.recipientField.trim(),
                ProviderName: this.selectedProvider?.Name ?? 'Preview',
                ProviderMessageTypeName: this.selectedMessageType?.Name ?? 'Preview',
                From: this.fromAddress || 'preview@local',
                Subject: this.subject,
                Body: this.body,
                PreviewOnly: 'true',
            });
            const data = this.parseResultData(result);
            this.audienceSummary = {
                TotalAudienceSize: this.coerceNumber(data['TotalAudienceSize']),
                WillReceiveCount: this.coerceNumber(data['WillReceiveCount']),
                SkippedCount: this.coerceNumber(data['SkippedCount']),
                EntityName: this.audienceSource ? this.describeSource(this.audienceSource) : '',
            };
        }
        catch (e) {
            const message = e instanceof Error ? e.message : String(e);
            this.notificationService.CreateSimpleNotification(`Preview failed: ${message}`, 'error', 5000);
        }
        finally {
            this.isResolvingAudience = false;
            this.cdr.detectChanges();
        }
    }
    async onSend() {
        if (!this.canSend)
            return;
        this.isSending = true;
        this.cdr.detectChanges();
        try {
            const actionID = await this.getSendToAudienceActionID();
            if (!actionID) {
                this.notificationService.CreateSimpleNotification("Couldn't find the 'Send To Audience' action — make sure CodeGen has run.", 'error', 5000);
                return;
            }
            const result = await this.invokeAction(actionID, {
                Source: JSON.stringify(this.audienceSource),
                RecipientField: this.recipientField.trim(),
                ProviderName: this.selectedProvider.Name,
                ProviderMessageTypeName: this.selectedMessageType.Name,
                From: this.fromAddress,
                Subject: this.subject,
                Body: this.body,
                PreviewOnly: 'false',
            });
            const data = this.parseResultData(result);
            const sent = this.coerceNumber(data['WillReceiveCount']) - this.coerceNumber(data['FailedCount']);
            const failed = this.coerceNumber(data['FailedCount']);
            const skipped = this.coerceNumber(data['SkippedCount']);
            const okOverall = result.Success === true && failed === 0;
            this.notificationService.CreateSimpleNotification(okOverall
                ? `Sent ${sent} message(s)${skipped > 0 ? ` (${skipped} skipped)` : ''}`
                : `Sent with errors: ${sent} sent, ${failed} failed, ${skipped} skipped`, okOverall ? 'success' : 'warning', okOverall ? 3000 : 7000);
        }
        catch (e) {
            const message = e instanceof Error ? e.message : String(e);
            this.notificationService.CreateSimpleNotification(`Send failed: ${message}`, 'error', 5000);
        }
        finally {
            this.isSending = false;
            this.cdr.detectChanges();
        }
    }
    // -----------------------------------------------------------------
    // Internals
    // -----------------------------------------------------------------
    /**
     * One RunView pair on init: providers + their message types. Cached on
     * the component for the session — we don't go back to the DB on every
     * channel selection. Use RunViews (plural) so it's a single round trip.
     */
    async loadChannelMetadata() {
        this.loadingProviders = true;
        try {
            const rv = RunView.FromMetadataProvider(this.ProviderToUse);
            const [providersResult, messageTypesResult] = await rv.RunViews([
                {
                    EntityName: 'MJ: Communication Providers',
                    ExtraFilter: "Status='Active'",
                    OrderBy: 'Name',
                    ResultType: 'simple',
                },
                {
                    EntityName: 'MJ: Communication Provider Message Types',
                    ExtraFilter: "Status='Active'",
                    OrderBy: 'Name',
                    ResultType: 'simple',
                },
            ]);
            this.providers = (providersResult.Success ? providersResult.Results ?? [] : []);
            this.messageTypes = (messageTypesResult.Success ? messageTypesResult.Results ?? [] : []);
        }
        catch (e) {
            const message = e instanceof Error ? e.message : String(e);
            this.notificationService.CreateSimpleNotification(`Failed to load channels: ${message}`, 'error', 5000);
        }
        finally {
            this.loadingProviders = false;
            this.cdr.detectChanges();
        }
    }
    async getSendToAudienceActionID() {
        if (this.sendToAudienceActionID)
            return this.sendToAudienceActionID;
        // Read from the cached ActionEngineBase singleton rather than a
        // fresh RunView. Config() is idempotent — short-circuits if the
        // engine has already loaded — so calling it on every Preview/Send
        // is effectively free after the first invocation.
        const engine = ActionEngineBase.Instance;
        await engine.Config(false, this.ProviderToUse.CurrentUser, this.ProviderToUse);
        const match = engine.Actions?.find((a) => a.Name === 'Send To Audience');
        this.sendToAudienceActionID = match?.ID ?? null;
        return this.sendToAudienceActionID;
    }
    /**
     * Invoke an Action via the RunAction GraphQL mutation. Same pattern as
     * the Action Test Harness — kept inline here so the resource component
     * stays self-contained.
     */
    async invokeAction(actionID, params) {
        const provider = this.ProviderToUse;
        const query = `
      mutation RunAction($input: RunActionInput!) {
        RunAction(input: $input) {
          Success
          Message
          ResultCode
          ResultData
        }
      }
    `;
        const actionParams = Object.entries(params).map(([Name, Value]) => ({
            Name, Value, Type: 'string',
        }));
        const variables = { input: { ActionID: actionID, Params: actionParams, SkipActionLog: false } };
        const gqlResult = await provider.ExecuteGQL(query, variables);
        if (!gqlResult?.RunAction) {
            throw new Error('RunAction returned no result');
        }
        return gqlResult.RunAction;
    }
    parseResultData(result) {
        if (!result.ResultData)
            return {};
        try {
            const parsed = JSON.parse(result.ResultData);
            // RunAction returns either an object or an array of {Name,Value}.
            if (Array.isArray(parsed)) {
                const out = {};
                for (const item of parsed) {
                    if (item && typeof item === 'object' && 'Name' in item && 'Value' in item) {
                        out[String(item.Name)] = item.Value;
                    }
                }
                return out;
            }
            return parsed;
        }
        catch {
            return {};
        }
    }
    coerceNumber(v) {
        if (typeof v === 'number')
            return v;
        if (typeof v === 'string') {
            const n = Number(v);
            return isNaN(n) ? 0 : n;
        }
        return 0;
    }
    describeSource(s) {
        switch (s.kind) {
            case 'list': return 'List';
            case 'view': return 'User View';
            case 'adhoc': return s.entityName;
        }
    }
    async GetResourceDisplayName(_data) { return 'New Communication'; }
    async GetResourceIconClass(_data) { return 'fa-solid fa-pen-to-square'; }
    static ɵfac = function CommunicationsNewMessageResource_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || CommunicationsNewMessageResource)(i0.ɵɵdirectiveInject(i0.ChangeDetectorRef), i0.ɵɵdirectiveInject(i1.MJNotificationService)); };
    static ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: CommunicationsNewMessageResource, selectors: [["mj-communications-new-message-resource"]], standalone: false, features: [i0.ɵɵInheritDefinitionFeature], decls: 31, vars: 9, consts: [[1, "new-message-resource"], [1, "page-header"], [1, "title-block"], [1, "fa-solid", "fa-message"], [1, "header-actions"], [1, "action-btn", 3, "click", "disabled"], [1, "action-btn", "action-btn--primary", 3, "click", "disabled"], [1, "layout-grid"], [1, "panel"], [1, "panel-header"], [1, "fa-solid", "fa-envelope"], [1, "panel-body"], ["text", "Loading channels...", "size", "small"], [1, "fa-solid", "fa-bullseye"], [3, "SourceChange", "Provider", "Source"], [1, "summary-block", 3, "summary-block--has-skips"], [1, "fa-solid", "fa-spinner", "fa-spin"], [1, "fa-solid", "fa-eye"], [1, "fa-solid", "fa-paper-plane"], [1, "field-label"], [1, "mj-input", "mj-select", 3, "ngModelChange", "ngModel"], [3, "ngValue"], ["type", "text", "placeholder", "sender@example.com", 1, "mj-input", 3, "ngModelChange", "ngModel"], ["type", "text", "placeholder", "Message subject", 1, "mj-input", 3, "ngModelChange", "ngModel"], ["rows", "10", 1, "mj-input", "mj-textarea", 3, "ngModelChange", "ngModel", "placeholder"], [1, "field-label", "field-label--spaced"], ["type", "text", "placeholder", "e.g. Email", 1, "mj-input", 3, "ngModelChange", "ngModel"], [1, "field-hint"], [1, "summary-block"], [1, "summary-row"], [1, "summary-label"], [1, "summary-value"], [1, "summary-row", "summary-row--will-receive"], [1, "summary-row", "summary-row--skipped"], [1, "summary-row", "summary-row--entity"]], template: function CommunicationsNewMessageResource_Template(rf, ctx) { if (rf & 1) {
            i0.ɵɵelementStart(0, "div", 0)(1, "div", 1)(2, "div", 2);
            i0.ɵɵelement(3, "i", 3);
            i0.ɵɵelementStart(4, "h2");
            i0.ɵɵtext(5, "New Communication");
            i0.ɵɵelementEnd()();
            i0.ɵɵelementStart(6, "div", 4)(7, "button", 5);
            i0.ɵɵlistener("click", function CommunicationsNewMessageResource_Template_button_click_7_listener() { return ctx.onPreviewAudience(); });
            i0.ɵɵconditionalCreate(8, CommunicationsNewMessageResource_Conditional_8_Template, 2, 0)(9, CommunicationsNewMessageResource_Conditional_9_Template, 2, 0);
            i0.ɵɵelementEnd();
            i0.ɵɵelementStart(10, "button", 6);
            i0.ɵɵlistener("click", function CommunicationsNewMessageResource_Template_button_click_10_listener() { return ctx.onSend(); });
            i0.ɵɵconditionalCreate(11, CommunicationsNewMessageResource_Conditional_11_Template, 2, 0)(12, CommunicationsNewMessageResource_Conditional_12_Template, 2, 0);
            i0.ɵɵelementEnd()()();
            i0.ɵɵelementStart(13, "div", 7)(14, "div", 8)(15, "div", 9);
            i0.ɵɵelement(16, "i", 10);
            i0.ɵɵelementStart(17, "h3");
            i0.ɵɵtext(18, "Message");
            i0.ɵɵelementEnd()();
            i0.ɵɵelementStart(19, "div", 11);
            i0.ɵɵconditionalCreate(20, CommunicationsNewMessageResource_Conditional_20_Template, 1, 0, "mj-loading", 12)(21, CommunicationsNewMessageResource_Conditional_21_Template, 17, 8);
            i0.ɵɵelementEnd()();
            i0.ɵɵelementStart(22, "div", 8)(23, "div", 9);
            i0.ɵɵelement(24, "i", 13);
            i0.ɵɵelementStart(25, "h3");
            i0.ɵɵtext(26, "Audience");
            i0.ɵɵelementEnd()();
            i0.ɵɵelementStart(27, "div", 11)(28, "mj-audience-source-picker", 14);
            i0.ɵɵlistener("SourceChange", function CommunicationsNewMessageResource_Template_mj_audience_source_picker_SourceChange_28_listener($event) { return ctx.onAudienceSourceChange($event); });
            i0.ɵɵelementEnd();
            i0.ɵɵconditionalCreate(29, CommunicationsNewMessageResource_Conditional_29_Template, 5, 1);
            i0.ɵɵconditionalCreate(30, CommunicationsNewMessageResource_Conditional_30_Template, 17, 6, "div", 15);
            i0.ɵɵelementEnd()()()();
        } if (rf & 2) {
            i0.ɵɵadvance(7);
            i0.ɵɵproperty("disabled", !ctx.canPreview || ctx.isResolvingAudience || ctx.isSending);
            i0.ɵɵadvance();
            i0.ɵɵconditional(ctx.isResolvingAudience ? 8 : 9);
            i0.ɵɵadvance(2);
            i0.ɵɵproperty("disabled", !ctx.canSend || ctx.isResolvingAudience || ctx.isSending);
            i0.ɵɵadvance();
            i0.ɵɵconditional(ctx.isSending ? 11 : 12);
            i0.ɵɵadvance(9);
            i0.ɵɵconditional(ctx.loadingProviders ? 20 : 21);
            i0.ɵɵadvance(8);
            i0.ɵɵproperty("Provider", ctx.Provider)("Source", ctx.audienceSource);
            i0.ɵɵadvance();
            i0.ɵɵconditional(ctx.audienceSource ? 29 : -1);
            i0.ɵɵadvance();
            i0.ɵɵconditional(ctx.audienceSummary ? 30 : -1);
        } }, dependencies: [i2.NgSelectOption, i2.ɵNgSelectMultipleOption, i2.DefaultValueAccessor, i2.SelectControlValueAccessor, i2.NgControlStatus, i2.NgModel, i3.LoadingComponent, i4.AudienceSourcePickerComponent], styles: [".new-message-resource[_ngcontent-%COMP%] {\n      display: flex;\n      flex-direction: column;\n      gap: 16px;\n      padding: 16px 24px;\n      height: 100%;\n      overflow: auto;\n    }\n    .page-header[_ngcontent-%COMP%] {\n      display: flex;\n      align-items: center;\n      justify-content: space-between;\n      gap: 16px;\n    }\n    .title-block[_ngcontent-%COMP%] { display: flex; align-items: center; gap: 12px; }\n    .title-block[_ngcontent-%COMP%]   i[_ngcontent-%COMP%] { font-size: 20px; color: var(--mj-brand-primary); }\n    .title-block[_ngcontent-%COMP%]   h2[_ngcontent-%COMP%] { margin: 0; font-size: 18px; font-weight: 600; color: var(--mj-text-primary); }\n    .header-actions[_ngcontent-%COMP%] { display: flex; gap: 8px; }\n    .action-btn[_ngcontent-%COMP%] {\n      padding: 8px 14px;\n      border-radius: 6px;\n      border: 1px solid var(--mj-border-default);\n      background: var(--mj-bg-surface);\n      color: var(--mj-text-primary);\n      font-size: 13px;\n      cursor: pointer;\n      display: inline-flex;\n      align-items: center;\n      gap: 6px;\n    }\n    .action-btn[_ngcontent-%COMP%]:hover:not(:disabled) {\n      background: var(--mj-bg-surface-hover);\n    }\n    .action-btn[_ngcontent-%COMP%]:disabled { opacity: 0.55; cursor: not-allowed; }\n    .action-btn--primary[_ngcontent-%COMP%] {\n      background: var(--mj-brand-primary);\n      border-color: var(--mj-brand-primary);\n      color: var(--mj-text-inverse, white);\n    }\n    .action-btn--primary[_ngcontent-%COMP%]:hover:not(:disabled) {\n      background: var(--mj-brand-primary-hover);\n    }\n\n    .layout-grid[_ngcontent-%COMP%] {\n      display: grid;\n      grid-template-columns: 1fr 380px;\n      gap: 16px;\n      align-items: start;\n    }\n    @media (max-width: 1024px) {\n      .layout-grid[_ngcontent-%COMP%] { grid-template-columns: 1fr; }\n    }\n\n    .panel[_ngcontent-%COMP%] {\n      background: var(--mj-bg-surface);\n      border: 1px solid var(--mj-border-default);\n      border-radius: 8px;\n      overflow: hidden;\n    }\n    .panel-header[_ngcontent-%COMP%] {\n      display: flex;\n      align-items: center;\n      gap: 8px;\n      padding: 12px 16px;\n      border-bottom: 1px solid var(--mj-border-default);\n      background: var(--mj-bg-surface-card);\n    }\n    .panel-header[_ngcontent-%COMP%]   i[_ngcontent-%COMP%] { color: var(--mj-text-secondary); }\n    .panel-header[_ngcontent-%COMP%]   h3[_ngcontent-%COMP%] {\n      margin: 0;\n      font-size: 14px;\n      font-weight: 600;\n      color: var(--mj-text-primary);\n    }\n    .panel-body[_ngcontent-%COMP%] { padding: 16px; }\n\n    .field-label[_ngcontent-%COMP%] {\n      display: block;\n      font-size: 12px;\n      font-weight: 500;\n      color: var(--mj-text-secondary);\n      margin: 12px 0 6px;\n      text-transform: uppercase;\n      letter-spacing: 0.4px;\n    }\n    .field-label--spaced[_ngcontent-%COMP%] { margin-top: 20px; }\n    .field-hint[_ngcontent-%COMP%] {\n      font-size: 11.5px;\n      color: var(--mj-text-muted);\n      margin: 6px 0 0;\n    }\n\n    .summary-block[_ngcontent-%COMP%] {\n      margin-top: 20px;\n      padding: 12px 14px;\n      background: var(--mj-bg-surface-card);\n      border: 1px solid var(--mj-border-default);\n      border-radius: 6px;\n    }\n    .summary-block--has-skips[_ngcontent-%COMP%] {\n      border-color: var(--mj-status-warning);\n      background: color-mix(in srgb, var(--mj-status-warning) 6%, var(--mj-bg-surface-card));\n    }\n    .summary-row[_ngcontent-%COMP%] {\n      display: flex;\n      justify-content: space-between;\n      gap: 16px;\n      font-size: 13px;\n      padding: 4px 0;\n    }\n    .summary-row[_ngcontent-%COMP%]    + .summary-row[_ngcontent-%COMP%] { border-top: 1px solid var(--mj-border-subtle); }\n    .summary-label[_ngcontent-%COMP%] { color: var(--mj-text-secondary); }\n    .summary-value[_ngcontent-%COMP%] { font-weight: 600; color: var(--mj-text-primary); }\n    .summary-row--will-receive[_ngcontent-%COMP%]   .summary-value[_ngcontent-%COMP%] { color: var(--mj-status-success); }\n    .summary-row--skipped[_ngcontent-%COMP%]   .summary-value[_ngcontent-%COMP%] { color: var(--mj-status-warning); }\n    .summary-row--entity[_ngcontent-%COMP%]   .summary-label[_ngcontent-%COMP%], \n   .summary-row--entity[_ngcontent-%COMP%]   .summary-value[_ngcontent-%COMP%] {\n      font-size: 11.5px;\n      color: var(--mj-text-muted);\n      font-weight: 500;\n    }"] });
};
CommunicationsNewMessageResource = __decorate([
    RegisterClass(BaseResourceComponent, 'CommunicationsNewMessageResource')
], CommunicationsNewMessageResource);
export { CommunicationsNewMessageResource };
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(CommunicationsNewMessageResource, [{
        type: Component,
        args: [{ standalone: false, selector: 'mj-communications-new-message-resource', template: `
    <div class="new-message-resource">
      <div class="page-header">
        <div class="title-block">
          <i class="fa-solid fa-message"></i>
          <h2>New Communication</h2>
        </div>
        <div class="header-actions">
          <button
            class="action-btn"
            (click)="onPreviewAudience()"
            [disabled]="!canPreview || isResolvingAudience || isSending">
            @if (isResolvingAudience) {
              <i class="fa-solid fa-spinner fa-spin"></i> Previewing…
            } @else {
              <i class="fa-solid fa-eye"></i> Preview Audience
            }
          </button>
          <button
            class="action-btn action-btn--primary"
            (click)="onSend()"
            [disabled]="!canSend || isResolvingAudience || isSending">
            @if (isSending) {
              <i class="fa-solid fa-spinner fa-spin"></i> Sending…
            } @else {
              <i class="fa-solid fa-paper-plane"></i> Send
            }
          </button>
        </div>
      </div>

      <div class="layout-grid">
        <!-- Message panel -->
        <div class="panel">
          <div class="panel-header">
            <i class="fa-solid fa-envelope"></i>
            <h3>Message</h3>
          </div>
          <div class="panel-body">
            @if (loadingProviders) {
              <mj-loading text="Loading channels..." size="small"></mj-loading>
            } @else {
              <label class="field-label">Channel</label>
              <select
                class="mj-input mj-select"
                [(ngModel)]="selectedProviderID"
                (ngModelChange)="onProviderChange()">
                <option [ngValue]="null">Select a channel…</option>
                @for (p of providers; track p.ID) {
                  <option [ngValue]="p.ID">{{ p.Name }}</option>
                }
              </select>

              @if (filteredMessageTypes.length > 0) {
                <label class="field-label">Message type</label>
                <select class="mj-input mj-select" [(ngModel)]="selectedMessageTypeID">
                  <option [ngValue]="null">Select a message type…</option>
                  @for (mt of filteredMessageTypes; track mt.ID) {
                    <option [ngValue]="mt.ID">{{ mt.Name }}</option>
                  }
                </select>
              }

              <label class="field-label">From</label>
              <input
                class="mj-input"
                type="text"
                [(ngModel)]="fromAddress"
                placeholder="sender@example.com" />

              <label class="field-label">Subject</label>
              <input
                class="mj-input"
                type="text"
                [(ngModel)]="subject"
                placeholder="Message subject" />

              <label class="field-label">Body</label>
              <textarea
                class="mj-input mj-textarea"
                [(ngModel)]="body"
                rows="10"
                placeholder="Hi {{ '{{FirstName}}' }},..."></textarea>
            }
          </div>
        </div>

        <!-- Audience panel -->
        <div class="panel">
          <div class="panel-header">
            <i class="fa-solid fa-bullseye"></i>
            <h3>Audience</h3>
          </div>
          <div class="panel-body">
            <mj-audience-source-picker
              [Provider]="Provider"
              [Source]="audienceSource"
              (SourceChange)="onAudienceSourceChange($event)">
            </mj-audience-source-picker>

            @if (audienceSource) {
              <label class="field-label field-label--spaced">Recipient field</label>
              <input
                class="mj-input"
                type="text"
                [(ngModel)]="recipientField"
                placeholder="e.g. Email" />
              <p class="field-hint">
                Field on the audience entity that holds the recipient address.
                Records with no value will be skipped.
              </p>
            }

            @if (audienceSummary) {
              <div class="summary-block" [class.summary-block--has-skips]="audienceSummary.SkippedCount > 0">
                <div class="summary-row">
                  <span class="summary-label">Total audience</span>
                  <span class="summary-value">{{ audienceSummary.TotalAudienceSize }}</span>
                </div>
                <div class="summary-row summary-row--will-receive">
                  <span class="summary-label">Will receive</span>
                  <span class="summary-value">{{ audienceSummary.WillReceiveCount }}</span>
                </div>
                @if (audienceSummary.SkippedCount > 0) {
                  <div class="summary-row summary-row--skipped">
                    <span class="summary-label">Skipped (missing {{ recipientField || 'recipient' }})</span>
                    <span class="summary-value">{{ audienceSummary.SkippedCount }}</span>
                  </div>
                }
                <div class="summary-row summary-row--entity">
                  <span class="summary-label">Entity</span>
                  <span class="summary-value">{{ audienceSummary.EntityName }}</span>
                </div>
              </div>
            }
          </div>
        </div>
      </div>
    </div>
  `, styles: ["\n    .new-message-resource {\n      display: flex;\n      flex-direction: column;\n      gap: 16px;\n      padding: 16px 24px;\n      height: 100%;\n      overflow: auto;\n    }\n    .page-header {\n      display: flex;\n      align-items: center;\n      justify-content: space-between;\n      gap: 16px;\n    }\n    .title-block { display: flex; align-items: center; gap: 12px; }\n    .title-block i { font-size: 20px; color: var(--mj-brand-primary); }\n    .title-block h2 { margin: 0; font-size: 18px; font-weight: 600; color: var(--mj-text-primary); }\n    .header-actions { display: flex; gap: 8px; }\n    .action-btn {\n      padding: 8px 14px;\n      border-radius: 6px;\n      border: 1px solid var(--mj-border-default);\n      background: var(--mj-bg-surface);\n      color: var(--mj-text-primary);\n      font-size: 13px;\n      cursor: pointer;\n      display: inline-flex;\n      align-items: center;\n      gap: 6px;\n    }\n    .action-btn:hover:not(:disabled) {\n      background: var(--mj-bg-surface-hover);\n    }\n    .action-btn:disabled { opacity: 0.55; cursor: not-allowed; }\n    .action-btn--primary {\n      background: var(--mj-brand-primary);\n      border-color: var(--mj-brand-primary);\n      color: var(--mj-text-inverse, white);\n    }\n    .action-btn--primary:hover:not(:disabled) {\n      background: var(--mj-brand-primary-hover);\n    }\n\n    .layout-grid {\n      display: grid;\n      grid-template-columns: 1fr 380px;\n      gap: 16px;\n      align-items: start;\n    }\n    @media (max-width: 1024px) {\n      .layout-grid { grid-template-columns: 1fr; }\n    }\n\n    .panel {\n      background: var(--mj-bg-surface);\n      border: 1px solid var(--mj-border-default);\n      border-radius: 8px;\n      overflow: hidden;\n    }\n    .panel-header {\n      display: flex;\n      align-items: center;\n      gap: 8px;\n      padding: 12px 16px;\n      border-bottom: 1px solid var(--mj-border-default);\n      background: var(--mj-bg-surface-card);\n    }\n    .panel-header i { color: var(--mj-text-secondary); }\n    .panel-header h3 {\n      margin: 0;\n      font-size: 14px;\n      font-weight: 600;\n      color: var(--mj-text-primary);\n    }\n    .panel-body { padding: 16px; }\n\n    .field-label {\n      display: block;\n      font-size: 12px;\n      font-weight: 500;\n      color: var(--mj-text-secondary);\n      margin: 12px 0 6px;\n      text-transform: uppercase;\n      letter-spacing: 0.4px;\n    }\n    .field-label--spaced { margin-top: 20px; }\n    .field-hint {\n      font-size: 11.5px;\n      color: var(--mj-text-muted);\n      margin: 6px 0 0;\n    }\n\n    .summary-block {\n      margin-top: 20px;\n      padding: 12px 14px;\n      background: var(--mj-bg-surface-card);\n      border: 1px solid var(--mj-border-default);\n      border-radius: 6px;\n    }\n    .summary-block--has-skips {\n      border-color: var(--mj-status-warning);\n      background: color-mix(in srgb, var(--mj-status-warning) 6%, var(--mj-bg-surface-card));\n    }\n    .summary-row {\n      display: flex;\n      justify-content: space-between;\n      gap: 16px;\n      font-size: 13px;\n      padding: 4px 0;\n    }\n    .summary-row + .summary-row { border-top: 1px solid var(--mj-border-subtle); }\n    .summary-label { color: var(--mj-text-secondary); }\n    .summary-value { font-weight: 600; color: var(--mj-text-primary); }\n    .summary-row--will-receive .summary-value { color: var(--mj-status-success); }\n    .summary-row--skipped .summary-value { color: var(--mj-status-warning); }\n    .summary-row--entity .summary-label,\n    .summary-row--entity .summary-value {\n      font-size: 11.5px;\n      color: var(--mj-text-muted);\n      font-weight: 500;\n    }\n  "] }]
    }], () => [{ type: i0.ChangeDetectorRef }, { type: i1.MJNotificationService }], null); })();
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(CommunicationsNewMessageResource, { className: "CommunicationsNewMessageResource", filePath: "src/Communication/communication-new-message-resource.component.ts", lineNumber: 311 }); })();
/** Tree-shaking prevention */
export function LoadCommunicationsNewMessageResource() { }
//# sourceMappingURL=communication-new-message-resource.component.js.map