import { Component, Input, computed, signal, ChangeDetectionStrategy, ViewEncapsulation, OnInit, OnChanges, SimpleChanges } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SyntaxHighlighterService } from '../../services/syntax-highlighter.service';
import { CodeThemeService, CodeTheme } from '../../services/theme.service';
import { CopyButtonDirective } from '../../directives/copy-button.directive';

export type InlineCodeSize = 'xs' | 'sm' | 'md' | 'lg';

@Component({
  selector: 'ui-inline-code',
  standalone: true,
  imports: [CommonModule, CopyButtonDirective],
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  template: `
    <span [class]="containerClasses()">
      <code 
        [class]="codeClasses()"
        [innerHTML]="highlightedCode()">
      </code>
      
      @if (copyable) {
        <button 
          type="button"
          class="inline-code__copy-btn"
          [uiCopyButton]="code"
          [attr.aria-label]="'Copy code to clipboard'"
          title="Copy code">
          <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
            <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/>
          </svg>
        </button>
      }
    </span>
  `,
  styleUrl: './inline-code.component.scss'
})
export class InlineCodeComponent implements OnInit, OnChanges {
  @Input() code = '';
  @Input() language = '';
  @Input() theme: CodeTheme | null = null;
  @Input() size: InlineCodeSize = 'md';
  @Input() copyable = false;

  constructor(
    private syntaxHighlighter: SyntaxHighlighterService,
    private themeService: CodeThemeService
  ) {}

  readonly finalLanguage = computed(() => {
    if (this.language) {
      return this.language;
    }
    // For inline code, we're more conservative with auto-detection
    return 'text';
  });

  readonly highlightedCode = signal('');

  private async updateHighlightedCode() {
    if (!this.code) {
      this.highlightedCode.set('');
      return;
    }
    
    const lang = this.finalLanguage();
    if (lang === 'text') {
      this.highlightedCode.set(this.escapeHtml(this.code));
      return;
    }
    
    try {
      const highlighted = await this.syntaxHighlighter.highlight(this.code, {
        language: lang
      });
      this.highlightedCode.set(highlighted);
    } catch (error) {
      console.warn('Failed to highlight code:', error);
      this.highlightedCode.set(this.escapeHtml(this.code));
    }
  }

  readonly currentTheme = computed(() => {
    return this.theme || this.themeService.theme();
  });

  readonly containerClasses = computed(() => {
    const classes = ['inline-code'];
    classes.push(`inline-code--${this.size}`);
    classes.push(`code-theme-${this.currentTheme()}`);
    
    if (this.copyable) classes.push('inline-code--copyable');
    
    return classes.join(' ');
  });

  readonly codeClasses = computed(() => {
    const classes = ['inline-code__code'];
    classes.push(`language-${this.finalLanguage()}`);
    return classes.join(' ');
  });

  ngOnInit(): void {
    this.updateHighlightedCode();
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['code'] || changes['language']) {
      this.updateHighlightedCode();
    }
  }

  private escapeHtml(text: string): string {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }
}