/**
 * @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' );

/**
 * Make sure each page has a title.
 * Page can be imported so title might be added from other guide. That's why this filter should be fired after `import-guide.js`.
 */
hexo.extend.filter.register( 'after_post_render', page => {
	// If the `menu-title` is specified, do not extract anything from the page.
	if ( page[ 'menu-title' ] ) {
		page.title = page[ 'menu-title' ];

		return;
	}

	const $ = cheerio.load( page.content, null, false );
	const title = $( 'h1:not( .live-snippet h1 )' ).first();

	if ( !title.length && !page.title ) {
		console.error( `Document: ${ page.source } has no title and no h1 which could be used as a title.` );
	}

	if ( !page.title ) {
		page.title = title.children().remove().end().text().trim();
	}
}, 32 );
