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

@Component({
  selector: 'workbench-tabs',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './workbench-tabs.component.html',
  styleUrl: './workbench-tabs.component.less',
})
export class WorkbenchTabsComponent {
  @ViewChild('tabsRef') tabsRef!: ElementRef<HTMLDivElement>;
  @Input() tabs: Option[] = [];
  @Input() activeTab: string | number = '';
  @Output() activeTabChange = new EventEmitter<string | number>();

  activeWidth = '0px'; // 48px
  activeOffsetLeft = '0px';

  ngAfterViewInit() {
    setTimeout(() => {
      this.handleChange(this.tabs.find(tab => tab.value === this.activeTab)!);
    }, 100);
  }
  handleChange(tab: Option) {
    this.activeTab = tab.value;
    this.activeTabChange.emit(tab.value);
    this.activeOffsetLeft = this.getActiveOffsetLeft() + 'px';
    this.activeWidth = this.getActiveWidth() + 'px';
  }

  findActiveTab() {
    const activeTab = this.tabsRef.nativeElement.querySelector(`[data-value="${this.activeTab}"]`) as HTMLSpanElement;
    return activeTab;
  }
  getActiveWidth() {
    const activeTab = this.findActiveTab();
    if (!activeTab) return 0;
    const width = activeTab.offsetWidth;
    if (width < 60) return 48;
    return width;
  }
  getActiveOffsetLeft() {
    const activeTab = this.findActiveTab();
    if (!activeTab) return 0;
    const offset = activeTab.offsetLeft;
    const width = activeTab.offsetWidth;
    if (width < 60) return offset + 6;
    return offset;
  }
}
