/**
 * InstallPromptService
 *
 * Story 3.4: Service layer for PWA install prompt logic
 *
 * Architecture Compliance (Logic Sandwich Pattern):
 * - UI Components MUST NOT directly handle beforeinstallprompt event
 * - All install prompt logic goes through this service layer
 * - Services return plain success/failure, not browser events directly
 *
 * Responsibilities:
 * - Listen for beforeinstallprompt event
 * - Store event in InstallPromptStore for later triggering
 * - Detect standalone mode (already installed)
 * - Trigger install prompt on demand
 */

import { useInstallPromptStore, type BeforeInstallPromptEvent } from '@/lib/store/install-prompt-store';

/**
 * InstallPromptService
 *
 * Manages the PWA install prompt lifecycle.
 * Initializes event listeners and detects install status.
 */
export class InstallPromptService {
  private static initialized = false;

  /**
   * Initialize the install prompt service
   *
   * Sets up event listeners for:
   * - beforeinstallprompt: Browser fires this when PWA is installable
   * - appinstalled: Browser fires this after successful install
   *
   * Also checks if app is already running in standalone mode
   */
  static initialize(): void {
    if (this.initialized) return;
    this.initialized = true;

    // Check if already installed (standalone mode)
    this.checkInstalledStatus();

    // Listen for beforeinstallprompt event
    if (typeof window !== 'undefined') {
      window.addEventListener('beforeinstallprompt', (e) => {
        // Prevent default browser install prompt
        e.preventDefault();

        const event = e as BeforeInstallPromptEvent;

        // Store event for later triggering
        useInstallPromptStore.getState().setDeferredPrompt(event);

        console.log('[InstallPromptService] beforeinstallprompt event captured');
      });

      // Listen for appinstalled event (user accepted install)
      window.addEventListener('appinstalled', () => {
        useInstallPromptStore.getState().setInstalled(true);
        console.log('[InstallPromptService] App installed successfully');
      });
    }
  }

  /**
   * Check if the app is running in standalone mode
   *
   * Standalone mode means the app was launched from the home screen,
   * not from a browser window.
   *
   * Uses two methods:
   * 1. window.matchMedia('(display-mode: standalone)') - Chrome/Edge/Firefox
   * 2. window.navigator.standalone - iOS Safari
   */
  static checkInstalledStatus(): void {
    if (typeof window === 'undefined') return;

    // Check if running in standalone mode
    const isStandalone =
      window.matchMedia('(display-mode: standalone)').matches ||
      (window.navigator as any).standalone === true; // iOS Safari

    useInstallPromptStore.getState().setInstalled(isStandalone);

    if (isStandalone) {
      console.log('[InstallPromptService] Running in standalone mode (already installed)');
    }
  }

  /**
   * Trigger the install prompt
   *
   * Calls the stored event's prompt() method
   * @returns true if user accepted, false if dismissed or no prompt available
   */
  static async promptInstall(): Promise<boolean> {
    return await useInstallPromptStore.getState().promptInstall();
  }

  /**
   * Check if the app is installable
   *
   * @returns true if beforeinstallprompt event was captured
   */
  static isInstallable(): boolean {
    return useInstallPromptStore.getState().isInstallable;
  }

  /**
   * Check if the app is installed (running in standalone mode)
   *
   * @returns true if app is running in standalone mode
   */
  static isInstalled(): boolean {
    return useInstallPromptStore.getState().isInstalled;
  }

  /**
   * Dismiss the install prompt
   *
   * Clears the stored event without triggering the prompt
   */
  static dismissInstall(): void {
    useInstallPromptStore.getState().dismissInstall();
  }

  /**
   * Check if we're in a browser that supports beforeinstallprompt
   *
   * @returns true if browser supports custom install prompts
   */
  static isSupported(): boolean {
    if (typeof window === 'undefined') return false;

    // Safari (iOS and desktop) doesn't support beforeinstallprompt
    const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
    return !isSafari;
  }
}
