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

'use strict';

const upath = require( 'upath' );

/**
 * Replaces @img tags with proper image tags.
 *
 * @example
 * {@img guides/images/1.png alt text} will be replaced with
 * <img src="../guides/images/1.png" data-lightbox="true" alt="alt text">
 * src may be different depending on page path as it's a relative path.
 */
hexo.extend.filter.register( 'after_post_render', page => {
	// jscs:disable
	const relativeUrlHelper = hexo.extend.helper.store.relative_url;
	// jscs:enable
	const regex = /{@img\s+([^}\s]+)(?:\s+(\d{2,}))?(?:\s+([^}]+))?}/g;
	const basePath = page.BASE_PATH;

	page.content = page.content.replace( regex, ( match, src, width, alt = '' ) => {
		const isExternalLink = src.startsWith( 'http' );
		let imgSrc = src;
		let imgWidth = '';

		if ( !isExternalLink ) {
			imgSrc = relativeUrlHelper( page.path, upath.join( basePath, src ) );
		}

		if ( width ) {
			imgWidth = ` width="${ width }"`;
		}

		return `<img src="${ imgSrc }" loading="lazy" decoding="async" data-lightbox="true" alt="${ alt }"${ imgWidth }>`;
	} );

	return page;
}, 40 );
