import { Controller } from '@hotwired/stimulus';

export default class extends Controller {

    connect() {
        console.log("Stimulus: contrôleur de planning actif");

        this.arrows = this.element.querySelectorAll('.period-controller');
        this.showAll = this.element.querySelector('[data-store]');
        this.containers = document.querySelectorAll('.period-panel');

        this.arrows.forEach(arrow => {
            arrow.addEventListener('click', (event) => {
                event.preventDefault();
                this.activatePanel(arrow);
            });
        });

        this.showAll.addEventListener('click', (event)=> {
            event.preventDefault();
            this.togglePanels();
        }) 
    }

    activatePanel(selectedPanel) {
        const targetId = selectedPanel.dataset.id;

        // Affichage du bon bloc
        this.containers.forEach(container => {
            if (container.id === targetId) {
                container.classList.remove('is-hidden');
                this.showAll.dataset.store = container.id;

            } else {
                container.classList.add('is-hidden');
            }
        });
    }

    togglePanels() {
        if (this.showAll.dataset.action == "show") {
            this.containers.forEach(container => {
                container.classList.remove('is-hidden');
            });
            this.showAll.dataset.action = "hide";
            this.showAll.innerHTML = 'Cacher les autres périodes';
            this.arrows.forEach(arrow => { console.log(arrow); arrow.classList.add('is-hidden') });
        } else {
            this.containers.forEach(container => {
                if (container.id === this.showAll.dataset.store) {
                    container.classList.remove('is-hidden');
                } else {
                    container.classList.add('is-hidden');
                }
                this.arrows.forEach(arrow => { arrow.classList.remove('is-hidden') });
            });
            this.showAll.dataset.action = "show";
            this.showAll.innerHTML = 'Afficher toutes les périodes à la suite';            
        }
        
    }
}