import { Component, computed, input, output, signal } from '@angular/core';
import { BonusCardInfo } from '@isa/crm/data-access';
import { CarouselComponent } from '@isa/ui/carousel';
import { CustomerCardComponent } from '../customer-card';
import { CardStackContainerDirective } from './card-stack-container.directive';
import { CardStackDistanceDirective } from './card-stack-distance.directive';

/**
 * Carousel container for displaying multiple customer loyalty cards.
 *
 * Features:
 * - Horizontal scrolling with navigation arrows
 * - Blocked cards sorted to the end
 * - Gap spacing between cards
 * - Uses @isa/ui/carousel for smooth scrolling
 *
 * Based on Figma design with carousel navigation.
 *
 * @example
 * ```html
 * <customer-cards-carousel
 *   [cards]="bonusCards"
 *   (unblockCard)="handleUnblock($event)" />
 * ```
 */
@Component({
  selector: 'crm-customer-cards-carousel',
  imports: [
    CarouselComponent,
    CustomerCardComponent,
    CardStackDistanceDirective,
    CardStackContainerDirective,
  ],
  templateUrl: './customer-cards-carousel.component.html',
  styleUrl: './customer-cards-carousel.component.css',
  host: {
    '(click)': 'unStack()',
  },
})
export class CustomerCardsCarouselComponent {
  #stacked = signal(true);

  /**
   * All bonus cards to display in carousel.
   */
  readonly cards = input.required<BonusCardInfo[]>();

  stacked = computed(() => {
    const cards = this.cards();
    const stacked = this.#stacked();

    return stacked && cards.length > 1;
  });

  /**
   * True when there is exactly one card - disables carousel scrolling.
   */
  readonly singleCard = computed(() => this.cards().length === 1);

  /**
   * Event emitted when a card has been successfully locked or unlocked.
   * Parent should reload cards and transactions.
   */
  readonly cardLocked = output<void>();

  /**
   * Cards sorted by priority: isPrimary > isActive > code
   * Per Figma annotation: "gesperrte Karte immer nach hinten"
   */
  readonly sortedCards = computed(() => {
    const cards = this.cards();
    return [...cards].sort((a, b) => {
      // 1. Primary cards first
      if (a.isPrimary !== b.isPrimary) {
        return a.isPrimary ? -1 : 1;
      }

      // 2. Active cards before blocked cards
      if (a.isActive !== b.isActive) {
        return a.isActive ? -1 : 1;
      }

      // 3. Sort by code for stable ordering
      return a.code.localeCompare(b.code);
    });
  });

  unStack(): void {
    this.#stacked.set(false);
  }
}
