<template>
	<ul :class="accordionClass">
		<slot></slot>
	</ul>
</template>

<script>
export default {
	props: {
		name: {
			type: String,
			default: "default",
		},
		type: {
			type: String,
			default: "default",
		},
	},
	data() {
		return {
			Accordion: {
				count: 0,
				name: this.name,
			},
			expandedIndex: null,
			activeIndex: null,
		};
	},
	provide() {
		return { Accordion: this.Accordion, watchAccordion: this.watchAccordion };
	},
	computed: {
		/**
		 * Get notice classes based of different conditions.
		 *
		 * @since 3.0.0
		 *
		 * @return {*}
		 */
		accordionClass() {
			return {
				"wcc-app-accordion": true,
				"wcc-app-accordion-boxed": this.type === "boxed",
			};
		},
	},
	methods: {
		watchAccordion(value) {
			this.expandedIndex = value;
			if (!this.isExpanded()) {
				this.closeAccordion(); /** Close previously opened accordions */
				this.expandAccordion();
			} else {
				this.closeAccordion();
			}
		},
		hideAccordion(element) {
			const content = element.querySelector(".wcc-app-accordion-content");
			if (!content) return;
			content.style.height = content.scrollHeight + "px";
			window.setTimeout(function () {
				content.style.height = "0";
				content.style.overflow = "hidden";
			}, 1);
			window.setTimeout(function () {
				element.classList.remove("wcc-app-accordion-open");
			}, 200);
		},
		expandAccordion() {
			const accordions = this.getActiveAccordions();
			accordions.forEach((element) => {
				if (element) {
					const content = element.querySelector(".wcc-app-accordion-content");
					if (!content) return;
					const height = this.getElementHeight(content);
					element.classList.add("wcc-app-accordion-open");
					content.style.height = height;
					window.setTimeout(function () {
						content.style.height = "";
						content.style.overflow = "visible";
					}, 200);
				}
			});
			this.activeIndex = this.expandedIndex;
		},
		getElementHeight(element) {
			element.style.display = "block"; // Make it visible
			const height = element.scrollHeight + "px"; // Get it's height
			element.style.display = ""; //  Hide it again
			return height;
		},
		getActiveAccordions() {
			return document.querySelectorAll(
				`[data-wcc-toggle="wcc-${this.name}-accordion-${this.expandedIndex}"]`
			);
		},
		isExpanded() {
			return this.expandedIndex === this.activeIndex;
		},
		closeAccordion() {
			if( this.activeIndex === null ) return;
			document
				.querySelectorAll(
					`.wcc-app-accordion-open[data-wcc-toggle="wcc-${this.name}-accordion-${this.activeIndex}"]`
				)
				.forEach((item) => {
					if (!item) return;
					this.hideAccordion(item);
				});
			this.activeIndex = null;
		},
	},
};
</script>