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

'use strict';

hexo.extend.helper.register( 'markEmptyCategories', ( () => {
	const pagesCategories = new Set();

	return ( ( { pages, categories, projectName, group } = {} ) => {
		function markEmptyCategories( categoryObj ) {
			if ( categoryObj.hasDescendentLeaf === undefined ) {
				if ( !categoryObj.categories ) {
					categoryObj.hasDescendentLeaf = pagesCategories.has( `${ projectName }|${ group }|${ categoryObj.id }` );
				} else {
					if ( categoryObj.categories.filter( item => item.hasDescendentLeaf ).length ) {
						categoryObj.hasDescendentLeaf = true;
					} else {
						categoryObj.categories.forEach( category => markEmptyCategories( category ) );
						categoryObj.hasDescendentLeaf = !!categoryObj.categories.filter( item => item.hasDescendentLeaf ).length;
					}
				}
			}
		}

		if ( !pagesCategories.size ) {
			pages.data.forEach( itm => {
				pagesCategories.add( `${ itm.projectName || 'empty' }|${ itm.groupId || 'empty' }|${ itm.category }` );
			} );
		}

		categories.forEach( category => markEmptyCategories( category ) );
		return categories;
	} );
} )() );

