import { Component, Input, OnInit, OnDestroy, OnChanges, SimpleChanges, ElementRef, inject, ChangeDetectionStrategy, ViewEncapsulation } from '@angular/core';
import { SolidBackgroundConfig } from '../../types/background.types';
import { BackgroundService } from '../../services/background.service';

@Component({
  selector: 'ui-solid-background',
  standalone: true,
  template: '<ng-content></ng-content>',
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  host: {
    'class': 'ui-background ui-background--solid'
  }
})
export class SolidBackgroundComponent implements OnInit, OnDestroy, OnChanges {
  private readonly elementRef = inject(ElementRef<HTMLElement>);
  private readonly backgroundService = inject(BackgroundService);
  private backgroundId?: string;

  @Input() color = '#000000';
  @Input() fullScreen = false;
  @Input() zIndex?: number;

  ngOnInit(): void {
    this.applyBackground();
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['color'] || changes['fullScreen'] || changes['zIndex']) {
      this.applyBackground();
    }
  }

  ngOnDestroy(): void {
    if (this.backgroundId) {
      this.backgroundService.removeBackground(this.backgroundId);
    }
  }

  private applyBackground(): void {
    if (this.backgroundId) {
      this.backgroundService.removeBackground(this.backgroundId);
    }

    const config: SolidBackgroundConfig = {
      type: 'solid',
      color: this.color
    };

    if (this.fullScreen) {
      this.backgroundId = this.backgroundService.applyFullScreenBackground(config, {
        zIndex: this.zIndex || -1
      });
    } else {
      this.backgroundId = this.backgroundService.applyBackground(
        this.elementRef.nativeElement,
        config
      );
    }
  }
}