import * as i0 from '@angular/core';
import { InjectionToken, inject, DestroyRef, ChangeDetectorRef, input, booleanAttribute, computed, model, output, signal, effect, ChangeDetectionStrategy, Component } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { NgForm, FormGroup } from '@angular/forms';
import * as i2 from '@angular/material/form-field';
import { MatFormFieldModule } from '@angular/material/form-field';
import * as i3 from '@angular/material/icon';
import { MatIconModule } from '@angular/material/icon';
import * as i4 from '@angular/material/tooltip';
import { MatTooltipModule } from '@angular/material/tooltip';
import * as i1 from '@ckeditor/ckeditor5-angular';
import { CKEditorModule } from '@ckeditor/ckeditor5-angular';
import { Plugin, FileRepository, Image, ImageResize, ImageUpload, ImageStyle, ImageToolbar, ClassicEditor, Essentials, FontColor, FontSize, Paragraph, Bold, Italic, Underline, List, Undo, Widget, Alignment } from 'ckeditor5';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import * as uuid from 'uuid';
import { SdNotifyService } from '@sdcorejs/angular/services';
import { I18nService } from '@sdcorejs/angular/i18n';
import { sdIsEmpty } from '@sdcorejs/angular/utilities/data-state';
import { SdFormControl, HandleSdCustomValidator } from '@sdcorejs/angular/forms/models';
import { SdCKEditorStyles } from '@sdcorejs/angular/components/ckeditor-styles';
import { SdLabel } from '@sdcorejs/angular/forms/label';

const SD_EDITOR_CONFIGURATION = new InjectionToken('sd.editor.configuration');

// Dựa vào file để detect định dạng thay vì chỉ check tên
// Tránh user gửi file không đúng, ví dụ file docx nhưng đổi tên thành ảnh docx.jpg
const detectFormatFromBytes = async (file) => {
    const buffer = await file.slice(0, 12).arrayBuffer();
    const b = new Uint8Array(buffer);
    if (b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff)
        return 'jpg';
    if (b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47)
        return 'png';
    if (b[0] === 0x52 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x46 && b[8] === 0x57)
        return 'webp';
    if (b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x38)
        return 'gif';
    if (b[4] === 0x66 && b[5] === 0x74 && b[6] === 0x79 && b[7] === 0x70) {
        const brand = String.fromCharCode(b[8], b[9], b[10], b[11]);
        if (brand === 'avif')
            return 'avif';
        if (brand.startsWith('hei'))
            return 'heic';
    }
    return '';
};
const getImageInfo = async (file) => {
    const sizeMB = file.size / (1024 * 1024);
    const loadDimensions = new Promise(resolve => {
        const url = URL.createObjectURL(file);
        const img = new window.Image();
        img.onload = () => {
            URL.revokeObjectURL(url);
            resolve({ width: img.naturalWidth, height: img.naturalHeight });
        };
        img.onerror = () => {
            URL.revokeObjectURL(url);
            resolve({ width: 0, height: 0 });
        };
        img.src = url;
    });
    const [format, { width, height }] = await Promise.all([detectFormatFromBytes(file), loadDimensions]);
    return { width, height, sizeMB, format };
};
// Helper: gọi i18n.t khi có service; nếu thiếu thì trả empty (Angular wrapper luôn truyền i18n)
const tr = (i18n, key, params) => i18n?.t(key, params) ?? '';
const validateImageFile = async (file, validation, onWarning, i18n) => {
    const { width, height, sizeMB, format } = await getImageInfo(file);
    if (validation.allowedFormats !== undefined) {
        const normalizedFormats = validation.allowedFormats.map((f) => {
            const fmt = f.replace(/^\./, '').toLowerCase();
            return fmt === 'jpeg' ? 'jpg' : fmt;
        });
        if (!normalizedFormats.includes(format)) {
            const allowed = normalizedFormats.join(', ');
            onWarning?.(tr(i18n, 'core.component.editor.image.invalid-format', { format, allowed }));
            return false;
        }
    }
    if (validation.maxSizeMB !== undefined && sizeMB > validation.maxSizeMB) {
        const sizeMBFixed = sizeMB.toFixed(2);
        onWarning?.(tr(i18n, 'core.component.editor.image.size-exceeded', { sizeMB: sizeMBFixed, maxSizeMB: validation.maxSizeMB }));
        return false;
    }
    if (validation.minWidth !== undefined && width < validation.minWidth) {
        onWarning?.(tr(i18n, 'core.component.editor.image.min-width', { width, min: validation.minWidth }));
        return false;
    }
    if (validation.minHeight !== undefined && height < validation.minHeight) {
        onWarning?.(tr(i18n, 'core.component.editor.image.min-height', { height, min: validation.minHeight }));
        return false;
    }
    if (validation.maxWidth !== undefined && width > validation.maxWidth) {
        onWarning?.(tr(i18n, 'core.component.editor.image.max-width', { width, max: validation.maxWidth }));
        return false;
    }
    if (validation.maxHeight !== undefined && height > validation.maxHeight) {
        onWarning?.(tr(i18n, 'core.component.editor.image.max-height', { height, max: validation.maxHeight }));
        return false;
    }
    return true;
};
const validateAndGetFile = async (loader, validation, onWarning, i18n) => {
    const file = (await loader.file);
    if (!file) {
        throw new Error('No file found');
    }
    if (validation) {
        const valid = await validateImageFile(file, validation, onWarning, i18n);
        if (!valid) {
            throw new Error('Image validation failed');
        }
    }
    return file;
};

const getBatchConfig = (option) => {
    const imageConfig = option?.imageConfig;
    return {
        batchSize: Math.max(1, imageConfig?.batchSize ?? 2),
        maxConcurrent: Math.max(1, imageConfig?.maxConcurrentUploads ?? 2),
    };
};
const getActiveBlobUrls = (editor) => {
    const urls = new Set();
    const root = editor.model.document.getRoot();
    if (!root)
        return urls;
    for (const item of editor.model.createRangeIn(root).getItems()) {
        if (item.is('element', 'imageBlock') || item.is('element', 'imageInline')) {
            const src = item.getAttribute('src');
            if (src?.startsWith('blob:'))
                urls.add(src);
        }
    }
    return urls;
};
const filterActivePendingFiles = (pendingFiles, activeBlobUrls) => {
    const toUpload = [];
    for (const [blobUrl, file] of pendingFiles) {
        if (activeBlobUrls.has(blobUrl)) {
            toUpload.push([blobUrl, file]);
        }
        else {
            URL.revokeObjectURL(blobUrl);
            pendingFiles.delete(blobUrl);
        }
    }
    return toUpload;
};
const runBatchUploads = async (toUpload, uploadFn, batchSize, maxConcurrent) => {
    const batches = [];
    for (let i = 0; i < toUpload.length; i += batchSize) {
        batches.push(toUpload.slice(i, i + batchSize));
    }
    const replacements = new Map();
    const failedBatches = [];
    let head = 0;
    const runWorker = async () => {
        while (head < batches.length) {
            const batch = batches[head++];
            try {
                const details = await uploadFn(batch.map(([, file]) => file));
                if (details.length !== batch.length) {
                    throw new Error(`API returned ${details.length} results for ${batch.length} files`);
                }
                batch.forEach(([blobUrl], idx) => {
                    replacements.set(blobUrl, details[idx]);
                    URL.revokeObjectURL(blobUrl);
                });
            }
            catch {
                failedBatches.push(batch);
            }
        }
    };
    await Promise.all(Array.from({ length: Math.min(maxConcurrent, batches.length) }, runWorker));
    return { replacements, failedBatches };
};
const applyReplacementsToEditor = (editor, replacements) => {
    if (replacements.size === 0)
        return;
    editor.model.change(writer => {
        const root = editor.model.document.getRoot();
        for (const item of editor.model.createRangeIn(root).getItems()) {
            if (!item.is('element', 'imageBlock') && !item.is('element', 'imageInline'))
                continue;
            const detail = replacements.get(item.getAttribute('src'));
            if (detail)
                writer.setAttribute('src', detail.cdn, item);
        }
    });
};

