import { Controller } from "stimulus"

export default class extends Controller {

	static targets = ["quote", "buttons", "button", "noButtons"]

	initialize() {
		function template(index) {
			return `<button class="appearance-none h-3 w-3 border-2 border-white rounded-full mr-4 quote-button focus:outline-none" data-action="click->quotes#selectSlide" data-quote-index="${index}" data-target="quotes.button"></button>`
		}

		let buttonsHtml = ''

		if (this.quoteTargets.length == 1) {
			this.buttonsTarget.classList.add("hidden");
			this.noButtonsTarget.classList.remove("hidden");
		}

		this.quoteTargets.forEach((el, i) => {
			buttonsHtml += template(i)
		})

		this.buttonsTarget.innerHTML = buttonsHtml

		this.showCurrentQuote()
	}

	selectSlide() {
		const element = event.target
		this.data.set("index", element.dataset.quoteIndex)
		this.showCurrentQuote()
	}

	showCurrentQuote() {
		this.quoteTargets.forEach((el, i) => {
			el.classList.toggle("quote-active", this.index == i)
		})
		this.buttonTargets.forEach((el, i) => {
			el.classList.toggle("bg-white", this.index == i)
		})
	}

	get index() {
		return parseInt(this.data.get("index"))
	}

	set index(value) {
		this.data.set("index", value)
		this.showCurrentQuote()
	}
}