---
// PWA Install Prompt
// Shows a custom install banner when the browser fires 'beforeinstallprompt'
// Also provides a manual install button accessible via #pwa-install-btn
---

<!-- Install Prompt Banner -->
<div
  id="pwa-install-banner"
  role="banner"
  aria-label="Install WorkRoot app"
  class="hidden fixed bottom-4 left-4 right-4 sm:left-auto sm:right-4 sm:w-80 z-50 bg-white border border-secondary-200 rounded-xl shadow-xl p-4"
>
  <div class="flex items-start gap-3">
    <img
      src="/apple-touch-icon.png"
      alt="WorkRoot"
      width="44"
      height="44"
      class="rounded-lg flex-shrink-0"
      loading="lazy"
    />
    <div class="flex-1 min-w-0">
      <p class="font-semibold text-secondary-900 text-sm">Install WorkRoot</p>
      <p class="text-secondary-500 text-xs mt-0.5">
        Add to your home screen for quick access
      </p>
    </div>
    <button
      id="pwa-dismiss-btn"
      aria-label="Dismiss install prompt"
      class="flex-shrink-0 text-secondary-400 hover:text-secondary-600 transition-colors"
    >
      <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
      </svg>
    </button>
  </div>
  <div class="flex gap-2 mt-3">
    <button
      id="pwa-install-btn"
      class="flex-1 bg-primary text-white text-sm font-semibold py-2 px-4 rounded-lg hover:bg-primary/90 transition-colors"
    >
      Install
    </button>
    <button
      id="pwa-later-btn"
      class="flex-1 bg-secondary-100 text-secondary-700 text-sm font-semibold py-2 px-4 rounded-lg hover:bg-secondary-200 transition-colors"
    >
      Not now
    </button>
  </div>
</div>

<script>
  // ─── Background Sync Helper ──────────────────────────────────────────────────
  // Exposed globally so form pages can queue submissions
  window.queueFormSync = async function (url, method, body, formType) {
    const db = await openDB();
    await addToDB(db, 'workroot-sync-queue', {
      url,
      method,
      body,
      formType,
      timestamp: Date.now(),
    });

    // Register background sync if supported
    if ('serviceWorker' in navigator && 'SyncManager' in window) {
      const reg = await navigator.serviceWorker.ready;
      await reg.sync.register('form-sync');
    }
  };

  function openDB() {
    return new Promise((resolve, reject) => {
      const request = indexedDB.open('workroot-pwa', 1);
      request.onupgradeneeded = (event) => {
        const db = event.target.result;
        if (!db.objectStoreNames.contains('workroot-sync-queue')) {
          const store = db.createObjectStore('workroot-sync-queue', { keyPath: 'id', autoIncrement: true });
          store.createIndex('timestamp', 'timestamp', { unique: false });
        }
      };
      request.onsuccess = (event) => resolve(event.target.result);
      request.onerror = () => reject(request.error);
    });
  }

  function addToDB(db, storeName, item) {
    return new Promise((resolve, reject) => {
      const tx = db.transaction(storeName, 'readwrite');
      const store = tx.objectStore(storeName);
      const request = store.add(item);
      request.onsuccess = () => resolve(request.result);
      request.onerror = () => reject(request.error);
    });
  }

  // ─── Install Prompt ───────────────────────────────────────────────────────────
  let deferredPrompt = null;
  const banner = document.getElementById('pwa-install-banner');
  const installBtn = document.getElementById('pwa-install-btn');
  const dismissBtn = document.getElementById('pwa-dismiss-btn');
  const laterBtn = document.getElementById('pwa-later-btn');

  // Don't show banner if already installed or dismissed within 7 days
  const DISMISSED_KEY = 'pwa-install-dismissed';
  const dismissedAt = localStorage.getItem(DISMISSED_KEY);
  const sevenDays = 7 * 24 * 60 * 60 * 1000;
  const recentlyDismissed = dismissedAt && Date.now() - parseInt(dismissedAt) < sevenDays;

  window.addEventListener('beforeinstallprompt', (e) => {
    e.preventDefault();
    deferredPrompt = e;

    if (!recentlyDismissed) {
      // Delay banner so it doesn't distract on first page load
      setTimeout(() => {
        banner?.classList.remove('hidden');
      }, 4000);
    }
  });

  installBtn?.addEventListener('click', async () => {
    if (!deferredPrompt) return;
    deferredPrompt.prompt();
    const { outcome } = await deferredPrompt.userChoice;
    deferredPrompt = null;
    banner?.classList.add('hidden');

    if (outcome === 'accepted') {
      localStorage.removeItem(DISMISSED_KEY);
    }
  });

  function dismissBanner() {
    banner?.classList.add('hidden');
    localStorage.setItem(DISMISSED_KEY, String(Date.now()));
    deferredPrompt = null;
  }

  dismissBtn?.addEventListener('click', dismissBanner);
  laterBtn?.addEventListener('click', dismissBanner);

  // Hide banner once app is installed
  window.addEventListener('appinstalled', () => {
    banner?.classList.add('hidden');
    deferredPrompt = null;
  });

  // ─── SW Sync Success Listener ─────────────────────────────────────────────────
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.addEventListener('message', (event) => {
      if (event.data?.type === 'SYNC_SUCCESS') {
        // Dispatch custom event so form handlers can react
        window.dispatchEvent(new CustomEvent('pwa:sync-success', { detail: event.data }));
      }
    });
  }
</script>
