import { MXInputBaseValueComponent, MXLookComponent, AXComponent, AXFocusableComponent, AXValuableComponent } from '@acorex/cdk/common';
import { AXPlatform } from '@acorex/core/platform';
import { AXHtmlUtil } from '@acorex/core/utils';
import * as i0 from '@angular/core';
import { viewChild, inject, input, afterNextRender, forwardRef, HostBinding, ChangeDetectionStrategy, ViewEncapsulation, Component, NgModule } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { classes } from 'polytype';

class AXEditorComponent extends classes((MXInputBaseValueComponent), MXLookComponent) {
    constructor() {
        super(...arguments);
        this.toolLoaders = {
            header: () => import('@editorjs/header'),
            list: () => import('@editorjs/list'),
            raw: () => import('@editorjs/raw'),
            quote: () => import('@editorjs/quote'),
            codeBox: () => import('@bomdi/codebox'),
            underline: () => import('@editorjs/underline'),
            color: () => import('editorjs-text-color-plugin'),
            image: () => import('@editorjs/image'),
            // linkTool: () => import('@editorjs/link'),
            // table: () => import('@editorjs/table'),
            // attaches: () => import('@editorjs/attaches'),
            // alignmentTuneTool: () => import('editorjs-text-alignment-blocktune'),
            // hyperlink: () => import('editorjs-hyperlink'),
            // delimiter: () => import('@editorjs/delimiter'),
            // inlineCode: () => import('@editorjs/inline-code'),
            // embed: () => import('@editorjs/embed'),
            // warning: () => import('@editorjs/warning'),
            // checklist: () => import('@editorjs/checklist'),
            // marker: () => import('@editorjs/marker'),
            // dragDrop: () => import('editorjs-drag-drop'),
            // undo: () => import('editorjs-undo'),
            // nestedList: () => import('@editorjs/nested-list'),
            // tooltip: () => import('editorjs-tooltip'),
            // paragraphWithAlignment: () => import('editorjs-paragraph-with-alignment'),
        };
        this.editorHolder = viewChild('r', ...(ngDevMode ? [{ debugName: "editorHolder" }] : []));
        this.platform = inject(AXPlatform);
        this.modules = input([], ...(ngDevMode ? [{ debugName: "modules" }] : []));
        this.imageConfig = input(...(ngDevMode ? [undefined, { debugName: "imageConfig" }] : []));
        this.colorConfig = {
            defaultColor: '#FF1300',
            type: 'text',
            customPicker: true,
            colorCollections: [
                '#EC7878',
                '#9C27B0',
                '#673AB7',
                '#3F51B5',
                '#0070FF',
                '#03A9F4',
                '#00BCD4',
                '#4CAF50',
                '#8BC34A',
                '#CDDC39',
                '#FFF',
            ],
        };
        this.markerConfig = {
            defaultColor: '#FFBF00',
            type: 'marker',
        };
        this.#init = afterNextRender(async () => {
            const tools = await this.loadEditorJsTools(this.modules());
            if (tools['color']) {
                tools['marker'] = { ...tools['color'] };
                tools['color'].config = this.colorConfig;
                tools['marker'].config = this.markerConfig;
            }
            if (tools['image'] && this.imageConfig()) {
                tools['image'].config = this.imageConfig();
            }
            if (tools['codeBox']) {
                tools['codeBox'].config = { useDefaultTheme: this.platform.themeMode() };
            }
            const EditorJS = (await import('@editorjs/editorjs')).default;
            this.editorClass = new EditorJS({
                holder: this.editorHolder().nativeElement,
                tools,
                onChange: async (e) => {
                    const content = await e.saver.save();
                    if (content.blocks.length) {
                        this.commitValue(content, true);
                    }
                    else {
                        this.commitValue(null, true);
                    }
                },
                data: this.value,
                readOnly: this.readonly || this.disabled,
            });
        });
    }
    async loadEditorJsTools(selectedTools) {
        const results = await Promise.all(selectedTools.map(async (name) => {
            try {
                const mod = await this.toolLoaders[name]();
                return [name, mod.default ?? mod];
            }
            catch (error) {
                console.error(`❌ Failed to load ${name}:`, error);
                return null;
            }
        }));
        return Object.fromEntries(results.map(([key, value]) => [key, { class: value }]));
    }
    #init;
    get __hostClass() {
        const style = [];
        if (this.disabled)
            style.push('ax-disable');
        if (AXHtmlUtil.isRtl())
            style.push('ax-rtl');
        return style;
    }
    get __hostName() {
        return this.name;
    }
    async save() {
        const resolve = await this.editorClass.save();
        return resolve;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: AXEditorComponent, deps: null, target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.2.0", version: "20.3.9", type: AXEditorComponent, isStandalone: true, selector: "ax-editor", inputs: { look: { classPropertyName: "look", publicName: "look", isSignal: false, isRequired: false, transformFunction: null }, readonly: { classPropertyName: "readonly", publicName: "readonly", isSignal: false, isRequired: false, transformFunction: null }, disabled: { classPropertyName: "disabled", publicName: "disabled", isSignal: false, isRequired: false, transformFunction: null }, modules: { classPropertyName: "modules", publicName: "modules", isSignal: true, isRequired: false, transformFunction: null }, imageConfig: { classPropertyName: "imageConfig", publicName: "imageConfig", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { onValueChanged: "onValueChanged" }, host: { properties: { "class": "this.__hostClass", "attr.name": "this.__hostName" } }, providers: [
            { provide: AXComponent, useExisting: AXEditorComponent },
            { provide: AXFocusableComponent, useExisting: AXEditorComponent },
            { provide: AXValuableComponent, useExisting: AXEditorComponent },
            {
                provide: NG_VALUE_ACCESSOR,
                useExisting: forwardRef(() => AXEditorComponent),
                multi: true,
            },
        ], viewQueries: [{ propertyName: "editorHolder", first: true, predicate: ["r"], descendants: true, isSignal: true }], usesInheritance: true, ngImport: i0, template: `
    <div class="ax-editor-container ax-{{ look }}">
      <div class="ax-editor-holder" #r></div>
    </div>
    <ng-content select="ax-validation-rule"> </ng-content>
    <div class="ax-error-container"></div>
  `, isInline: true, styles: ["ax-editor>.ax-editor-container{display:block;height:fit-content!important}ax-editor.ax-rtl .ce-toolbar__actions{left:100%;right:auto}ax-editor.ax-disable{opacity:.5;cursor:not-allowed}ax-editor .ce-inline-toolbar{background-color:rgba(var(--ax-sys-color-surface))}ax-editor .colorPlugin svg{fill:rgba(var(--ax-sys-color-on-surface))!important}ax-editor .ce-inline-toolbar{border:1px solid rgba(var(--ax-sys-color-border-surface))}ax-editor .ce-toolbar__plus{color:unset}ax-editor .ce-popover{background:rgba(var(--ax-sys-color-darker-surface))}ax-editor .ce-popover-item{color:unset}ax-editor .ce-popover--opened{border:1px solid rgba(var(--ax-sys-color-border-surface))}ax-editor .ce-popover-item__icon{background:unset}ax-editor .cdx-search-field{background:unset}ax-editor .ce-popover-item:hover:not(.ce-popover-item--no-hover){background-color:rgba(var(--ax-sys-color-lightest-surface))}ax-editor .ce-toolbar__plus:hover{background-color:rgba(var(--ax-sys-color-darkest-surface))}\n"], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: AXEditorComponent, decorators: [{
            type: Component,
            args: [{ selector: 'ax-editor', template: `
    <div class="ax-editor-container ax-{{ look }}">
      <div class="ax-editor-holder" #r></div>
    </div>
    <ng-content select="ax-validation-rule"> </ng-content>
    <div class="ax-error-container"></div>
  `, providers: [
                        { provide: AXComponent, useExisting: AXEditorComponent },
                        { provide: AXFocusableComponent, useExisting: AXEditorComponent },
                        { provide: AXValuableComponent, useExisting: AXEditorComponent },
                        {
                            provide: NG_VALUE_ACCESSOR,
                            useExisting: forwardRef(() => AXEditorComponent),
                            multi: true,
                        },
                    ], inputs: ['look', 'readonly', 'disabled'], outputs: ['onValueChanged'], encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, styles: ["ax-editor>.ax-editor-container{display:block;height:fit-content!important}ax-editor.ax-rtl .ce-toolbar__actions{left:100%;right:auto}ax-editor.ax-disable{opacity:.5;cursor:not-allowed}ax-editor .ce-inline-toolbar{background-color:rgba(var(--ax-sys-color-surface))}ax-editor .colorPlugin svg{fill:rgba(var(--ax-sys-color-on-surface))!important}ax-editor .ce-inline-toolbar{border:1px solid rgba(var(--ax-sys-color-border-surface))}ax-editor .ce-toolbar__plus{color:unset}ax-editor .ce-popover{background:rgba(var(--ax-sys-color-darker-surface))}ax-editor .ce-popover-item{color:unset}ax-editor .ce-popover--opened{border:1px solid rgba(var(--ax-sys-color-border-surface))}ax-editor .ce-popover-item__icon{background:unset}ax-editor .cdx-search-field{background:unset}ax-editor .ce-popover-item:hover:not(.ce-popover-item--no-hover){background-color:rgba(var(--ax-sys-color-lightest-surface))}ax-editor .ce-toolbar__plus:hover{background-color:rgba(var(--ax-sys-color-darkest-surface))}\n"] }]
        }], propDecorators: { editorHolder: [{ type: i0.ViewChild, args: ['r', { isSignal: true }] }], modules: [{ type: i0.Input, args: [{ isSignal: true, alias: "modules", required: false }] }], imageConfig: [{ type: i0.Input, args: [{ isSignal: true, alias: "imageConfig", required: false }] }], __hostClass: [{
                type: HostBinding,
                args: ['class']
            }], __hostName: [{
                type: HostBinding,
                args: ['attr.name']
            }] } });

const COMPONENT = [AXEditorComponent];
const MODULES = [];
class EditorModule {
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: EditorModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
    static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "20.3.9", ngImport: i0, type: EditorModule, imports: [AXEditorComponent], exports: [AXEditorComponent] }); }
    static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: EditorModule, imports: [MODULES] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: EditorModule, decorators: [{
            type: NgModule,
            args: [{
                    imports: [...MODULES, ...COMPONENT],
                    exports: [...COMPONENT],
                    providers: [],
                }]
        }] });

/**
 * Generated bundle index. Do not edit.
 */

export { AXEditorComponent, EditorModule };
//# sourceMappingURL=acorex-components-editor.mjs.map
