// Calm PWA install state. Captures the browser's install prompt (Android/desktop
// Chrome), detects iOS (which has no prompt — needs the Share → Add to Home Screen
// hint), and remembers a dismissal so we never nag.
import { browser } from '$app/environment';

export const pwa = $state({ canInstall: false, isIOS: false, isStandalone: false, dismissed: false });
let deferred = null;

if (browser) {
  try {
    pwa.isStandalone =
      window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone === true;
    pwa.isIOS = /iphone|ipad|ipod/i.test(window.navigator.userAgent);
    pwa.dismissed = localStorage.getItem('goodnews:pwa_dismissed') === '1';
  } catch {
    /* private mode / unavailable */
  }
  window.addEventListener('beforeinstallprompt', (e) => {
    e.preventDefault();
    deferred = e;
    pwa.canInstall = true;
  });
  window.addEventListener('appinstalled', () => {
    pwa.canInstall = false;
    pwa.isStandalone = true;
  });
}

export async function installApp() {
  if (!deferred) return;
  deferred.prompt();
  try { await deferred.userChoice; } catch { /* dismissed */ }
  deferred = null;
  pwa.canInstall = false;
}

export function dismissPwa() {
  pwa.dismissed = true;
  if (browser) {
    try { localStorage.setItem('goodnews:pwa_dismissed', '1'); } catch { /* ignore */ }
  }
}
