import {AfterViewInit, Component, ElementRef, inject, input, OnDestroy, OnInit, Renderer2} from '@angular/core';
import {FooterService} from '@services/footer.service';

@Component({
  selector: 'app-full-size',
  standalone: true,
  imports: [],
  templateUrl: './full-size.component.html',
  styleUrl: './full-size.component.scss'
})
export class FullSizeComponent implements OnInit, AfterViewInit, OnDestroy {
  private resizeObserver: ResizeObserver | null = null;
  private boundHandleResize: any;

  // Optional extra offset in pixels to subtract from available height
  extraOffset = input<number>(0);
  hideFooter = input<boolean>(false);

  private readonly elementRef = inject(ElementRef);
  private readonly renderer = inject(Renderer2);
  private readonly footerService = inject(FooterService);

  ngOnInit(): void {
    this.footerService.hideFooter.set(this.hideFooter());
  }

  ngAfterViewInit(): void {
    this.setupResizeObserver();
    this.updateContainerHeight();

    this.boundHandleResize = this.handleResize.bind(this);
    window.addEventListener('resize', this.boundHandleResize);

    // Ensure first paint sets correct height
    setTimeout(() => this.updateContainerHeight(), 0);
  }

  ngOnDestroy(): void {
    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
      this.resizeObserver = null;
    }

    if (this.boundHandleResize) {
      window.removeEventListener('resize', this.boundHandleResize);
    }

    this.footerService.hideFooter.set(false);
  }

  private handleResize() {
    this.updateContainerHeight();
  }

  private setupResizeObserver() {
    this.resizeObserver = new ResizeObserver(() => {
      this.updateContainerHeight();
    });

    const headerElement = document.querySelector('app-header');
    if (headerElement) {
      this.resizeObserver.observe(headerElement);
    }

    const footerElement = document.querySelector('footer');
    if (footerElement) {
      this.resizeObserver.observe(footerElement);
    }
  }

  private updateContainerHeight() {
    const headerElement = document.querySelector('app-header');
    const footerElement = document.querySelector('footer');

    const container: HTMLElement | null = this.elementRef.nativeElement.querySelector('.full-size-container');

    if (container) {
      const headerHeight = headerElement ? headerElement.getBoundingClientRect().height : 0;
      const footerHeight = this.hideFooter() ? 0 : (footerElement ? footerElement.getBoundingClientRect().height : 0);

      const totalOffset = headerHeight + footerHeight + (this.extraOffset() || 0);
      const calculatedHeight = `calc(100vh - ${totalOffset}px)`;
      this.renderer.setStyle(container, 'height', calculatedHeight);
    }
  }
}
