/**
 * @license
 * Copyright 2019 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */

import {LitElement, html, css, unsafeCSS, PropertyValueMap} from 'lit';
import {customElement, property} from 'lit/decorators.js';
import { breakpoints } from '../../breakpoints';

@customElement('iu-accordion-group')

export class AccordionGroup extends LitElement {
    static override styles = css`
        ::slotted(*:last-child){
            --iu-accordion-border-color-b: var(--iu-color-grey-200);
        }
        :host(.columns-2) .inner{
            display: grid;
            grid-template-columns: repeat(2,1fr);
            column-gap: var(--iu-grid-gutter);
        }
    `;

    @property({ type: String }) mode: 'single' | 'multiple' = 'single'; 
    @property({ type: Boolean, reflect: true}) columns : boolean = false;
    @property({ type: Array }) openAccordions: number[] = []; 

    override firstUpdated() {
        super.firstUpdated();

        if(this.columns){
            this.classList.add('columns-2');
        }

        this.querySelectorAll('iu-accordion').forEach((accordion, index) => {
            accordion.index = index;
            accordion.controlled = true;
        });      
    }

    private handleAccordionToggle(event: CustomEvent<{ index: number }>) {
        const { index } = event.detail;
        // console.log(index)
        if (this.mode === 'single') {
            // Single mode: Only one accordion open
            this.openAccordions = this.openAccordions.includes(index) ? [] : [index];
            // console.log(this.openAccordions)
        } else if (this.mode === 'multiple') {
          // Multiple mode: Toggle the clicked accordion
          if (this.openAccordions.includes(index)) {
            this.openAccordions = this.openAccordions.filter((i) => i !== index);
          } else {
            this.openAccordions = [...this.openAccordions, index];
          }
        }
    
        // Update the `isOpen` state of all child accordions
        this.updateAccordionStates();
    }

    private updateAccordionStates() {
        this.querySelectorAll('iu-accordion').forEach((accordion, index) => {
            const isOpen = this.openAccordions.includes(index);
            (accordion as any).isOpen = isOpen;
        });
    }

    override render() {
        return html`
            <iu-container>
                <div class="inner">
                    <slot @iu-toggle-accordion=${this.handleAccordionToggle}></slot>
                </div>
            </iu-container>
        `;
    }

}

declare global {
  interface HTMLElementTagNameMap {
    'iu-accordion-group': AccordionGroup;
  }
}