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

import { BaseComponent } from './base-component';
import { toggleHeight } from '../helpers/toggle-height';

// .js-api-collapsing-button

export class ApiToggle extends BaseComponent {
	/**
	 * Creates a API toggle component.
	 *
	 * @param element - The toggle button.
	 */
	constructor( element ) {
		super();

		this.elements = {
			toggleButton: element
		};
	}

	/**
	 * Initializes API toggle component on the page.
	 */
	static attach() {
		const toggleButtons = document.querySelectorAll( '.js-api-collapsing-button' );

		toggleButtons.forEach( button => {
			new ApiToggle( button ).init();
		} );

		ApiToggle.expandWhereYouAre();
	}

	/**
	 * Expands the error item if the hash in the URL matches an error id.
	 * This is a static utility for the whole API/error list, not for a single instance.
	 */
	static expandWhereYouAre() {
		if ( window.location.hash ) {
			const hash = window.location.hash.slice( 1 );
			const target = document.getElementById( hash );

			if ( target && target.classList.contains( 'js-api-collapsing-button' ) ) {
				const parent = target.parentElement;
				const descriptionElement = parent.querySelector( '.collapsing-list__description' );

				if ( descriptionElement && !parent.classList.contains( 'collapsing-list__item--open' ) ) {
					toggleHeight( descriptionElement, 'collapsing-list__description--open' ).then( () => {
						descriptionElement.setAttribute( 'aria-hidden', 'false' );
						target.setAttribute( 'aria-expanded', 'true' );
						parent.classList.add( 'collapsing-list__item--open' );
					} );
				}
			}
		}
	}

	/**
	 * Initializes the API toggle component with event listeners.
	 */
	init() {
		const { toggleButton } = this.elements;

		toggleButton?.addEventListener( 'click', async () => {
			const parent = toggleButton.parentElement;
			const descriptionElement = parent.querySelector( '.collapsing-list__description' );

			if ( !descriptionElement ) {
				return;
			}

			const toggleState = await toggleHeight( descriptionElement, 'collapsing-list__description--open' );
			const isExpanded = toggleState === 'visible';

			// Update ARIA attributes for accessibility
			descriptionElement.setAttribute( 'aria-hidden', !isExpanded );
			toggleButton.setAttribute( 'aria-expanded', isExpanded );

			parent.classList.toggle( 'collapsing-list__item--open' );
		} );

		this.render();
	}

	render() {
		// No specific rendering logic for the navigation tree component.
	}
}
