/**
 * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
 */

import {
	ClassicEditor,
	Code,
	Strikethrough,
	CloudServices,
	CodeBlock,
	CKBox,
	CKBoxImageEdit,
	HorizontalLine,
	ImageUpload,
	ImageInsert,
	PictureEditing,
	AutoImage,
	TodoList,
	Markdown
} from 'ckeditor5';
import { SourceEditingEnhanced } from 'ckeditor5-premium-features';
import {
	CS_CONFIG,
	TOKEN_URL,
	ArticlePluginSet,
	getViewportTopOffsetConfig
} from '@snippets/index.js';

ClassicEditor
	.create( document.querySelector( '#snippet-markdown' ), {
		plugins: [
			ArticlePluginSet, SourceEditingEnhanced, CKBox, CKBoxImageEdit, ImageInsert, ImageUpload, PictureEditing, AutoImage,
			CloudServices, Markdown, Code, CodeBlock, TodoList, Strikethrough, HorizontalLine
		],
		toolbar: {
			items: [
				'undo', 'redo', '|', 'sourceEditingEnhanced', '|', 'heading',
				'|', 'bold', 'italic', 'strikethrough', 'code',
				'-', 'link', 'insertImage', 'insertTable', 'mediaEmbed', 'blockQuote', 'codeBlock', 'horizontalLine',
				'|', 'bulletedList', 'numberedList', 'todoList', 'outdent', 'indent'
			],
			shouldNotGroupWhenFull: true
		},
		image: {
			toolbar: [
				'imageStyle:inline',
				'imageStyle:wrapText',
				'imageStyle:breakText',
				'|',
				'toggleImageCaption',
				'imageTextAlternative',
				'|',
				'ckboxImageEdit'
			]
		},
		codeBlock: {
			languages: [
				{ language: 'css', label: 'CSS' },
				{ language: 'html', label: 'HTML' },
				{ language: 'javascript', label: 'JavaScript' },
				{ language: 'php', label: 'PHP' }
			]
		},
		cloudServices: CS_CONFIG,
		ui: {
			viewportOffset: {
				top: getViewportTopOffsetConfig()
			}
		},
		ckbox: {
			tokenUrl: TOKEN_URL,
			allowExternalImagesEditing: [ /^data:/, 'origin', /ckbox/ ],
			forceDemoLabel: true
		}
	} )
	.then( editor => {
		window.editor = editor;

		const { codeBlock } = document.querySelector( '#snippet-markdown-output' );
		const throttleRefreshPreview = window.umberto.throttle( () => {
			codeBlock.setCode( editor.getData() );
		}, 200 );

		window.umberto.afterReady( () => {
			editor.model.document.on( 'change', throttleRefreshPreview );
			throttleRefreshPreview();
		} );
	} )
	.catch( err => {
		console.error( err.stack );
	} );
