(function () {
	'use strict';

	const STORAGE_KEY =
		'tutorhelperCalendarSidebarCollapsed';

    const settings =
	window.tutorhelperAdminCalendar || {};

    const sidebarSettings =
        settings.sidebar || {};

	/**
	 * Read the saved sidebar state.
	 *
	 * @returns {boolean}
	 */
	function getSavedState() {
		try {
			return window.localStorage.getItem(
				STORAGE_KEY
			) === '1';
		} catch (error) {
			return false;
		}
	}

	/**
	 * Save the sidebar state.
	 *
	 * @param {boolean} collapsed Whether the panel is collapsed.
	 */
	function saveState(collapsed) {
		try {
			window.localStorage.setItem(
				STORAGE_KEY,
				collapsed ? '1' : '0'
			);
		} catch (error) {
			/*
			 * Storage may be unavailable in private or restricted
			 * browser contexts. The toggle still works for the
			 * current page without persistence.
			 */
		}
	}

	/**
	 * Initialise the calendar sidebar toggle.
	 */
	function initialiseCalendarSidebar() {
		const layout = document.querySelector(
			'[data-calendar-layout]'
		);

		const sidebar = document.querySelector(
			'[data-calendar-sidebar]'
		);

		const button = document.querySelector(
			'[data-calendar-sidebar-toggle]'
		);

		if (
			!layout
			|| !sidebar
			|| !button
		) {
			return;
		}

		const label = button.querySelector(
			'[data-calendar-sidebar-toggle-label]'
		);

		/**
		 * Apply the selected state.
		 *
		 * @param {boolean} collapsed Whether to collapse the sidebar.
		 * @param {boolean} persist Whether to save the choice.
		 */
		function setCollapsed(
			collapsed,
			persist
		) {
			layout.classList.toggle(
				'is-sidebar-collapsed',
				collapsed
			);

			sidebar.hidden = collapsed;

			button.setAttribute(
				'aria-expanded',
				collapsed ? 'false' : 'true'
			);

			if (label) {
				label.textContent = collapsed
                ? (
                    sidebarSettings.showLabel
                    || 'Show side panel'
                )
                : (
                    sidebarSettings.hideLabel
                    || 'Hide side panel'
                );
			}

			if (persist) {
				saveState(collapsed);
			}
		}

		setCollapsed(
			getSavedState(),
			false
		);

		button.addEventListener(
			'click',
			function () {
				const collapsed =
					!layout.classList.contains(
						'is-sidebar-collapsed'
					);

				setCollapsed(
					collapsed,
					true
				);
			}
		);
	}

	if (document.readyState === 'loading') {
		document.addEventListener(
			'DOMContentLoaded',
			initialiseCalendarSidebar
		);
	} else {
		initialiseCalendarSidebar();
	}
}());
