import { ChangeDetectionStrategy, Component, ElementRef, ViewChild, computed, input, output, signal } from '@angular/core';
import { renderHighlighted, tokenizeCss, tokenizeHtml } from './code-highlight';

export type CodeEditorLanguage = 'html' | 'css';

@Component({
  selector: 'app-code-editor',
  standalone: true,
  templateUrl: './code-editor.component.html',
  styleUrl: './code-editor.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CodeEditorComponent {
  readonly value = input('');
  readonly language = input<CodeEditorLanguage>('html');
  readonly rows = input(10);
  readonly invalid = input(false);

  readonly valueChange = output<string>();

  @ViewChild('textarea', { static: true }) private textarea!: ElementRef<HTMLTextAreaElement>;
  @ViewChild('highlightLayer', { static: true }) private highlightLayer!: ElementRef<HTMLElement>;

  protected readonly highlighted = computed(() => {
    const tokens = this.language() === 'css' ? tokenizeCss(this.value()) : tokenizeHtml(this.value());
    return renderHighlighted(tokens) + '\n';
  });

  protected readonly focused = signal(false);

  protected onInput(event: Event): void {
    this.valueChange.emit((event.target as HTMLTextAreaElement).value);
  }

  protected syncScroll(): void {
    this.highlightLayer.nativeElement.scrollTop = this.textarea.nativeElement.scrollTop;
    this.highlightLayer.nativeElement.scrollLeft = this.textarea.nativeElement.scrollLeft;
  }
}
