import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
    static targets = ['list', 'menu', 'icon'];

    toggleMenu() {
        this.menuTarget.classList.toggle('is-hidden');
    }

    close() {
        this.menuTarget.classList.add('is-hidden');
    }

    toggleList(id) {
        document.querySelector(`#${id}`).classList.toggle('is-hidden');
    }

    openSubList(event) {
        const target = event.currentTarget;
        const targetIcon = target.querySelector('.fa');
        const id = target.getAttribute('data-list-id');
        this.toggleList(id);
        this.toggleIcon(targetIcon);
    }

    toggle(event) {
        const target = event.currentTarget; 
        const targetIcon = target.querySelector('.fa');
        const id = target.getAttribute('data-id');
        const listId = `${id}-list`;
        const list = this.listTargets.find(t => t.id === listId);

        if (list) {
            list.classList.toggle('is-hidden');
        }

        this.toggleIcon(targetIcon);
    }

    toggleIcon(icon) {
        if (icon.classList.contains('fa-chevron-right')) {
            icon.classList.remove('fa-chevron-right');
            icon.classList.add('fa-chevron-down');
        } else {
            icon.classList.add('fa-chevron-right');
            icon.classList.remove('fa-chevron-down');
        }

        return icon;
    }
}