const parseStyle = (style) => {
    const map = new Map();
    for (const decl of style.split(';')) {
        const colon = decl.indexOf(':');
        if (colon === -1)
            continue;
        const key = decl.slice(0, colon).trim();
        const value = decl.slice(colon + 1).trim();
        if (key && value)
            map.set(key, value);
    }
    return map;
};
const serializeStyle = (map) => [...map.entries()].map(([k, v]) => `${k}:${v}`).join(';');
const countTextLength = (content) => {
    if (!content)
        return 0;
    const doc = new DOMParser().parseFromString(content, 'text/html');
    doc.querySelectorAll('img, figure').forEach(el => el.remove());
    return doc.body.textContent?.length ?? 0;
};
const imageInlineStylesToClasses = (html) => {
    if (!html)
        return html;
    const doc = new DOMParser().parseFromString(html, 'text/html');
    doc.querySelectorAll('figure.image').forEach(figure => {
        const styleMap = parseStyle(figure.getAttribute('style') || '');
        const floatVal = styleMap.get('float') || '';
        const marginVal = styleMap.get('margin') || '';
        const widthVal = styleMap.get('width') || '';
        const hasNumericWidth = /\d/.test(widthVal) && widthVal !== 'fit-content';
        styleMap.delete('display');
        styleMap.delete('max-width');
        styleMap.delete('float');
        styleMap.delete('margin');
        if (widthVal === 'fit-content')
            styleMap.delete('width');
        figure.classList.remove('image-style-align-left', 'image-style-align-right', 'image-style-block-align-left', 'image-style-block-align-right');
        if (floatVal === 'left') {
            figure.classList.add('image-style-align-left');
        }
        else if (floatVal === 'right') {
            figure.classList.add('image-style-align-right');
        }
        else if (marginVal === '0 auto 0 0') {
            figure.classList.add(hasNumericWidth ? 'image-style-align-left' : 'image-style-block-align-left');
        }
        else if (marginVal === '0 0 0 auto') {
            figure.classList.add(hasNumericWidth ? 'image-style-align-right' : 'image-style-block-align-right');
        }
        figure.setAttribute('style', serializeStyle(styleMap));
        if (hasNumericWidth) {
            const img = figure.querySelector('img');
            if (img) {
                const imgStyle = parseStyle(img.getAttribute('style') || '');
                if (imgStyle.get('width') === '100%')
                    imgStyle.delete('width');
                if (imgStyle.get('height') === 'auto')
                    imgStyle.delete('height');
                const serialized = serializeStyle(imgStyle);
                if (serialized)
                    img.setAttribute('style', serialized);
                else
                    img.removeAttribute('style');
            }
        }
    });
    return doc.body.innerHTML;
};
const imageClassesToInlineStyles = (html) => {
    if (!html)
        return html;
    const doc = new DOMParser().parseFromString(html, 'text/html');
    doc.querySelectorAll('figure.image').forEach(figure => {
        const styleMap = parseStyle(figure.getAttribute('style') || '');
        const classList = figure.classList;
        const hasResizeWidth = styleMap.has('width') && /\d/.test(styleMap.get('width'));
        styleMap.set('display', 'block');
        styleMap.set('max-width', '100%');
        if (classList.contains('image-style-align-left')) {
            if (hasResizeWidth && styleMap.get('width') === '100%') {
                styleMap.delete('float');
                styleMap.set('margin', '0 auto 0 0');
            }
            else {
                styleMap.set('float', 'left');
                styleMap.set('margin', '0 1em 0 0');
            }
        }
        else if (classList.contains('image-style-align-right')) {
            if (hasResizeWidth && styleMap.get('width') === '100%') {
                styleMap.delete('float');
                styleMap.set('margin', '0 0 0 auto');
            }
            else {
                styleMap.set('float', 'right');
                styleMap.set('margin', '0 0 0 1em');
            }
        }
        else if (classList.contains('image-style-block-align-left')) {
            styleMap.delete('float');
            styleMap.set('margin', '0 auto 0 0');
        }
        else if (classList.contains('image-style-block-align-right')) {
            styleMap.delete('float');
            styleMap.set('margin', '0 0 0 auto');
        }
        else {
            styleMap.delete('float');
            styleMap.set('margin', '0 auto');
        }
        if (!hasResizeWidth)
            styleMap.set('width', 'fit-content');
        figure.setAttribute('style', serializeStyle(styleMap));
        if (hasResizeWidth) {
            const img = figure.querySelector('img');
            if (img) {
                const imgStyle = parseStyle(img.getAttribute('style') || '');
                imgStyle.set('width', '100%');
                imgStyle.set('height', 'auto');
                img.setAttribute('style', serializeStyle(imgStyle));
            }
        }
    });
    return doc.body.innerHTML;
};

