// Register Service Worker
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('./sw.js')
      .then((registration) => {
        console.log('[PWA] Service Worker registered');
      })
      .catch((error) => {
        console.error('[PWA] SW registration failed:', error);
      });
  });
}

let deferredPrompt;

// Standalone detection
const isStandalone = window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone;

window.addEventListener('beforeinstallprompt', (e) => {
  // Prevent default mini-infobar
  e.preventDefault();
  // Stash the event
  deferredPrompt = e;
  
  // Only show if not already installed
  if (!isStandalone) {
    showInstallPromotion();
  }
});

function showInstallPromotion() {
  // If user already dismissed it this session, don't nag
  if (sessionStorage.getItem('pwa_prompt_dismissed')) return;
  if (document.getElementById('pwa-install-banner')) return;

  const banner = document.createElement('div');
  banner.id = 'pwa-install-banner';
  banner.style.cssText = `
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: white;
    padding: 20px;
    box-shadow: 0 -10px 40px rgba(0,0,0,0.15);
    z-index: 99999;
    display: flex;
    flex-direction: column;
    align-items: center;
    border-top: 4px solid #4f46e5;
    border-radius: 24px 24px 0 0;
    animation: slideUp 0.5s ease-out;
  `;

  banner.innerHTML = `
    <style>
      @keyframes slideUp { from { transform: translateY(100%); } to { transform: translateY(0); } }
      .pwa-btn { padding: 12px 24px; border-radius: 12px; font-weight: 700; cursor: pointer; transition: 0.2s; border: none; flex: 1; }
      .pwa-install { background: #4f46e5; color: white; }
      .pwa-install:hover { background: #4338ca; transform: translateY(-2px); }
      .pwa-later { background: #f1f5f9; color: #64748b; }
    </style>
    <div style="width: 50px; height: 50px; background: #eef2ff; border-radius: 12px; display: flex; align-items: center; justify-content: center; margin-bottom: 12px;">
      <img src="./image/mylogo.png" alt="QualiLearn" style="width: 30px; height: 30px;">
    </div>
    <h5 style="margin: 0; color: #1e293b; font-weight: 800;">Install QualiLearn App</h5>
    <p style="margin: 8px 0 20px 0; color: #64748b; text-align: center; font-size: 0.9rem;">Access your courses faster and study offline anytime.</p>
    <div style="display: flex; gap: 12px; width: 100%; max-width: 400px;">
      <button class="pwa-btn pwa-later" id="pwa-close">Maybe Later</button>
      <button class="pwa-btn pwa-install" id="pwa-do-install">Install Now</button>
    </div>
  `;

  document.body.appendChild(banner);

  document.getElementById('pwa-close').addEventListener('click', () => {
    sessionStorage.setItem('pwa_prompt_dismissed', 'true');
    banner.style.transform = 'translateY(100%)';
    banner.style.transition = '0.5s';
    setTimeout(() => banner.remove(), 500);
  });

  document.getElementById('pwa-do-install').addEventListener('click', async () => {
    if (deferredPrompt) {
      deferredPrompt.prompt();
      const { outcome } = await deferredPrompt.userChoice;
      console.log(`[PWA] Install choice: ${outcome}`);
      deferredPrompt = null;
      banner.remove();
    } else {
      // iOS fallback
      const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
      if (isIOS) {
        alert("To Install on iOS: \n1. Tap the Share button below\n2. Select 'Add to Home Screen'");
      } else {
        alert("Installation is ready! Please check your browser's menu for the Install button.");
      }
      banner.remove();
    }
  });
}

// Global function to trigger install from UI buttons
window.triggerPWAInstall = () => {
  if (deferredPrompt) {
    deferredPrompt.prompt();
  } else if (isStandalone) {
    alert("QualiLearn is already installed!");
  } else {
    showInstallPromotion();
  }
};
