import { Component, OnInit, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ButtonsModule } from '@progress/kendo-angular-buttons';
import { PushNotificationService } from '../../../../core/services/push-notification.service';
import { ToastService } from '../../../../core/services/toast.service';

/**
 * Lets the logged-in member turn Web Push on/off for the current device and fire a test
 * notification. Shows an iOS install hint, since on iPhone push only works once the PWA is
 * added to the Home Screen.
 */
@Component({
  selector: 'app-push-notifications-card',
  standalone: true,
  imports: [CommonModule, ButtonsModule],
  template: `
<div class="flex flex-col gap-3">
  <p class="text-sm text-gray-500">
    Get notified on this device. You can turn it off anytime.
  </p>

  <!-- iOS: must install to Home Screen first -->
  <div *ngIf="showIosHint" class="rounded-md bg-amber-50 border border-amber-200 p-3 text-sm text-amber-800">
    在 iPhone / iPad 上，請先用 Safari 的「分享 → 加入主畫面」安裝本 App，再從主畫面圖示開啟，才能啟用推播。
  </div>

  <div *ngIf="!supported && !showIosHint"
    class="rounded-md bg-gray-50 border border-gray-200 p-3 text-sm text-gray-600">
    此瀏覽器或環境不支援推播通知（開發模式下會停用）。
  </div>

  <div class="flex flex-wrap items-center gap-2">
    <button *ngIf="!enabled" kendoButton themeColor="primary"
      [disabled]="!supported || busy" (click)="enable()">
      Enable notifications
    </button>
    <button *ngIf="enabled" kendoButton
      [disabled]="busy" (click)="disable()">
      Disable notifications
    </button>
    <button *ngIf="enabled" kendoButton themeColor="info"
      [disabled]="busy" (click)="sendTest()">
      Send test
    </button>
    <span *ngIf="enabled" class="text-sm text-green-700">● 已啟用 Enabled on this device</span>
  </div>
</div>
  `,
})
export class PushNotificationsCardComponent implements OnInit {
  private readonly push = inject(PushNotificationService);
  private readonly toast = inject(ToastService);

  supported = false;
  enabled = false;
  busy = false;
  showIosHint = false;

  ngOnInit(): void {
    this.supported = this.push.isSupported;
    this.showIosHint = this.isIosNotInstalled();
    this.push.subscription$.subscribe((subscription) => (this.enabled = !!subscription));
  }

  async enable(): Promise<void> {
    this.busy = true;
    try {
      await this.push.enable();
      this.toast.success('已啟用推播通知。Notifications enabled.');
    } catch (err: unknown) {
      this.toast.error(err instanceof Error ? err.message : '無法啟用推播通知。');
    } finally {
      this.busy = false;
    }
  }

  async disable(): Promise<void> {
    this.busy = true;
    try {
      await this.push.disable();
      this.toast.success('已關閉推播通知。Notifications disabled.');
    } catch {
      this.toast.error('無法關閉推播通知。');
    } finally {
      this.busy = false;
    }
  }

  async sendTest(): Promise<void> {
    this.busy = true;
    try {
      await this.push.sendTestToSelf();
      this.toast.success('測試通知已送出。Test notification sent.');
    } catch {
      this.toast.error('無法送出測試通知。');
    } finally {
      this.busy = false;
    }
  }

  // iOS Safari, not running as an installed PWA — push is unavailable until added to Home Screen.
  private isIosNotInstalled(): boolean {
    const isIos = /iphone|ipad|ipod/i.test(navigator.userAgent);
    const isStandalone =
      window.matchMedia('(display-mode: standalone)').matches ||
      (navigator as unknown as { standalone?: boolean }).standalone === true;
    return isIos && !isStandalone;
  }
}
