<link rel="stylesheet" href="/lib/ckeditor/ckeditor5/ckeditor5.css" asp-append-version="true" />

<script type="importmap">
    {
        "imports": {
            "ckeditor5": "/lib/ckeditor/ckeditor5/ckeditor5.js",
            "ckeditor5/": "/lib/ckeditor/ckeditor5/"
        }
    }
</script>

<script type="module">
    import {
        ClassicEditor, Essentials, Paragraph, Bold, Italic, Underline, Strikethrough, Code, Subscript, Superscript, RemoveFormat, List, TodoList, 
        Indent, Heading, Font, Highlight, Alignment, Link, Image, ImageToolbar, ImageCaption, ImageStyle, ImageResize, ImageUpload, MediaEmbed, CodeBlock, 
        HtmlEmbed, SpecialCharacters, HorizontalLine, PageBreak, SourceEditing, FindAndReplace, SelectAll, BlockQuote, Table, TableToolbar, TextPartLanguage
    } from 'ckeditor5';

    // 사용자 정의 업로드 어댑터
    class CustomUploadAdapter {

        constructor(loader) {
            this.loader = loader;
        }

        // 업로드 시작
        upload() {
            return this.loader.file
                .then(file => {
                    return new Promise((resolve, reject) => {
                        // 여기서 사용자가 업로드를 제어할 수 있도록 설정
                        console.log('File selected:', file);

                        // 업로드 완료 후 resolve 호출
                        // 예시:
                        // resolve({ default: 'uploaded-image-url.jpg' });

                        // 사용자가 확인 후 업로드
                        setTimeout(() => {
                            alert('사용자가 이미지를 업로드하도록 구현 필요');
                            reject('사용자가 업로드 취소');
                        }, 1000);
                    });
                });
        }

        // 취소 또는 정리 작업
        abort() {
            console.log('업로드가 취소되었습니다.');
        }
    }

    // CKEditor 초기화
    document.querySelectorAll('.ck-editor').forEach(e => {
        ClassicEditor
            .create(e, {
                licenseKey: 'GPL',
                plugins: [
                    Essentials, Paragraph, Bold, Italic, Underline, Strikethrough, Code,
                    Subscript, Superscript, RemoveFormat, List, TodoList, Indent, Heading,
                    Font, Highlight, Alignment, Link, Image, ImageToolbar, ImageCaption,
                    ImageStyle, ImageResize, ImageUpload, MediaEmbed, CodeBlock, HtmlEmbed,
                    SpecialCharacters, HorizontalLine, PageBreak, SourceEditing,
                    FindAndReplace, SelectAll, BlockQuote, Table, TableToolbar, TextPartLanguage
                ],
                toolbar: {
                    items: [
                        'findAndReplace', 'selectAll', '|',
                        'heading', '|',
                        'bold', 'italic', 'strikethrough', 'underline', 'code', 'subscript', 'superscript', 'removeFormat', '|',
                        'bulletedList', 'numberedList', 'todoList', '|',
                        'outdent', 'indent', '|',
                        'undo', 'redo', '|',
                        'fontSize', 'fontFamily', 'fontColor', 'fontBackgroundColor', 'highlight', '|',
                        'alignment', '|',
                        'link', 'insertImage', 'blockQuote', 'insertTable', 'mediaEmbed', 'codeBlock', 'htmlEmbed', '|',
                        'specialCharacters', 'horizontalLine', 'pageBreak', '|',
                        'textPartLanguage', '|',
                        'sourceEditing'
                    ],
                    shouldNotGroupWhenFull: true
                },
                list: {
                    properties: {
                        styles: true,
                        startIndex: true,
                        reversed: true
                    }
                },
                heading: {
                    options: [
                        { model: 'paragraph', title: 'Paragraph', class: 'ck-heading_paragraph' },
                        { model: 'heading1', view: 'h1', title: 'Heading 1', class: 'ck-heading_heading1' },
                        { model: 'heading2', view: 'h2', title: 'Heading 2', class: 'ck-heading_heading2' },
                        { model: 'heading3', view: 'h3', title: 'Heading 3', class: 'ck-heading_heading3' },
                        { model: 'heading4', view: 'h4', title: 'Heading 4', class: 'ck-heading_heading4' },
                        { model: 'heading5', view: 'h5', title: 'Heading 5', class: 'ck-heading_heading5' },
                        { model: 'heading6', view: 'h6', title: 'Heading 6', class: 'ck-heading_heading6' }
                    ]
                },
                placeholder: '내용을 입력해주세요.',
                fontFamily: {
                    options: [
                        'default',
                        'Arial, Helvetica, sans-serif',
                        'Courier New, Courier, monospace',
                        'Georgia, serif',
                        'Lucida Sans Unicode, Lucida Grande, sans-serif',
                        'Tahoma, Geneva, sans-serif',
                        'Times New Roman, Times, serif',
                        'Trebuchet MS, Helvetica, sans-serif',
                        'Verdana, Geneva, sans-serif'
                    ],
                    supportAllValues: true
                },
                fontSize: {
                    options: [10, 12, 14, 'default', 18, 20, 22],
                    supportAllValues: true
                },
                htmlSupport: {
                    allow: [
                        {
                            name: /.*/,
                            attributes: true,
                            classes: true,
                            styles: true
                        }
                    ]
                },
                htmlEmbed: {
                    showPreviews: true
                },
                link: {
                    decorators: {
                        addTargetToExternalLinks: true,
                        defaultProtocol: 'https://',
                        toggleDownloadable: {
                            mode: 'manual',
                            label: 'Downloadable',
                            attributes: {
                                download: 'file'
                            }
                        }
                    }
                },
                image: {
                    toolbar: [
                        'imageStyle:inline', 'imageStyle:block', 'imageStyle:side', '|',
                        'toggleImageCaption', 'imageTextAlternative'
                    ]
                },
                table: {
                    contentToolbar: ['tableColumn', 'tableRow', 'mergeTableCells']
                }
            })
            .then(editor => {
                editor.plugins.get('FileRepository').createUploadAdapter = loader => {
                    return new CustomUploadAdapter(loader); // 사용자 정의 업로드 어댑터 적용
                };

                console.log('Editor initialized', editor);
            })
            .catch(error => {
                console.error('Error initializing CKEditor:', error);
            });
    });
</script>
