import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { faChevronRight } from '@fortawesome/free-solid-svg-icons';

export interface BreadcrumbItem {
  label: string;
  route?: string;
  disabled?: boolean;
}

@Component({
  selector: 'ui-breadcrumb',
  standalone: true,
  imports: [CommonModule, FontAwesomeModule],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <nav [class]="wrapperClasses" aria-label="breadcrumb">
      <ol class="breadcrumb-list">
        @for (item of items; track $index; let isLast = $last) {
          <li [class]="getItemClasses($index, isLast)">
            @if (!isLast && item.route && !item.disabled) {
              <a 
                class="breadcrumb-link"
                [href]="item.route"
                (click)="onItemClick($event, item, $index)"
              >
                {{ item.label }}
              </a>
            } @else {
              <span [class]="getLabelClasses(isLast, item.disabled)">
                {{ item.label }}
              </span>
            }
            
            @if (!isLast) {
              <fa-icon 
                class="breadcrumb-separator" 
                [icon]="separatorIcon"
              />
            }
          </li>
        }
      </ol>
    </nav>
  `,
  styleUrl: './breadcrumb.component.scss'
})
export class BreadcrumbComponent {
  @Input() items: BreadcrumbItem[] = [];
  @Input() separator: 'chevron' | 'slash' = 'chevron';

  @Output() itemClick = new EventEmitter<{item: BreadcrumbItem, index: number}>();

  separatorIcon = faChevronRight;

  get wrapperClasses(): string {
    return [
      'ui-breadcrumb'
    ].filter(Boolean).join(' ');
  }

  getItemClasses(index: number, isLast: boolean): string {
    return [
      'breadcrumb-item',
      isLast ? 'breadcrumb-item--current' : ''
    ].filter(Boolean).join(' ');
  }

  getLabelClasses(isLast: boolean, disabled?: boolean): string {
    return [
      'breadcrumb-label',
      isLast ? 'breadcrumb-label--current' : '',
      disabled ? 'breadcrumb-label--disabled' : ''
    ].filter(Boolean).join(' ');
  }

  onItemClick(event: Event, item: BreadcrumbItem, index: number): void {
    event.preventDefault();
    if (!item.disabled) {
      this.itemClick.emit({ item, index });
    }
  }
}