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

import { BaseComponent } from './base-component';

/**
 * Component for managing expandable/collapsible content sections.
 * Tracks expanded state and manages accessibility attributes.
 */
export class Expandable extends BaseComponent {
	/**
	 * Creates an expandable component.
	 *
	 * @param element - The expandable component wrapper element
	 */
	constructor( element ) {
		super( {
			expanded: false
		} );

		const trigger = element.querySelector( '[aria-controls]' );
		const contentId = trigger.getAttribute( 'aria-controls' );
		const content = document.getElementById( contentId );

		this.elements = {
			wrapper: element,
			trigger,
			content
		};
	}

	/**
	 * Creates expandable components for all matching elements on the page.
	 */
	static attach() {
		const expandableElements = document.querySelectorAll( '.js-expandable' );

		for ( const element of expandableElements ) {
			new Expandable( element ).init();
		}
	}

	/**
	 * Initializes the expandable component.
	 * Sets up event listeners for the trigger element.
	 */
	init() {
		const { trigger } = this.elements;

		// Add click handler to toggle expanded state
		trigger.addEventListener( 'click', () => {
			this.setState( { expanded: !this.state.expanded } );
		} );

		// Initialize ARIA attributes based on initial state
		this.render();
	}

	/**
	 * Renders the component based on current state.
	 * Updates the visibility and accessibility attributes.
	 *
	 * @param prevState - Previous component state
	 * @param state - Current component state
	 */
	render( prevState, state = this.state ) {
		const { trigger, content } = this.elements;
		const { expanded } = state;

		// Update ARIA attributes for accessibility
		content.setAttribute( 'aria-hidden', !expanded );
		trigger.setAttribute( 'aria-expanded', expanded );

		// Toggle a visual class for styling
		content.classList.toggle( 'is-expanded', expanded );
	}
}