class UploadQueue {
    #queue = [];
    #running = 0;
    maxConcurrent;
    constructor(maxConcurrent) {
        this.maxConcurrent = maxConcurrent;
    }
    async run(task) {
        if (this.#running >= this.maxConcurrent) {
            await new Promise(resolve => {
                this.#queue.push(resolve);
            });
        }
        this.#running++;
        try {
            return await task();
        }
        finally {
            this.#running--;
            this.#queue.shift()?.();
        }
    }
}
class BatchUploadScheduler {
    #pending = [];
    #timer = null;
    #batchSize;
    #uploadFn;
    #queue;
    constructor(batchSize, uploadFn, queue) {
        this.#batchSize = batchSize;
        this.#uploadFn = uploadFn;
        this.#queue = queue;
    }
    enqueue(file) {
        return new Promise((resolve, reject) => {
            this.#pending.push({ file, resolve, reject });
            if (this.#timer) {
                clearTimeout(this.#timer);
            }
            if (this.#pending.length >= this.#batchSize) {
                this.#timer = null;
                this.#flush();
            }
            else {
                this.#timer = setTimeout(() => this.#flush(), 50);
            }
        });
    }
    destroy() {
        if (this.#timer !== null) {
            clearTimeout(this.#timer);
            this.#timer = null;
        }
        this.#pending.splice(0).forEach(p => p.reject(new Error('Upload cancelled')));
    }
    #flush() {
        this.#timer = null;
        const all = this.#pending.splice(0);
        if (all.length === 0) {
            return;
        }
        for (let i = 0; i < all.length; i += this.#batchSize) {
            const batch = all.slice(i, i + this.#batchSize);
            this.#queue
                .run(() => this.#uploadFn(batch.map(p => p.file)))
                .then(details => {
                batch.forEach((p, idx) => {
                    if (details && details[idx]) {
                        p.resolve(details[idx]);
                    }
                    else {
                        p.reject(new Error('Upload failed: Missing details from server'));
                    }
                });
            })
                .catch(err => {
                batch.forEach(p => p.reject(err));
            });
        }
    }
}
class DeferredImageUploadAdapter {
    #loader;
    #pendingFiles;
    #imageMetaMap;
    #validation;
    #onWarning;
    #i18n;
    #lazyLoad;
    #currentBlobUrl = null;
    constructor(loader, pendingFiles, imageMetaMap, options) {
        this.#loader = loader;
        this.#pendingFiles = pendingFiles;
        this.#imageMetaMap = imageMetaMap;
        this.#validation = options.validation;
        this.#onWarning = options.onWarning;
        this.#i18n = options.i18n;
        this.#lazyLoad = options.lazyLoad;
    }
    upload = async () => {
        const file = await validateAndGetFile(this.#loader, this.#validation, this.#onWarning, this.#i18n);
        if (!file)
            throw new Error('Image validation failed');
        this.#currentBlobUrl = URL.createObjectURL(file);
        this.#pendingFiles.set(this.#currentBlobUrl, file);
        this.#imageMetaMap.set(this.#currentBlobUrl, { fileName: file.name, lazyLoad: this.#lazyLoad });
        return { default: this.#currentBlobUrl };
    };
    abort() {
        if (this.#currentBlobUrl) {
            URL.revokeObjectURL(this.#currentBlobUrl);
            this.#pendingFiles.delete(this.#currentBlobUrl);
            this.#imageMetaMap.delete(this.#currentBlobUrl);
        }
    }
}
class ImmediateImageUploadAdapter {
    #loader;
    #validation;
    #onWarning;
    #i18n;
    #scheduler;
    #imageMetaMap;
    #lazyLoad;
    constructor(loader, scheduler, imageMetaMap, options) {
        this.#loader = loader;
        this.#scheduler = scheduler;
        this.#imageMetaMap = imageMetaMap;
        this.#validation = options.validation;
        this.#onWarning = options.onWarning;
        this.#i18n = options.i18n;
        this.#lazyLoad = options.lazyLoad;
    }
    upload = async () => {
        const file = await validateAndGetFile(this.#loader, this.#validation, this.#onWarning, this.#i18n);
        if (!file)
            throw new Error('Image validation failed');
        const detail = await this.#scheduler.enqueue(file);
        this.#imageMetaMap.set(detail.cdn, {
            name: detail.name,
            fileName: file.name,
            idOrKey: detail.idOrKey,
            lazyLoad: this.#lazyLoad,
        });
        return { default: detail.cdn };
    };
    abort() { }
}
class EditorImageUploadPlugin extends Plugin {
    pendingFiles = new Map();
    uploadQueue;
    #batchScheduler;
    #imageMetaMap = new Map();
    setMeta(cdnUrl, meta) {
        this.#imageMetaMap.set(cdnUrl, { name: meta.name, idOrKey: meta.idOrKey, lazyLoad: meta.lazyLoad });
    }
    static get pluginName() {
        return 'EditorImageUploadPlugin';
    }
    static get requires() {
        return [FileRepository, Image, ImageResize, ImageUpload, ImageStyle, ImageToolbar];
    }
    init() {
        const editor = this.editor;
        const getOption = editor.config.get('getOption');
        const maxConcurrent = getOption?.()?.imageConfig?.maxConcurrentUploads ?? 2;
        this.uploadQueue = new UploadQueue(maxConcurrent);
        this.#registerSchemaAndConverters();
        this.#listenForSrcChanges();
        editor.editing.view.document.on('clipboardInput', (evt, data) => {
            const dataTransfer = data.dataTransfer;
            if (!dataTransfer)
                return;
            const hasImageFiles = Array.from(dataTransfer.files ?? []).some(f => f.type.startsWith('image/'));
            const hasImageInHtml = /<img[\s>]/i.test(dataTransfer.getData('text/html') ?? '');
            if (hasImageFiles || hasImageInHtml) {
                evt.stop();
            }
        }, { priority: 'highest' });
        const uploadImageCommand = editor.commands.get('uploadImage');
        if (uploadImageCommand) {
            uploadImageCommand.on('execute', (evt, args) => {
                const options = args[0] || {};
                const option = getOption?.();
                const maxPerSelection = option?.imageConfig?.maxImagesPerSelection;
                if (maxPerSelection !== undefined) {
                    const files = Array.isArray(options?.file) ? options.file : options?.file ? [options.file] : [];
                    if (files.length > maxPerSelection) {
                        // Angular wrapper luôn truyền _i18n; nếu thiếu thì warning sẽ là chuỗi rỗng (i18n service tự log missing key)
                        const msg = option?._i18n?.t('core.component.editor.image.max-per-selection', { max: maxPerSelection }) ?? '';
                        option?.onWarning?.(msg);
                        evt.stop();
                    }
                }
            }, { priority: 'high' });
        }
        editor.once('ready', () => {
            const notification = editor.plugins.get('Notification');
            notification?.on('show:warning', (evt) => {
                evt.stop();
            }, { priority: 'highest' });
        });
        editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
            const option = getOption?.();
            const imageConfig = option?.imageConfig;
            const uploadMode = imageConfig?.uploadMode ?? 'deferred';
            const validation = imageConfig?.validation;
            const onWarning = option?.onWarning;
            const i18n = option?._i18n;
            const lazyLoad = imageConfig?.lazyLoad ?? true;
            if (uploadMode === 'deferred') {
                return new DeferredImageUploadAdapter(loader, this.pendingFiles, this.#imageMetaMap, { validation, onWarning, i18n, lazyLoad });
            }
            if (!this.#batchScheduler) {
                const uploadFn = option?.uploadFn;
                if (uploadFn) {
                    const batchSize = imageConfig?.batchSize ?? 2;
                    this.#batchScheduler = new BatchUploadScheduler(batchSize, uploadFn, this.uploadQueue);
                }
            }
            if (!this.#batchScheduler) {
                throw new Error('No upload function configured');
            }
            return new ImmediateImageUploadAdapter(loader, this.#batchScheduler, this.#imageMetaMap, { validation, onWarning, i18n, lazyLoad });
        };
    }
    destroy() {
        super.destroy();
        this.#batchScheduler?.destroy();
        for (const blobUrl of this.pendingFiles.keys()) {
            URL.revokeObjectURL(blobUrl);
        }
        this.pendingFiles.clear();
        this.#imageMetaMap.clear();
    }
    #registerSchemaAndConverters() {
        const editor = this.editor;
        const schema = editor.model.schema;
        for (const type of ['imageBlock', 'imageInline']) {
            if (schema.isRegistered(type)) {
                schema.extend(type, { allowAttributes: ['loading', 'imageId'] });
            }
        }
        // Downcast: model → HTML view
        editor.conversion.for('downcast').add((dispatcher) => {
            for (const [modelAttr, htmlAttr] of [
                ['loading', 'loading'],
                ['imageId', 'id'],
            ]) {
                const handleAttribute = (isBlock) => (evt, data, conversionApi) => {
                    if (!conversionApi.consumable.consume(data.item, evt.name))
                        return;
                    const viewElement = conversionApi.mapper.toViewElement(data.item);
                    const viewImg = isBlock ? this.#findImg(viewElement) : viewElement;
                    if (!viewImg)
                        return;
                    if (data.attributeNewValue != null) {
                        conversionApi.writer.setAttribute(htmlAttr, String(data.attributeNewValue), viewImg);
                    }
                    else {
                        conversionApi.writer.removeAttribute(htmlAttr, viewImg);
                    }
                };
                dispatcher.on(`attribute:${modelAttr}:imageBlock`, handleAttribute(true));
                dispatcher.on(`attribute:${modelAttr}:imageInline`, handleAttribute(false));
            }
        });
        // Upcast: HTML → model
        editor.conversion.for('upcast').add((dispatcher) => {
            dispatcher.on('element:figure', (_evt, data, conversionApi) => {
                if (!data.viewItem.hasClass('image'))
                    return;
                const modelElement = data.modelRange?.start?.nodeAfter;
                if (!modelElement)
                    return;
                const viewImg = this.#findImg(data.viewItem);
                if (!viewImg)
                    return;
                this.#transferHtmlAttrsToModel(viewImg, modelElement, conversionApi);
            }, { priority: 'low' });
            dispatcher.on('element:img', (_evt, data, conversionApi) => {
                const modelElement = data.modelRange?.start?.nodeAfter;
                if (!modelElement)
                    return;
                this.#transferHtmlAttrsToModel(data.viewItem, modelElement, conversionApi);
            }, { priority: 'low' });
        });
    }
    #listenForSrcChanges() {
        const editor = this.editor;
        editor.model.document.on('change', () => {
            const changes = editor.model.document.differ.getChanges();
            const updates = [];
            for (const change of changes) {
                if (change.type !== 'attribute' || change.attributeKey !== 'src')
                    continue;
                const newSrc = change.attributeNewValue;
                const meta = this.#imageMetaMap.get(newSrc);
                if (!meta)
                    continue;
                const node = change.range?.start?.nodeAfter;
                if (node?.is('element')) {
                    updates.push({ element: node, meta });
                    this.#imageMetaMap.delete(newSrc);
                }
            }
            if (updates.length === 0)
                return;
            editor.model.enqueueChange('transparent', (writer) => {
                for (const { element, meta } of updates) {
                    if (meta.name || meta.fileName) {
                        writer.setAttribute('alt', meta.name || this.#generateAlt(meta.fileName), element);
                    }
                    if (meta.lazyLoad) {
                        writer.setAttribute('loading', 'lazy', element);
                    }
                    if (meta.idOrKey) {
                        writer.setAttribute('imageId', meta.idOrKey, element);
                    }
                }
            });
        });
    }
    #findImg(viewElement) {
        if (!viewElement)
            return null;
        if (viewElement.is?.('element', 'img'))
            return viewElement;
        for (const child of viewElement.getChildren?.() ?? []) {
            if (child.is?.('element', 'img'))
                return child;
        }
        return null;
    }
    #transferHtmlAttrsToModel(viewImg, modelElement, conversionApi) {
        const schema = this.editor.model.schema;
        if (viewImg.hasAttribute('loading') && schema.checkAttribute(modelElement, 'loading')) {
            conversionApi.writer.setAttribute('loading', viewImg.getAttribute('loading'), modelElement);
        }
        if (viewImg.hasAttribute('id') && schema.checkAttribute(modelElement, 'imageId')) {
            conversionApi.writer.setAttribute('imageId', viewImg.getAttribute('id'), modelElement);
        }
    }
    #generateAlt(fileName) {
        if (!fileName)
            return 'Image';
        const nameWithoutExt = fileName.replace(/\.[^.]+$/, '');
        const result = nameWithoutExt
            .replace(/[_\-\.]+/g, ' ')
            .replace(/\s+/g, ' ')
            .trim();
        return result || 'Image';
    }
}

class SdEditor {
    // Injected
    #destroyRef = inject(DestroyRef);
    #cdRef = inject(ChangeDetectorRef);
    #uploadConfig = inject(SD_EDITOR_CONFIGURATION, { optional: true });
    #notifyService = inject(SdNotifyService);
    #i18n = inject(I18nService);
    // Input
    option = input({}, ...(ngDevMode ? [{ debugName: "option" }] : []));
    height = input('250px', ...(ngDevMode ? [{ debugName: "height" }] : [])); // Chiều dài height hiển thị mặc định
    maxHeight = input('250px', ...(ngDevMode ? [{ debugName: "maxHeight" }] : [])); // Chiều dài tối đa mở rộng nếu nội dung vượt quá height mặc định
    maxlength = input(undefined, ...(ngDevMode ? [{ debugName: "maxlength" }] : []));
    label = input(...(ngDevMode ? [undefined, { debugName: "label" }] : []));
    helperText = input(...(ngDevMode ? [undefined, { debugName: "helperText" }] : []));
    required = input(false, ...(ngDevMode ? [{ debugName: "required", transform: booleanAttribute }] : [{ transform: booleanAttribute }]));
    disabled = input(false, ...(ngDevMode ? [{ debugName: "disabled", transform: booleanAttribute }] : [{ transform: booleanAttribute }]));
    readonly = input(false, ...(ngDevMode ? [{ debugName: "readonly", transform: booleanAttribute }] : [{ transform: booleanAttribute }]));
    hideInlineError = input(false, ...(ngDevMode ? [{ debugName: "hideInlineError", transform: booleanAttribute }] : [{ transform: booleanAttribute }]));
    inlineError = input(...(ngDevMode ? [undefined, { debugName: "inlineError" }] : []));
    placeholder = input(...(ngDevMode ? [undefined, { debugName: "placeholder" }] : []));
    validator = input(...(ngDevMode ? [undefined, { debugName: "validator" }] : []));
    form = input(undefined, ...(ngDevMode ? [{ debugName: "form", transform: (val) => {
                if (!val)
                    return undefined;
                if (val instanceof NgForm)
                    return val.form;
                if (val instanceof FormGroup)
                    return val;
                if (val?.form instanceof FormGroup)
                    return val.form;
                return undefined;
            } }] : [{
            transform: (val) => {
                if (!val)
                    return undefined;
                if (val instanceof NgForm)
                    return val.form;
                if (val instanceof FormGroup)
                    return val;
                if (val?.form instanceof FormGroup)
                    return val.form;
                return undefined;
            },
        }]));
    key = input(undefined, ...(ngDevMode ? [{ debugName: "key" }] : []));
    autoIdInput = input(undefined, ...(ngDevMode ? [{ debugName: "autoIdInput", alias: 'autoId' }] : [{ alias: 'autoId' }]));
    autoId = computed(() => (this.autoIdInput() ? `components-editor-${this.autoIdInput()}` : undefined), ...(ngDevMode ? [{ debugName: "autoId" }] : []));
    dataDisabled = computed(() => (this.disabled() ? 'true' : 'false'), ...(ngDevMode ? [{ debugName: "dataDisabled" }] : []));
    dataEmpty = computed(() => (sdIsEmpty(this.valueModel()) ? 'true' : 'false'), ...(ngDevMode ? [{ debugName: "dataEmpty" }] : []));
    name = input(uuid.v4(), ...(ngDevMode ? [{ debugName: "name" }] : []));
    valueModel = model('', ...(ngDevMode ? [{ debugName: "valueModel", alias: 'model' }] : [{ alias: 'model' }]));
    // Output
    sdChange = output();
    sdBlur = output();
    sdFocus = output();
    // State
    _textLength = signal(0, ...(ngDevMode ? [{ debugName: "_textLength" }] : []));
    formControl = new SdFormControl();
    isOverLimit = computed(() => {
        const max = this.maxlength();
        return max !== undefined && this._textLength() > max;
    }, ...(ngDevMode ? [{ debugName: "isOverLimit" }] : []));
    get errorMessage() {
        const errors = this.formControl.errors;
        if (!errors)
            return undefined;
        if (errors['required'])
            return this.#i18n.t('core.component.editor.required');
        if (errors['maxlength'])
            return this.#i18n.t('core.component.editor.maxlength', { max: this.maxlength() ?? 0 });
        if (errors['customValidator'])
            return errors['customValidator'];
        if (errors['inlineError'])
            return this.inlineError();
        return undefined;
    }
    Editor = ClassicEditor;
    #editor;
    #contentChangeSubject = new Subject();
    editorConfig = computed(() => {
        const opt = this.option();
        const uploadFn = this.#buildUploadFn();
        const enableImageUpload = !!uploadFn;
        const plugins = [Essentials, FontColor, FontSize, Paragraph, Bold, Italic, Underline, List, Undo, Widget, Alignment];
        if (enableImageUpload)
            plugins.push(EditorImageUploadPlugin);
        const toolbarItems = [
            'bold',
            'italic',
            'underline',
            '|',
            'fontSize',
            'fontColor',
            '|',
            'alignment:left',
            'alignment:center',
            'alignment:right',
            'alignment:justify',
            '|',
            'bulletedList',
            'numberedList',
        ];
        if (enableImageUpload)
            toolbarItems.push('|', 'uploadImage');
        const config = {
            licenseKey: 'GPL',
            getOption: () => ({
                ...opt,
                uploadFn,
                onWarning: (msg) => this.#notifyService.warning(msg),
                // Truyền i18n service xuống CKEditor plugin (ngoài DI tree) để dịch warning messages
                _i18n: this.#i18n,
            }),
            plugins,
            toolbar: { items: toolbarItems, shouldNotGroupWhenFull: true },
            placeholder: this.placeholder(),
            fontColor: { columns: 5, documentColors: 10, colorPicker: { format: 'hex' } },
            fontSize: { options: [10, 11, 12, 14, 16, 18, 20], supportAllValues: true },
        };
        if (enableImageUpload) {
            config.image = {
                resizeUnit: '%',
                resizeOptions: [
                    { name: 'resizeImage:100', value: '100', label: '100%' },
                    { name: 'resizeImage:75', value: '75', label: '75%' },
                    { name: 'resizeImage:50', value: '50', label: '50%' },
                    { name: 'resizeImage:25', value: '25', label: '25%' },
                    { name: 'resizeImage:original', value: null, label: 'Original' },
                ],
                toolbar: ['resizeImage', '|', 'imageStyle:alignBlockLeft', 'imageStyle:alignCenter', 'imageStyle:alignBlockRight'],
            };
        }
        return config;
    }, ...(ngDevMode ? [{ debugName: "editorConfig" }] : []));
    constructor() {
        this.#validateDuplicateConfigKeys();
        this.#setupEffects();
        this.#setupSubscriptions();
        this.#setupDestroy();
    }
    onReady = (editor) => {
        this.#editor = editor;
        const currentValue = this.valueModel();
        if (currentValue) {
            this.#setToEditor(currentValue);
        }
        if (this.formControl.disabled) {
            editor.enableReadOnlyMode('sd-editor');
        }
        if (this.readonly()) {
            editor.enableReadOnlyMode('sd-editor-readonly');
        }
        editor.model.document.registerPostFixer(writer => {
            let changed = false;
            for (const change of editor.model.document.differ.getChanges()) {
                if (change.type === 'insert' && (change.name === 'imageBlock' || change.name === 'imageInline')) {
                    const element = change.position.nodeAfter;
                    if (element && !element.hasAttribute('resizedWidth')) {
                        writer.setAttribute('resizedWidth', '100%', element);
                        changed = true;
                    }
                }
            }
            return changed;
        });
        editor.model.document.on('change:data', () => this.#contentChangeSubject.next(editor.getData()));
        editor.editing.view.document.on('focus', evt => this.sdFocus.emit(evt.domEvent));
        editor.editing.view.document.on('blur', evt => {
            this.sdBlur.emit(evt.domEvent);
            this.formControl.markAsTouched();
            this.#cdRef.markForCheck();
        });
    };
    focusEditor = () => this.#editor?.editing?.view?.focus?.();
    /**
     * Xử lý tải lên các file và trả về nội dung dữ liệu cuối cùng.
     * * @description
     * - Đối với các file upload chế độ 'deferred' (chỉ xử lý khi submit), cần @ViewChild component và gọi hàm upload() này.
     * - Hỗ trợ two-way binding.
     * - Hàm hỗ trợ trả ra data cuối cùng.
     * * @returns {Promise<string>} Nội dung cuối cùng được trích xuất từ sd-editor.
     */
    upload = async () => {
        await this.#uploadImages();
        return this.#getFromEditor();
    };
    // Editor Content
    #setToEditor(html) {
        this.#editor?.setData?.(this.#normalizeHtmlForEditor(html));
    }
    #getFromEditor() {
        return this.#editor ? this.#normalizeEditorToHtml(this.#editor.getData()) : '';
    }
    // Normalize HTML từ bên ngoài -> format CKEditor.
    #normalizeHtmlForEditor = (html) => {
        if (!html) {
            return '';
        }
        let result = html;
        result = imageInlineStylesToClasses(result);
        return result;
    };
    // Normalize HTML từ CKEditor → format HTML.
    #normalizeEditorToHtml = (html) => {
        if (!html) {
            return '';
        }
        let result = html;
        result = imageClassesToInlineStyles(result);
        return result;
    };
    // Xử lý binding 2 chiều
    #onModelSignalChange(html) {
        const v = html ?? '';
        if (this.formControl.value === v) {
            return;
        }
        this.formControl.setValue(v, { emitEvent: false });
        this._textLength.set(countTextLength(v));
        if (this.#editor) {
            this.#setToEditor(v);
        }
    }
    // Xử lý khi user soạn thảo
    #onEditorUserInput(rawHtml) {
        const out = imageClassesToInlineStyles(rawHtml);
        this._textLength.set(countTextLength(out));
        if (this.formControl.value !== out) {
            this.formControl.setValue(out, { emitEvent: false });
        }
        this.formControl.updateValueAndValidity({ emitEvent: false });
        this.formControl.sdChanges.next(true);
        this.valueModel.set(out);
        this.sdChange.emit(out);
    }
    // Xử lý nếu dev sử dụng form và set trực tiếp data
    #onFormGroupExternalChange(html) {
        const v = html ?? '';
        this.valueModel.set(v);
        this._textLength.set(countTextLength(v));
        if (this.#editor) {
            this.#setToEditor(v);
        }
    }
    // Validators
    #requiredValidator() {
        return () => (this._textLength() ? null : { required: true });
    }
    #maxLengthValidator() {
        return () => {
            const max = this.maxlength();
            const len = this._textLength();
            return len > max ? { maxlength: { requiredLength: max, actualLength: len } } : null;
        };
    }
    #inlineErrorValidator() {
        return () => ({ inlineError: true });
    }
    #updateValidators() {
        const validators = [];
        const asyncValidators = [];
        if (this.required()) {
            validators.push(this.#requiredValidator());
        }
        if (this.maxlength() !== undefined) {
            validators.push(this.#maxLengthValidator());
        }
        if (this.inlineError()) {
            validators.push(this.#inlineErrorValidator());
        }
        const val = this.validator();
        if (val) {
            asyncValidators.push(HandleSdCustomValidator(val));
        }
        this.formControl.setValidators(validators.length ? validators : null);
        this.formControl.setAsyncValidators(asyncValidators.length ? asyncValidators : null);
        this.formControl.updateValueAndValidity({ emitEvent: false });
    }
    // Setup
    #setupEffects() {
        // Lắng nghe disabled
        effect(() => {
            this.disabled() ? this.formControl.disable({ emitEvent: false }) : this.formControl.enable({ emitEvent: false });
        });
        // Lắng nghe readonly
        effect(() => {
            if (!this.#editor) {
                return;
            }
            if (this.readonly()) {
                this.#editor.enableReadOnlyMode('sd-editor-readonly');
            }
            else {
                this.#editor.disableReadOnlyMode('sd-editor-readonly');
            }
        });
        // Lắng nghe binđing 2 chiều model
        effect(() => this.#onModelSignalChange(this.valueModel()));
        // Lắng nghe name form
        effect(() => this.form()?.addControl(this.name(), this.formControl));
        // Lắng nghe validators
        effect(() => {
            this.required();
            this.maxlength();
            this.inlineError();
            this.validator();
            this.#updateValidators();
        });
    }
    #setupSubscriptions() {
        // Đăng ký nếu dev sử dụng form để set data trực tiếp từ bên ngoài vào
        this.formControl.valueChanges
            .pipe(takeUntilDestroyed(this.#destroyRef))
            .subscribe((val) => this.#onFormGroupExternalChange(val));
        this.formControl.sdChanges.pipe(takeUntilDestroyed(this.#destroyRef)).subscribe(() => this.#cdRef.markForCheck());
        // Đăng ký user gõ trong editor
        this.#contentChangeSubject
            .pipe(debounceTime(100), takeUntilDestroyed(this.#destroyRef))
            .subscribe(rawHtml => this.#onEditorUserInput(rawHtml));
    }
    #setupDestroy() {
        this.#destroyRef.onDestroy(() => {
            this.form()?.removeControl(this.name());
            this.#editor?.destroy?.();
        });
    }
    // Helpers
    #uploadImages = async () => {
        const uploadMode = this.option()?.imageConfig?.uploadMode ?? 'deferred';
        // Early return nếu không phải 'deferred' mode.
        // Nếu trước đó là mode "deferred" mà mong muốn chuyển sang mode "immediate", dev chưa cần refactor code phía caller mà không ảnh hưởng đến logic.
        if (uploadMode !== 'deferred')
            return;
        const uploadFn = this.#buildUploadFn();
        if (!uploadFn) {
            throw new Error('No upload function configured for image upload');
        }
        const plugin = this.#editor?.plugins?.get(EditorImageUploadPlugin);
        if (!plugin || plugin.pendingFiles.size === 0)
            return;
        const { batchSize, maxConcurrent } = getBatchConfig(this.option());
        const activeBlobUrls = this.#editor ? getActiveBlobUrls(this.#editor) : new Set();
        const toUpload = filterActivePendingFiles(plugin.pendingFiles, activeBlobUrls);
        // Capture trước await để tránh race condition: ảnh được chèn trong lúc chờ API
        const processedBlobUrls = new Set(toUpload.map(([blobUrl]) => blobUrl));
        const { replacements, failedBatches } = await runBatchUploads(toUpload, uploadFn, batchSize, maxConcurrent);
        if (this.#editor) {
            const lazyLoad = this.option()?.imageConfig?.lazyLoad ?? true;
            for (const detail of replacements.values()) {
                plugin.setMeta(detail.cdn, { name: detail.name, idOrKey: detail.idOrKey, lazyLoad });
            }
            applyReplacementsToEditor(this.#editor, replacements);
        }
        // Chỉ xóa đúng các entries đã được xử lý
        for (const blobUrl of processedBlobUrls) {
            plugin.pendingFiles.delete(blobUrl);
        }
        for (const [blobUrl, file] of failedBatches.flat()) {
            plugin.pendingFiles.set(blobUrl, file);
        }
        if (failedBatches.length > 0) {
            throw new Error(`Upload failed for ${failedBatches.flat().length} image(s)`);
        }
    };
    #getConfigurations = () => {
        const config = this.#uploadConfig;
        if (!config) {
            return [];
        }
        return Array.isArray(config) ? config : [config];
    };
    #validateDuplicateConfigKeys = () => {
        const config = this.#uploadConfig;
        if (!config) {
            return;
        }
        const configurations = Array.isArray(config) ? config : [config];
        const seen = new Set();
        for (const cfg of configurations) {
            const normalizedKey = cfg.key === undefined ? '__undefined__' : cfg.key;
            if (seen.has(normalizedKey)) {
                const label = cfg.key === undefined ? 'undefined' : cfg.key;
                throw new Error(`[sd-editor] Duplicate upload configuration key detected: ${label}`);
            }
            seen.add(normalizedKey);
        }
    };
    #getSelectedConfig = () => {
        const configurations = this.#getConfigurations();
        if (!configurations.length) {
            return undefined;
        }
        return configurations.find(cfg => cfg.key === this.key());
    };
    #buildUploadFn = () => {
        return this.option()?.imageConfig?.uploadFn ?? this.#getSelectedConfig()?.upload;
    };
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.24", ngImport: i0, type: SdEditor, deps: [], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "20.3.24", type: SdEditor, isStandalone: true, selector: "sd-editor", inputs: { option: { classPropertyName: "option", publicName: "option", isSignal: true, isRequired: false, transformFunction: null }, height: { classPropertyName: "height", publicName: "height", isSignal: true, isRequired: false, transformFunction: null }, maxHeight: { classPropertyName: "maxHeight", publicName: "maxHeight", isSignal: true, isRequired: false, transformFunction: null }, maxlength: { classPropertyName: "maxlength", publicName: "maxlength", isSignal: true, isRequired: false, transformFunction: null }, label: { classPropertyName: "label", publicName: "label", isSignal: true, isRequired: false, transformFunction: null }, helperText: { classPropertyName: "helperText", publicName: "helperText", isSignal: true, isRequired: false, transformFunction: null }, required: { classPropertyName: "required", publicName: "required", isSignal: true, isRequired: false, transformFunction: null }, disabled: { classPropertyName: "disabled", publicName: "disabled", isSignal: true, isRequired: false, transformFunction: null }, readonly: { classPropertyName: "readonly", publicName: "readonly", isSignal: true, isRequired: false, transformFunction: null }, hideInlineError: { classPropertyName: "hideInlineError", publicName: "hideInlineError", isSignal: true, isRequired: false, transformFunction: null }, inlineError: { classPropertyName: "inlineError", publicName: "inlineError", isSignal: true, isRequired: false, transformFunction: null }, placeholder: { classPropertyName: "placeholder", publicName: "placeholder", isSignal: true, isRequired: false, transformFunction: null }, validator: { classPropertyName: "validator", publicName: "validator", isSignal: true, isRequired: false, transformFunction: null }, form: { classPropertyName: "form", publicName: "form", isSignal: true, isRequired: false, transformFunction: null }, key: { classPropertyName: "key", publicName: "key", isSignal: true, isRequired: false, transformFunction: null }, autoIdInput: { classPropertyName: "autoIdInput", publicName: "autoId", isSignal: true, isRequired: false, transformFunction: null }, name: { classPropertyName: "name", publicName: "name", isSignal: true, isRequired: false, transformFunction: null }, valueModel: { classPropertyName: "valueModel", publicName: "model", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { valueModel: "modelChange", sdChange: "sdChange", sdBlur: "sdBlur", sdFocus: "sdFocus" }, ngImport: i0, template: "<sd-ckeditor-styles />\n@let lbl = label();\n@let hText = helperText();\n@let hideErr = hideInlineError();\n@let errMsg = errorMessage;\n@let req = required();\n@let maxLen = maxlength();\n@let showCounter = !!maxLen && !formControl.disabled && !hideErr;\n\n@if (lbl) {\n  <sd-label [label]=\"lbl\" [required]=\"req\" [helperText]=\"hText\"></sd-label>\n}\n\n<div\n  class=\"sd-editor\"\n  [class.sd-editor--readonly]=\"readonly()\"\n  [class.sd-editor--error]=\"formControl.invalid && formControl.touched\"\n  [class.has-counter]=\"showCounter\"\n  [style.--sd-editor-content-min-height]=\"height()\"\n  [style.--sd-editor-content-max-height]=\"maxHeight()\"\n  [attr.data-autoId]=\"autoId()\"\n  [attr.data-disabled]=\"dataDisabled()\"\n  [attr.data-empty]=\"dataEmpty()\">\n  <ckeditor [editor]=\"Editor\" [config]=\"editorConfig()\" [disabled]=\"formControl.disabled\" (ready)=\"onReady($event)\"></ckeditor>\n\n  @if (showCounter) {\n    <div class=\"sd-editor-counter-row\">\n      <span class=\"sd-editor-counter\" [class.sd-editor-counter--over]=\"isOverLimit()\"> {{ _textLength() }}/{{ maxLen }} </span>\n    </div>\n  }\n\n  @if (hideErr && errMsg && formControl.touched) {\n    <mat-icon class=\"sd-error-icon\" [matTooltip]=\"errMsg\" matTooltipPosition=\"above\">error</mat-icon>\n  }\n</div>\n\n<div class=\"sd-editor-footer\">\n  @if (!hideErr && errMsg && formControl.touched) {\n    <mat-error>{{ errMsg }}</mat-error>\n  }\n</div>\n", styles: [".sd-editor{display:flex;flex-direction:column;width:100%;position:relative}.sd-editor-counter-row{display:flex;justify-content:flex-end;align-items:center;padding:4px 12px;border:1px solid var(--ck-color-base-border);border-top:none}.sd-editor-footer{min-height:20px;margin-top:4px}.sd-editor-footer mat-error{font-size:12px;color:var(--mdc-theme-error, #f44336)}.sd-error-icon{position:absolute;right:8px;bottom:8px;z-index:2;color:var(--mdc-theme-error, #f44336);height:20px;width:20px;font-size:20px;cursor:default}.sd-editor--readonly :host ::ng-deep .ck-editor__editable{background:#0000000a;cursor:default}.sd-editor-counter{font-size:12px;color:#0009}.sd-editor-counter--over{color:var(--mdc-theme-error, #f44336)}::ng-deep .ck-powered-by,::ng-deep .ck-powered-by-balloon{display:none!important}:host ::ng-deep ckeditor,:host ::ng-deep .ck-editor{display:flex;flex-direction:column}:host ::ng-deep .ck-editor{--ck-content-font-size: 14px;--ck-content-line-height: 1.5}:host ::ng-deep .ck-editor__main{overflow:visible}:host ::ng-deep .ck-editor__editable{min-height:var(--sd-editor-content-min-height, 200px)!important;max-height:var(--sd-editor-content-max-height, none)!important;padding:24px!important;overflow-y:auto!important;border:1px solid var(--ck-color-base-border)!important}:host ::ng-deep .ck-editor__editable.ck-focused{box-shadow:none!important}:host ::ng-deep .sd-editor.has-counter .ck-editor__editable{border-bottom:none!important}:host ::ng-deep .sd-editor--error .ck-editor__editable,:host ::ng-deep .sd-editor--error .ck-toolbar{border-color:var(--mdc-theme-error, #f44336)!important}:host ::ng-deep .sd-editor--error.has-counter .sd-editor-counter-row{border-color:var(--mdc-theme-error, #f44336)}:host ::ng-deep .ck-content p{margin-bottom:var(--ck-spacing-large);text-indent:0}:host ::ng-deep .ck-content ul,:host ::ng-deep .ck-content ol{margin-left:0!important;padding-left:20px!important}\n", ":host ::ng-deep .ck-content img{max-width:100%!important;height:auto!important;object-fit:contain}:host ::ng-deep .ck-content figure.image{position:relative;display:block;width:fit-content;max-width:100%;margin:0 auto;overflow:visible}:host ::ng-deep .ck-content figure.image:hover{z-index:99999!important}:host ::ng-deep .ck-content figure.image.image-style-align-left{float:left;margin:0 1em 0 0}:host ::ng-deep .ck-content figure.image.image-style-align-left[style*=\"width:100\"]{float:none;margin:0 auto 0 0}:host ::ng-deep .ck-content figure.image.image-style-align-right{float:right;margin:0 0 0 1em}:host ::ng-deep .ck-content figure.image.image-style-align-right[style*=\"width:100\"]{float:none;margin:0 0 0 auto}:host ::ng-deep .ck-content figure.image.image-style-block-align-left{margin:0 auto 0 0}:host ::ng-deep .ck-content figure.image.image-style-block-align-right{margin:0 0 0 auto}:host ::ng-deep .ck-content figure.image .ck-progress-bar{position:absolute;bottom:0;left:0;width:30%!important;height:3px;background:var(--sd-color-primary, #1565c0);border-radius:2px;z-index:10;pointer-events:none;animation:sd-progress-indeterminate 1.4s ease-in-out infinite}:host ::ng-deep .ck-content figure.image:has(.ck-progress-bar){overflow:hidden}:host ::ng-deep .ck-content figure.image:has(.ck-progress-bar) img{filter:blur(1px) brightness(.85);transition:filter .3s ease}:host ::ng-deep .ck-content figure.image:has(.ck-progress-bar):after{content:\"\";position:absolute;inset:0;display:flex;align-items:center;justify-content:center;z-index:9;background:#ffffff40;border-radius:inherit}:host ::ng-deep .ck-content figure.image:has(.ck-progress-bar):before{content:\"\";position:absolute;top:50%;left:50%;width:28px;height:28px;margin:-14px 0 0 -14px;border:3px solid rgba(255,255,255,.5);border-top-color:var(--sd-color-primary, #1565c0);border-radius:50%;animation:sd-spinner .75s linear infinite;z-index:11;pointer-events:none}@keyframes sd-spinner{to{transform:rotate(360deg)}}@keyframes sd-progress-indeterminate{0%{left:-30%}to{left:100%}}\n"], dependencies: [{ kind: "ngmodule", type: CKEditorModule }, { kind: "component", type: i1.CKEditorComponent, selector: "ckeditor", inputs: ["editor", "config", "data", "tagName", "watchdog", "editorWatchdogConfig", "disableWatchdog", "disableTwoWayDataBinding", "disabled"], outputs: ["ready", "change", "blur", "focus", "error"] }, { kind: "component", type: SdLabel, selector: "sd-label", inputs: ["label", "description", "required", "helperText"] }, { kind: "component", type: SdCKEditorStyles, selector: "sd-ckeditor-styles" }, { kind: "ngmodule", type: MatFormFieldModule }, { kind: "directive", type: i2.MatError, selector: "mat-error, [matError]", inputs: ["id"] }, { kind: "ngmodule", type: MatIconModule }, { kind: "component", type: i3.MatIcon, selector: "mat-icon", inputs: ["color", "inline", "svgIcon", "fontSet", "fontIcon"], exportAs: ["matIcon"] }, { kind: "ngmodule", type: MatTooltipModule }, { kind: "directive", type: i4.MatTooltip, selector: "[matTooltip]", inputs: ["matTooltipPosition", "matTooltipPositionAtOrigin", "matTooltipDisabled", "matTooltipShowDelay", "matTooltipHideDelay", "matTooltipTouchGestures", "matTooltip", "matTooltipClass"], exportAs: ["matTooltip"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.24", ngImport: i0, type: SdEditor, decorators: [{
            type: Component,
            args: [{ selector: 'sd-editor', standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, imports: [CKEditorModule, SdLabel, SdCKEditorStyles, MatFormFieldModule, MatIconModule, MatTooltipModule], template: "<sd-ckeditor-styles />\n@let lbl = label();\n@let hText = helperText();\n@let hideErr = hideInlineError();\n@let errMsg = errorMessage;\n@let req = required();\n@let maxLen = maxlength();\n@let showCounter = !!maxLen && !formControl.disabled && !hideErr;\n\n@if (lbl) {\n  <sd-label [label]=\"lbl\" [required]=\"req\" [helperText]=\"hText\"></sd-label>\n}\n\n<div\n  class=\"sd-editor\"\n  [class.sd-editor--readonly]=\"readonly()\"\n  [class.sd-editor--error]=\"formControl.invalid && formControl.touched\"\n  [class.has-counter]=\"showCounter\"\n  [style.--sd-editor-content-min-height]=\"height()\"\n  [style.--sd-editor-content-max-height]=\"maxHeight()\"\n  [attr.data-autoId]=\"autoId()\"\n  [attr.data-disabled]=\"dataDisabled()\"\n  [attr.data-empty]=\"dataEmpty()\">\n  <ckeditor [editor]=\"Editor\" [config]=\"editorConfig()\" [disabled]=\"formControl.disabled\" (ready)=\"onReady($event)\"></ckeditor>\n\n  @if (showCounter) {\n    <div class=\"sd-editor-counter-row\">\n      <span class=\"sd-editor-counter\" [class.sd-editor-counter--over]=\"isOverLimit()\"> {{ _textLength() }}/{{ maxLen }} </span>\n    </div>\n  }\n\n  @if (hideErr && errMsg && formControl.touched) {\n    <mat-icon class=\"sd-error-icon\" [matTooltip]=\"errMsg\" matTooltipPosition=\"above\">error</mat-icon>\n  }\n</div>\n\n<div class=\"sd-editor-footer\">\n  @if (!hideErr && errMsg && formControl.touched) {\n    <mat-error>{{ errMsg }}</mat-error>\n  }\n</div>\n", styles: [".sd-editor{display:flex;flex-direction:column;width:100%;position:relative}.sd-editor-counter-row{display:flex;justify-content:flex-end;align-items:center;padding:4px 12px;border:1px solid var(--ck-color-base-border);border-top:none}.sd-editor-footer{min-height:20px;margin-top:4px}.sd-editor-footer mat-error{font-size:12px;color:var(--mdc-theme-error, #f44336)}.sd-error-icon{position:absolute;right:8px;bottom:8px;z-index:2;color:var(--mdc-theme-error, #f44336);height:20px;width:20px;font-size:20px;cursor:default}.sd-editor--readonly :host ::ng-deep .ck-editor__editable{background:#0000000a;cursor:default}.sd-editor-counter{font-size:12px;color:#0009}.sd-editor-counter--over{color:var(--mdc-theme-error, #f44336)}::ng-deep .ck-powered-by,::ng-deep .ck-powered-by-balloon{display:none!important}:host ::ng-deep ckeditor,:host ::ng-deep .ck-editor{display:flex;flex-direction:column}:host ::ng-deep .ck-editor{--ck-content-font-size: 14px;--ck-content-line-height: 1.5}:host ::ng-deep .ck-editor__main{overflow:visible}:host ::ng-deep .ck-editor__editable{min-height:var(--sd-editor-content-min-height, 200px)!important;max-height:var(--sd-editor-content-max-height, none)!important;padding:24px!important;overflow-y:auto!important;border:1px solid var(--ck-color-base-border)!important}:host ::ng-deep .ck-editor__editable.ck-focused{box-shadow:none!important}:host ::ng-deep .sd-editor.has-counter .ck-editor__editable{border-bottom:none!important}:host ::ng-deep .sd-editor--error .ck-editor__editable,:host ::ng-deep .sd-editor--error .ck-toolbar{border-color:var(--mdc-theme-error, #f44336)!important}:host ::ng-deep .sd-editor--error.has-counter .sd-editor-counter-row{border-color:var(--mdc-theme-error, #f44336)}:host ::ng-deep .ck-content p{margin-bottom:var(--ck-spacing-large);text-indent:0}:host ::ng-deep .ck-content ul,:host ::ng-deep .ck-content ol{margin-left:0!important;padding-left:20px!important}\n", ":host ::ng-deep .ck-content img{max-width:100%!important;height:auto!important;object-fit:contain}:host ::ng-deep .ck-content figure.image{position:relative;display:block;width:fit-content;max-width:100%;margin:0 auto;overflow:visible}:host ::ng-deep .ck-content figure.image:hover{z-index:99999!important}:host ::ng-deep .ck-content figure.image.image-style-align-left{float:left;margin:0 1em 0 0}:host ::ng-deep .ck-content figure.image.image-style-align-left[style*=\"width:100\"]{float:none;margin:0 auto 0 0}:host ::ng-deep .ck-content figure.image.image-style-align-right{float:right;margin:0 0 0 1em}:host ::ng-deep .ck-content figure.image.image-style-align-right[style*=\"width:100\"]{float:none;margin:0 0 0 auto}:host ::ng-deep .ck-content figure.image.image-style-block-align-left{margin:0 auto 0 0}:host ::ng-deep .ck-content figure.image.image-style-block-align-right{margin:0 0 0 auto}:host ::ng-deep .ck-content figure.image .ck-progress-bar{position:absolute;bottom:0;left:0;width:30%!important;height:3px;background:var(--sd-color-primary, #1565c0);border-radius:2px;z-index:10;pointer-events:none;animation:sd-progress-indeterminate 1.4s ease-in-out infinite}:host ::ng-deep .ck-content figure.image:has(.ck-progress-bar){overflow:hidden}:host ::ng-deep .ck-content figure.image:has(.ck-progress-bar) img{filter:blur(1px) brightness(.85);transition:filter .3s ease}:host ::ng-deep .ck-content figure.image:has(.ck-progress-bar):after{content:\"\";position:absolute;inset:0;display:flex;align-items:center;justify-content:center;z-index:9;background:#ffffff40;border-radius:inherit}:host ::ng-deep .ck-content figure.image:has(.ck-progress-bar):before{content:\"\";position:absolute;top:50%;left:50%;width:28px;height:28px;margin:-14px 0 0 -14px;border:3px solid rgba(255,255,255,.5);border-top-color:var(--sd-color-primary, #1565c0);border-radius:50%;animation:sd-spinner .75s linear infinite;z-index:11;pointer-events:none}@keyframes sd-spinner{to{transform:rotate(360deg)}}@keyframes sd-progress-indeterminate{0%{left:-30%}to{left:100%}}\n"] }]
        }], ctorParameters: () => [], propDecorators: { option: [{ type: i0.Input, args: [{ isSignal: true, alias: "option", required: false }] }], height: [{ type: i0.Input, args: [{ isSignal: true, alias: "height", required: false }] }], maxHeight: [{ type: i0.Input, args: [{ isSignal: true, alias: "maxHeight", required: false }] }], maxlength: [{ type: i0.Input, args: [{ isSignal: true, alias: "maxlength", required: false }] }], label: [{ type: i0.Input, args: [{ isSignal: true, alias: "label", required: false }] }], helperText: [{ type: i0.Input, args: [{ isSignal: true, alias: "helperText", required: false }] }], required: [{ type: i0.Input, args: [{ isSignal: true, alias: "required", required: false }] }], disabled: [{ type: i0.Input, args: [{ isSignal: true, alias: "disabled", required: false }] }], readonly: [{ type: i0.Input, args: [{ isSignal: true, alias: "readonly", required: false }] }], hideInlineError: [{ type: i0.Input, args: [{ isSignal: true, alias: "hideInlineError", required: false }] }], inlineError: [{ type: i0.Input, args: [{ isSignal: true, alias: "inlineError", required: false }] }], placeholder: [{ type: i0.Input, args: [{ isSignal: true, alias: "placeholder", required: false }] }], validator: [{ type: i0.Input, args: [{ isSignal: true, alias: "validator", required: false }] }], form: [{ type: i0.Input, args: [{ isSignal: true, alias: "form", required: false }] }], key: [{ type: i0.Input, args: [{ isSignal: true, alias: "key", required: false }] }], autoIdInput: [{ type: i0.Input, args: [{ isSignal: true, alias: "autoId", required: false }] }], name: [{ type: i0.Input, args: [{ isSignal: true, alias: "name", required: false }] }], valueModel: [{ type: i0.Input, args: [{ isSignal: true, alias: "model", required: false }] }, { type: i0.Output, args: ["modelChange"] }], sdChange: [{ type: i0.Output, args: ["sdChange"] }], sdBlur: [{ type: i0.Output, args: ["sdBlur"] }], sdFocus: [{ type: i0.Output, args: ["sdFocus"] }] } });

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

export { SD_EDITOR_CONFIGURATION, SdEditor };
//# sourceMappingURL=sdcorejs-angular-components-editor.mjs.map
