import {
  ChangeDetectionStrategy,
  Component,
  computed,
  forwardRef,
  inject,
  input,
  model,
} from '@angular/core';

import { AccordionComponent } from './accordion.component';

let nextAccordionItemId = 0;

@Component({
  selector: 'app-accordion-item',
  imports: [],
  templateUrl: './accordion-item.component.html',
  styleUrl: './accordion-item.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    class: 'accordion-item',
  },
})
export class AccordionItemComponent {
  private readonly accordion = inject(forwardRef(() => AccordionComponent));
  private readonly generatedId = `app-accordion-item-${nextAccordionItemId++}`;

  readonly title = input.required<string>();
  readonly id = input<string | null>(null);
  readonly disabled = input(false);
  readonly headingLevel = input(2);
  readonly open = model(false);

  protected readonly itemId = computed(() => this.id()?.trim() || this.generatedId);
  protected readonly triggerId = computed(() => `${this.itemId()}-trigger`);
  protected readonly panelId = computed(() => `${this.itemId()}-panel`);
  protected readonly normalizedHeadingLevel = computed(() =>
    Math.min(6, Math.max(1, Math.trunc(this.headingLevel()))),
  );

  protected toggle(): void {
    this.accordion.toggle(this);
  }
}
