import { Directive, Input, HostListener, inject, signal } from '@angular/core';

@Directive({
  selector: '[uiCopyButton]',
  standalone: true
})
export class CopyButtonDirective {
  @Input() uiCopyButton!: string;
  @Input() copySuccessMessage = 'Copied!';
  @Input() copyErrorMessage = 'Failed to copy';

  private copied = signal(false);
  private timeoutId: number | null = null;

  @HostListener('click', ['$event'])
  async onClick(event: Event): Promise<void> {
    event.preventDefault();
    event.stopPropagation();

    if (!this.uiCopyButton) {
      console.warn('No content provided to copy');
      return;
    }

    try {
      await this.copyToClipboard(this.uiCopyButton);
      this.showFeedback(true);
    } catch (error) {
      console.error('Failed to copy to clipboard:', error);
      this.showFeedback(false);
    }
  }

  private async copyToClipboard(text: string): Promise<void> {
    if (navigator.clipboard && window.isSecureContext) {
      // Use modern clipboard API
      await navigator.clipboard.writeText(text);
    } else {
      // Fallback for older browsers or non-secure contexts
      this.fallbackCopyToClipboard(text);
    }
  }

  private fallbackCopyToClipboard(text: string): void {
    const textArea = document.createElement('textarea');
    textArea.value = text;
    textArea.style.position = 'fixed';
    textArea.style.left = '-999999px';
    textArea.style.top = '-999999px';
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    
    try {
      document.execCommand('copy');
    } catch (error) {
      throw new Error('Fallback copy failed');
    } finally {
      document.body.removeChild(textArea);
    }
  }

  private showFeedback(success: boolean): void {
    this.copied.set(success);
    
    // Clear existing timeout
    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
    }
    
    // Reset after 2 seconds
    this.timeoutId = window.setTimeout(() => {
      this.copied.set(false);
      this.timeoutId = null;
    }, 2000);
  }

  get isCopied(): boolean {
    return this.copied();
  }
}