<template>
	<section :class="{'sidebar__section': true, 'section--collapsed': collapsed}">
		<button :id="`${name}-heading`" type="button" class="section__heading"
		        @click.prevent="toggle" @keydown="handleKeydown" :title="title"
		        :aria-expanded="!collapsed" :aria-controls="`${name}-content`">
			<slot name="heading"></slot>
		</button>
		<div :id="`${name}-content`" role="region" :aria-labelledby="`${name}-heading`" :aria-hidden="collapsed">
			<slot></slot>
		</div>
	</section>
</template>

<script lang="ts">
	import {useStore} from "@/store";
	import {LiveAtlasSidebarSection} from "@/index";
	import {defineComponent} from "@vue/runtime-core";

	export default defineComponent({
		name: 'CollapsibleSection',

		props: {
			name: {
				type: String as () => LiveAtlasSidebarSection,
				required: true,
			}
		},

		computed: {
			title(): string {
				return useStore().state.messages.toggleTitle;
			},

			collapsed(): boolean {
				return useStore().state.ui.collapsedSections.has(this.name);
			},
		},

		methods: {
			handleKeydown(e: KeyboardEvent) {
				if(e.key !== ' ' && e.key !== 'Enter') {
					return;
				}

				e.preventDefault();

				this.toggle();
			},

			toggle() {
				const store = useStore();

				if(this.collapsed) {
					store.state.ui.collapsedSections.delete(this.name);
				} else {
					store.state.ui.collapsedSections.add(this.name);
				}
			}
		}
	});
</script>
