import { Injectable, signal } from '@angular/core';
import { ConfirmationService } from 'primeng/api';

@Injectable({ providedIn: 'root' })
export class PwaInstallService {
  private deferredInstallPrompt: any = null;
  readonly isInstalled = signal(false);
  readonly canInstall = signal(false);

  constructor(private readonly confirmationService: ConfirmationService) {
    this.init();
  }

  init() {
    if (typeof window === 'undefined') {
      return;
    }

    const standalone =
      window.matchMedia('(display-mode: standalone)').matches ||
      (window.navigator as any).standalone === true;

    this.isInstalled.set(standalone);

    window.addEventListener('beforeinstallprompt', (event: any) => {
      event.preventDefault();

      this.deferredInstallPrompt = event;
      this.canInstall.set(true);
    });

    window.addEventListener('appinstalled', () => {
      this.deferredInstallPrompt = null;
      this.canInstall.set(false);
      this.isInstalled.set(true);
    });
  }

  openInstallConfirm() {
    if (this.isInstalled() || !this.canInstall() || !this.deferredInstallPrompt) {
      return;
    }

    this.confirmationService.confirm({
      header: 'نصب اپلیکیشن',
      message: 'برای ادامه می‌بایست نیازمندی‌های نرم‌افزار را نصب کنید',
      acceptLabel: 'نصب',
      rejectButtonProps: {
        outlined: true,
      },
      accept: () => {
        this.deferredInstallPrompt.prompt();
        this.deferredInstallPrompt.userChoice.finally(() => {
          this.deferredInstallPrompt = null;
          this.canInstall.set(false);
          window.location.reload();
        });
      },
    });
  }
}
