import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy, ViewEncapsulation } from '@angular/core';
import { CommonModule } from '@angular/common';

type AspectRatioPreset = 'square' | 'video' | 'cinema' | 'photo' | 'portrait' | 'golden';
type AspectRatioSize = 'sm' | 'md' | 'lg';
type AspectRatioVariant = 'default' | 'elevated' | 'bordered' | 'interactive';

@Component({
  selector: 'ui-aspect-ratio',
  standalone: true,
  imports: [CommonModule],
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  template: `
    <div 
      [ngClass]="getClasses()"
      [style.--aspect-ratio]="customRatio"
      [attr.role]="role"
      [tabindex]="interactive && !loading ? tabIndex : -1"
      (click)="handleClick($event)"
      (keydown)="handleKeydown($event)">
      
      <div class="ui-aspect-ratio__content" [class.ui-aspect-ratio__content--center]="centerContent">
        @if (loading) {
          <!-- Loading indicator is handled by CSS -->
        } @else {
          <ng-content></ng-content>
        }
      </div>
    </div>
  `,
  styleUrl: './aspect-ratio.component.scss'
})
export class AspectRatioComponent {
  @Input() ratio: AspectRatioPreset = 'video';
  @Input() customRatio?: string; // e.g., "4/3", "1.5", "75%"
  @Input() size: AspectRatioSize = 'md';
  @Input() variant: AspectRatioVariant = 'default';
  @Input() loading = false;
  @Input() centerContent = false;
  @Input() role?: string;
  @Input() tabIndex = 0;

  @Output() clicked = new EventEmitter<MouseEvent>();

  get interactive(): boolean {
    return this.variant === 'interactive';
  }

  getClasses(): Record<string, boolean> {
    const classes: Record<string, boolean> = {
      'ui-aspect-ratio': true,
      [`ui-aspect-ratio--${this.ratio}`]: !this.customRatio,
      [`ui-aspect-ratio--${this.size}`]: this.size !== 'md',
      'ui-aspect-ratio--loading': this.loading
    };

    if (this.variant !== 'default') {
      classes[`ui-aspect-ratio--${this.variant}`] = true;
    }

    return classes;
  }

  handleClick(event: MouseEvent): void {
    if (this.interactive && !this.loading) {
      this.clicked.emit(event);
    }
  }

  handleKeydown(event: KeyboardEvent): void {
    if (this.interactive && !this.loading && (event.key === 'Enter' || event.key === ' ')) {
      event.preventDefault();
      this.handleClick(event as any);
    }
  }
}