import {
  Component,
  ChangeDetectionStrategy,
  Input,
  Output,
  EventEmitter,
  ElementRef,
  Renderer2,
  AfterViewInit,
  OnChanges,
  SimpleChanges,
} from '@angular/core';

@Component({
  selector: 'shell-section-toggle',
  templateUrl: 'section-toggle.component.html',
  styleUrls: ['section-toggle.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ShellSectionToggleComponent implements AfterViewInit, OnChanges {
  @Input()
  section: string = 'customer';

  @Input()
  sections: Array<{ label: string; key: string }> = [
    { label: 'Kunden', key: 'customer' },
    { label: 'Filiale', key: 'branch' },
  ];

  @Output()
  sectionChange = new EventEmitter<string>();

  constructor(private readonly _elementRef: ElementRef, private readonly _renderer: Renderer2) {}

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.section) {
      this.updateSwitchPositionAndSize();
    }
  }

  ngAfterViewInit(): void {
    this.updateSwitchPositionAndSize();
  }

  setSection(section: string) {
    if (this.section !== section) {
      this.section = section;
      this.sectionChange.emit(section);
    }
    this.updateSwitchPositionAndSize();
  }

  updateSwitchPositionAndSize() {
    const hostElement = this._elementRef?.nativeElement;
    const targetElement = hostElement?.querySelector(`button[section="${this.section}"]`);
    const switchElement = hostElement?.querySelector('.switch');

    if (!hostElement || !targetElement || !switchElement) {
      return;
    }

    const targetElementRect = targetElement.getBoundingClientRect();
    const targetElementLeft = targetElementRect.left;
    const targetElementWidth = targetElementRect.width;
    const hostElementLeft = hostElement.getBoundingClientRect().left;
    const left = targetElementLeft - hostElementLeft;
    this._renderer.setStyle(switchElement, 'left', `${left}px`);
    this._renderer.setStyle(switchElement, 'width', `${targetElementWidth}px`);
  }
}
