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

'use strict';

const path = require( 'path' );
const hexoManager = require( '../../../src/hexo-manager' );

/**
 * Renders a Pug component with specified includes and parameters.
 *
 * @param options - The rendering options.
 * @param options.hexo - The Hexo instance.
 * @param options.mixinContextVars - Context variables to be passed to the Pug mixin.
 * @param [options.requires=[]] - Array of Pug includes to be added at the top of the template.
 * @param options.component - The name of the component to render (without the + prefix).
 * @param [options.componentAttrs={}] - Attributes to pass to the component.
 * @param [options.basePath] - Base path for the component. Defaults to theme components directory.
 * @returns The rendered HTML.
 */
module.exports = function renderPugComponent(
	{
		hexo,
		mixinContextVars = {},
		requires = [],
		component,
		componentAttrs = {},
		basePath
	}
) {
	const { children, ...restComponentAttrs } = componentAttrs || {};

	// Default base path is the components directory in the theme
	// Handle case where hexo.theme_dir might be undefined
	const resolvedHexo = hexo || hexoManager.hexo;
	const themeDir = resolvedHexo && resolvedHexo.theme_dir || path.join( __dirname, '../../themes/umberto' );
	const componentsPath = basePath || path.join( themeDir, 'layout', 'gloria', '_components' );

	// Prepare includes statements
	const includeStatements = requires.map( include => `include ${ include }` );

	// Prepare the component call with its attributes
	const componentCall = `+${ component }(${ JSON.stringify( restComponentAttrs ) })`;

	// Complete content to be rendered
	const content = [
		...includeStatements,
		componentCall,
		children
	]
		.filter( Boolean )
		.join( '\n' );

	// Prepare locals for rendering
	const locals = Object.assign(
		{},
		resolvedHexo.locals.toObject(),
		resolvedHexo.extend.helper.list(),
		{
			...mixinContextVars,
			config: resolvedHexo.config
		}
	);

	// Render and return the component
	return resolvedHexo.render.renderSync( {
		text: content,
		engine: 'pug',
		path: componentsPath
	}, locals );
};
