import { Controller } from '@hotwired/stimulus';

export default class extends Controller {
    static targets = ['editor'];

    async connect() {
        // Dynamically import CKEditor to avoid SSR issues
        const { ClassicEditor, Essentials, Bold, Italic, Underline, Strikethrough,
            Font, Heading, Paragraph, Alignment,
            Link, Image, ImageUpload, ImageResize, ImageStyle, ImageToolbar, ImageCaption,
            List, TodoList, Table, TableToolbar, TableProperties, TableCellProperties,
            BlockQuote, CodeBlock, HorizontalLine, Indent, IndentBlock,
            MediaEmbed, PasteFromOffice, RemoveFormat, SourceEditing,
            Highlight, FindAndReplace, SpecialCharacters, SpecialCharactersEssentials,
            HtmlEmbed
        } = await import('ckeditor5');

        // Import CKEditor styles
        await import('ckeditor5/ckeditor5.css');

        this.editorTargets.forEach(async (element) => {
            try {
                const editor = await ClassicEditor.create(element, {
                    licenseKey: 'GPL',
                    plugins: [
                        Essentials, Bold, Italic, Underline, Strikethrough,
                        Font, Heading, Paragraph, Alignment,
                        Link, Image, ImageResize, ImageStyle, ImageToolbar, ImageCaption,
                        List, TodoList,
                        Table, TableToolbar, TableProperties, TableCellProperties,
                        BlockQuote, CodeBlock, HorizontalLine,
                        Indent, IndentBlock,
                        MediaEmbed, PasteFromOffice, RemoveFormat, SourceEditing,
                        Highlight, FindAndReplace,
                        SpecialCharacters, SpecialCharactersEssentials,
                        HtmlEmbed
                    ],
                    toolbar: {
                        items: [
                            'heading', '|',
                            'bold', 'italic', 'underline', 'strikethrough', '|',
                            'fontSize', 'fontColor', 'fontBackgroundColor', 'highlight', '|',
                            'alignment', '|',
                            'bulletedList', 'numberedList', 'todoList', '|',
                            'outdent', 'indent', '|',
                            'link', 'insertImage', 'mediaEmbed', 'insertTable', 'blockQuote', '|',
                            'horizontalLine', 'codeBlock', 'htmlEmbed', '|',
                            'findAndReplace', 'removeFormat', 'sourceEditing', '|',
                            'specialCharacters', '|',
                            'undo', 'redo'
                        ],
                        shouldNotGroupWhenFull: false
                    },
                    heading: {
                        options: [
                            { model: 'paragraph', title: 'Paragraf', class: 'ck-heading_paragraph' },
                            { model: 'heading2', view: 'h2', title: 'Baslik 2', class: 'ck-heading_heading2' },
                            { model: 'heading3', view: 'h3', title: 'Baslik 3', class: 'ck-heading_heading3' },
                            { model: 'heading4', view: 'h4', title: 'Baslik 4', class: 'ck-heading_heading4' }
                        ]
                    },
                    fontSize: {
                        options: [10, 12, 14, 'default', 18, 20, 24, 28, 32]
                    },
                    image: {
                        toolbar: [
                            'imageStyle:inline', 'imageStyle:block', 'imageStyle:side', '|',
                            'toggleImageCaption', 'imageTextAlternative', '|',
                            'resizeImage'
                        ],
                        resizeOptions: [
                            { name: 'resizeImage:original', value: null, label: 'Orijinal' },
                            { name: 'resizeImage:25', value: '25', label: '25%' },
                            { name: 'resizeImage:50', value: '50', label: '50%' },
                            { name: 'resizeImage:75', value: '75', label: '75%' }
                        ]
                    },
                    table: {
                        contentToolbar: [
                            'tableColumn', 'tableRow', 'mergeTableCells',
                            'tableProperties', 'tableCellProperties'
                        ]
                    },
                    link: {
                        addTargetToExternalLinks: true,
                        defaultProtocol: 'https://'
                    },
                    mediaEmbed: {
                        previewsInData: true
                    },
                    language: 'tr',
                    placeholder: 'Haber icerigini buraya yazin...'
                });

                // Store editor instance
                element._ckeditor = editor;

                // Sync editor data back to textarea on change
                editor.model.document.on('change:data', () => {
                    element.value = editor.getData();
                    // Dispatch input event so other controllers (like seo-analyzer) react
                    element.dispatchEvent(new Event('input', { bubbles: true }));
                });

                // Style the editor area
                const editableElement = editor.ui.view.editable.element;
                editableElement.style.minHeight = '400px';
                editableElement.style.maxHeight = '700px';

            } catch (error) {
                console.error('CKEditor initialization failed:', error);
            }
        });
    }

    disconnect() {
        this.editorTargets.forEach((element) => {
            if (element._ckeditor) {
                element._ckeditor.destroy().catch(error => {
                    console.error('CKEditor destroy failed:', error);
                });
            }
        });
    }
}
