/**
 * @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 {
	TOKEN_URL,
	getViewportTopOffsetConfig,
	attachTourBalloon,
	findToolbarItem
} from '@snippets/index.js';
import { CkBoxEditor } from './build-ckbox-source.js';
import './ckbox.css';

const { CKBoxWidget, CKBox } = window;

CkBoxEditor
	.create( document.querySelector( '#snippet-ckbox-ckeditor' ), {
		root: {
			initialData: document.querySelector( '#snippet-ckbox-content' ).innerHTML
		},
		toolbar: {
			items: [
				'undo', 'redo',
				'|', 'heading',
				'|', 'bold', 'italic',
				'|', 'link', 'uploadImage', 'ckbox', 'ckboxImageEdit', 'insertTable', 'mediaEmbed',
				'|', 'bulletedList', 'numberedList', 'outdent', 'indent'
			]
		},
		image: {
			toolbar: [
				'toggleImageCaption',
				'imageTextAlternative',
				'|',
				'imageStyle:inline',
				'imageStyle:block',
				'imageStyle:wrapText',
				'|',
				'resizeImage:25',
				'resizeImage:50',
				'resizeImage:original',
				'|',
				'ckboxImageEdit'
			],
			resizeOptions: [
				{
					name: 'resizeImage:original',
					value: null,
					icon: 'original'
				},
				{
					name: 'resizeImage:25',
					value: '25',
					icon: 'small'
				},
				{
					name: 'resizeImage:50',
					value: '50',
					icon: 'medium'
				}
			],
			resizeUnit: '%'
		},
		ui: {
			viewportOffset: {
				top: getViewportTopOffsetConfig()
			}
		},
		ckbox: {
			tokenUrl: TOKEN_URL,
			forceDemoLabel: true,
			allowExternalImagesEditing: [ /^data:/, 'origin', /ckbox/ ]
		}
	} )
	.then( editor => {
		window.editor = editor;

		attachTourBalloon( {
			target: findToolbarItem( editor.ui.view.toolbar, item => item.label && item.label === 'Open file manager' ),
			text: 'Click to open the file manager.',
			editor
		} );
	} )
	.catch( err => {
		console.error( err.stack );
	} );

fetch( TOKEN_URL )
	.then( response => response.text() )
	.then( token => {
		const { auth } = JSON.parse( atob( token.split( '.' )[ 1 ] ) );
		const workspaceId = auth.ckbox.workspaces[ 0 ];

		CKBoxWidget.mountUploaderWidget( document.getElementById( 'snippet-ckbox-uploader-widget' ), {
			tokenUrl: TOKEN_URL,
			workspaceId,
			onUpload: asset => {
				document.getElementById( 'ckbox-uploader-asset-code-json' ).textContent = JSON.stringify( asset, null, 2 );
			},
			onDelete: () => {
				document.getElementById( 'ckbox-uploader-asset-code-json' ).textContent =
					'Upload a file to preview its asset data in this panel.';
			}
		} );
	} );

document.getElementById( 'ckbox-button' ).addEventListener( 'click', () => {
	CKBox.mount( document.getElementById( 'snippet-ckbox-standalone-root' ), {
		dialog: true,
		tokenUrl: TOKEN_URL
	} );
} );
