import { Component, inject, ApplicationRef } from '@angular/core';
import { SwUpdate, VersionReadyEvent } from '@angular/service-worker';
import { filter, first } from 'rxjs/operators';
import { concat, interval, fromEvent } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss'],
  standalone: false,
})
export class AppComponent {
  private swUpdate = inject(SwUpdate);
  private appRef = inject(ApplicationRef);

  constructor() {
    this.setupUpdates();
  }

  private setupUpdates() {
    if (this.swUpdate.isEnabled) {
      // Wait for the application to stabilize before running update checks or starting intervals
      this.appRef.isStable.pipe(
        filter(stable => stable),
        first()
      ).subscribe(() => {
        console.log('[PWA-Update] App is stable. Initializing update checks...');
        
        // 1. Check for updates immediately
        this.swUpdate.checkForUpdate().catch(err => {
          console.warn('[PWA-Update] Failed immediate startup update check:', err);
        });

        // 2. Periodic check in background every 30 seconds
        const every30Seconds$ = interval(30 * 1000);
        every30Seconds$.subscribe(async () => {
          console.log('[PWA-Update] Periodic check for updates (every 30s)...');
          try {
            await this.swUpdate.checkForUpdate();
          } catch (err) {
            console.warn('[PWA-Update] Failed periodic update check:', err);
          }
        });
      });

      // 3. Check for updates when the app is resumed/focused
      fromEvent(document, 'visibilitychange')
        .pipe(filter(() => document.visibilityState === 'visible'))
        .subscribe(async () => {
          console.log('[PWA-Update] App resumed, checking for PWA updates...');
          try {
            await this.swUpdate.checkForUpdate();
          } catch (err) {
            console.warn('[PWA-Update] Failed visible resume update check:', err);
          }
        });

      // 4. Activate update and reload when a new version is ready
      this.swUpdate.versionUpdates
        .pipe(filter((evt): evt is VersionReadyEvent => evt.type === 'VERSION_READY'))
        .subscribe(() => {
          console.log('[PWA-Update] New version ready! Activating and reloading...');
          this.swUpdate.activateUpdate().then(() => {
            window.location.reload();
          });
        });
    }
  }
}
