/**
 * @license Copyright (c) 2017-2025, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md.
 */

import './vendor/prism';

export function setupPrism() {
	const locationHref = window.location.href;
	const isApiPage = !!locationHref.match( /\/api\// );

	// For CKEditor 4 snippets (SDK) attach the "Download" button.
	if ( locationHref.match( /\/ckeditor4\// ) && locationHref.match( /\/examples\// ) ) {
		createDownloadButton();
	}

	Array.from( document.querySelectorAll( 'pre code' ) )
		.filter( element => {
			// Don't highlight code block's inside editor's content. See: #838.
			if ( element.closest( '.ck-content' ) ) {
				return false;
			}

			// Don't highlight the element if it contains the `no-highlight` class.
			if ( element.classList.contains( 'no-highlight' ) ) {
				return false;
			}

			return true;
		} )
		.forEach( element => {
			const classList = element.classList.values();
			const preElement = element.parentElement;

			// Don't highlight the element if it has no parent.
			if ( !preElement ) {
				return false;
			}

			for ( const className of classList ) {
				preElement.classList.add( `language-${ className }` );
			}

			// Render as `javascript` on API pages and as `plaintext` for others if the language is not specified.
			if ( !preElement.classList.length ) {
				preElement.classList.add( isApiPage ? 'language-javascript' : 'language-plaintext' );
			}

			element.setAttribute( 'data-prismjs-copy-success', 'Ready!' );
			preElement.classList.add( 'highlight' );

			window.Prism.highlightElement( element );
		} );

	// Add the `[title]` attribute to "Copy" button.
	[ ...document.querySelectorAll( '.copy-to-clipboard-button' ) ]
		.forEach( button => {
			button.title = 'Copy the code to the clipboard';
		} );
}

/**
 * Add the "Download" button to the code snippets.
 */
function createDownloadButton() {
	window.Prism.plugins.toolbar.registerButton( 'download', env => {
		const button = document.createElement( 'button' );
		const span = document.createElement( 'span' );

		span.innerHTML = 'Download';
		button.appendChild( span );
		button.classList.add( 'download-snippet-button' );
		button.title = 'Download this snippet';

		button.addEventListener( 'click', () => {
			download( env.element.textContent, 'index.html', 'text/html' );
		} );

		return button;
	} );

	function download( data, filename, type ) {
		const file = new Blob( [ data ], { type } );

		if ( window.navigator.msSaveOrOpenBlob ) {
			// IE10+
			window.navigator.msSaveOrOpenBlob( file, filename );
		} else {
			// Others
			const a = document.createElement( 'a' );
			const url = URL.createObjectURL( file );

			a.href = url;
			a.download = filename;
			document.body.appendChild( a );

			a.click();
			setTimeout( function() {
				document.body.removeChild( a );
				window.URL.revokeObjectURL( url );
			} );
		}
	}
}
