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

'use strict';

const cheerio = require( 'cheerio' );

const regexp = /(?<=>)utf8_encoded_content:([0-9,]+)(?=<\/code><\/pre>)/g;
const textDecoder = new TextDecoder();

/**
 * Fixes some codeblocks issues.
 */
hexo.extend.filter.register( 'after_post_render', page => {
	// Decoding codeblocks inside infobox from UTF-8. See #1122.
	if ( regexp.test( page.content ) ) {
		page.content = page.content.replace( regexp, ( match, encodedContent ) => {
			const decodedContent = textDecoder.decode( new Uint8Array( encodedContent.split( ',' ) ) );

			return decodedContent.replace( /^\n/, '' );
		} );
	}

	const $ = cheerio.load( page.content, null, false );

	// This is an attempt to automatically discover code blocks of HTML and add 'html' class if needed.
	// It is needed for triple backtick ``` codeblocks in markdown which contain HTML but don't use ```html notation.
	if ( page.content.indexOf( '<pre' ) !== -1 ) {
		$( 'pre' ).each( function() {
			const codeEl = $( this ).find( 'code' );

			if ( codeEl.is( '.html,.js,.php,.css,.java' ) ) {
				return true;
			}

			const codeContent = codeEl.html();
			const matches = codeContent ? codeContent.match( /(?:<|&lt;)\/?[a-z]+?(?:&gt;|>)/g ) : null;

			if ( matches && matches.length >= 2 ) {
				codeEl.addClass( 'html' );
			}

			$( this ).replaceWith( $( this ).toString().replace( /\t/g, '    ' ) );
		} );
	}

	page.content = $.html();
} );
