/**
 * @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 createPrerenderPugTemplate = require( '../../../utils/pug-renderer/create-prerender-pug-template' );

/**
 * Components to be processed after markdown rendering
 */
const POST_RENDER_COMPONENTS = [
	{
		fastCheck: str => str.includes( '<pre' ) && str.includes( 'highlight' ),
		selector: 'pre.highlight',
		handler: ( () => {
			const template = createPrerenderPugTemplate( {
				hexo,
				requires: [
					'_components/svg/index',
					'_components/icon/index',
					'_components/tooltip-popover/index',
					'_components/skeleton/index',
					'_components/code-block/index'
				],
				skipCacheIf: ( { code } ) => code?.split( '\n' ).length > 1,
				component: 'code-block',
				componentAttrs: {
					static: {
						copyable: true
					},
					dynamic: [ 'copyable', 'language' ],
					mask: [ 'code' ]
				}
			} );

			return $element => {
				const $code = $element.find( 'code' );

				if ( !$code.length ) {
					return null;
				}

				// Get the language from the class (e.g., "language-js" -> "js")
				const language = $code.attr( 'class' ).replace( 'doc', '' ).trim();

				return template( {
					code: $code.html(),
					language
				} );
			};
		} )()
	}
];

hexo.extend.filter.register( 'after_post_render', page => {
	if ( page.projectTheme !== 'gloria' || !page.content ) {
		return page;
	}

	try {
		let $ = null;
		let hasChanges = false;

		POST_RENDER_COMPONENTS.forEach( component => {
			if ( component.fastCheck && !component.fastCheck( page.content ) ) {
				return;
			}

			$ = $ || cheerio.load( page.content );

			$( component.selector ).each( ( i, element ) => {
				const $element = $( element );
				const replacement = component.handler( $element, { hexo, page } );

				if ( replacement ) {
					$element.replaceWith( replacement );
					hasChanges = true;
				}
			} );
		} );

		if ( hasChanges ) {
			page.content = $.html();
		}
	} catch ( error ) {
		console.error( error );
		throw error;
	}

	return page;
} );
