import { AfterContentInit, ChangeDetectionStrategy, Component, ElementRef, Renderer2 } from '@angular/core';

@Component({
  selector: 'shared-scale-content, [sharedScaleContent]',
  template: '<ng-content></ng-content>',
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
  styles: [
    `
      :host {
        overflow-y: hidden;
      }
    `,
  ],
})
export class ScaleContentComponent implements AfterContentInit {
  // TODO: Bessere Lösung finden? Falls keine bessere Lösung gefunden wird, dann muss die Komponente auslagen

  fontSizeInEm = 1;

  adjustmentSteps = 0.05;

  constructor(
    private _elementRef: ElementRef<HTMLElement>,
    private _renderer: Renderer2,
  ) {}

  ngAfterContentInit(): void {
    this.adjustFontSize();
  }

  adjustFontSize() {
    const element = this._elementRef.nativeElement;

    const clientRect = element?.getClientRects();
    const scrollHeight = element?.scrollHeight;

    const domRect = clientRect && clientRect[0];

    if (domRect && Math.ceil(domRect?.height) < scrollHeight) {
      this.fontSizeInEm -= this.adjustmentSteps;
    } else {
      return;
    }

    this._renderer.setStyle(element, 'font-size', `${this.fontSizeInEm}em`);

    setTimeout(() => this.adjustFontSize(), 1);
  }
}
