import { create } from 'zustand';

interface PWAState {
  deferredPrompt: any;
  isInstallable: boolean;
  setDeferredPrompt: (prompt: any) => void;
  clearDeferredPrompt: () => void;
  triggerInstall: () => Promise<boolean>;
}

export const usePWAStore = create<PWAState>((set, get) => ({
  deferredPrompt: null,
  isInstallable: false,
  setDeferredPrompt: (prompt) => set({ deferredPrompt: prompt, isInstallable: !!prompt }),
  clearDeferredPrompt: () => set({ deferredPrompt: null, isInstallable: false }),
  triggerInstall: async () => {
    const prompt = get().deferredPrompt;
    if (!prompt) return false;
    
    // Show the install prompt
    prompt.prompt();
    
    // Wait for the user to respond to the prompt
    const { outcome } = await prompt.userChoice;
    console.log(`[PWA] Install user choice: ${outcome}`);
    
    // Clear the stashed prompt
    get().clearDeferredPrompt();
    return outcome === 'accepted';
  }
}));

// Set up event listeners early when the module is imported
if (typeof window !== 'undefined') {
  window.addEventListener('beforeinstallprompt', (e) => {
    // Prevent default Chrome 67 and earlier auto-prompt
    e.preventDefault();
    // Stash the event
    usePWAStore.getState().setDeferredPrompt(e);
    console.log('[PWA] beforeinstallprompt event fired & stashed');
  });

  window.addEventListener('appinstalled', () => {
    console.log('[PWA] Application successfully installed');
    usePWAStore.getState().clearDeferredPrompt();
  });
}
