import {
  ChangeDetectionStrategy,
  Component,
  contentChildren,
  effect,
  input,
} from '@angular/core';

import { AccordionItemComponent } from './accordion-item.component';

@Component({
  selector: 'app-accordion',
  imports: [],
  templateUrl: './accordion.component.html',
  styleUrl: './accordion.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AccordionComponent {
  readonly allowMultiple = input(false);
  readonly flush = input(false);

  private readonly items = contentChildren(AccordionItemComponent);

  constructor() {
    effect(() => {
      const items = this.items();

      if (this.allowMultiple()) {
        return;
      }

      const firstOpenItem = items.find((item) => item.open());

      for (const item of items) {
        if (item !== firstOpenItem && item.open()) {
          item.open.set(false);
        }
      }
    });
  }

  toggle(itemToToggle: AccordionItemComponent): void {
    if (itemToToggle.disabled()) {
      return;
    }

    const shouldOpen = !itemToToggle.open();

    if (shouldOpen && !this.allowMultiple()) {
      for (const item of this.items()) {
        if (item !== itemToToggle) {
          item.open.set(false);
        }
      }
    }

    itemToToggle.open.set(shouldOpen);
  }
}
