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

// Handle Install Prompt
let deferredPrompt;

// Check if already in standalone mode
const isStandalone = window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone;

window.addEventListener('beforeinstallprompt', (e) => {
  console.log('[PWA] beforeinstallprompt event fired');
  // Prevent the mini-infobar from appearing on mobile
  e.preventDefault();
  // Stash the event so it can be triggered later.
  deferredPrompt = e;
  
  // Show the custom install UI
  showInstallPromotion();
});

function showInstallPromotion() {
  if (isStandalone) return;
  if (sessionStorage.getItem('pwaPromptShown') === 'true') return;
  if (document.getElementById('pwa-install-banner')) return;

  // Mark as shown for this session
  sessionStorage.setItem('pwaPromptShown', 'true');

  const banner = document.createElement('div');
  banner.id = 'pwa-install-banner';
  banner.className = 'animate__animated animate__slideInUp';
  banner.style.cssText = `
    position: fixed;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    width: 90%;
    max-width: 400px;
    background: white;
    border-radius: 20px;
    box-shadow: 0 20px 50px rgba(0,0,0,0.3);
    padding: 1.5rem;
    z-index: 10000;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    border: 2px solid #4f46e5;
  `;

  banner.innerHTML = `
    <div style="width: 70px; height: 70px; background: #eef2ff; border-radius: 20px; display: flex; align-items: center; justify-content: center; margin-bottom: 1rem;">
        <img src="./image/mylogo.png" alt="QualiLearn" style="width: 50px; height: 50px; object-fit: contain;">
    </div>
    <h4 style="font-family: 'Outfit', sans-serif; font-weight: 800; color: #1e293b; margin-bottom: 0.5rem;">Download QualiLearn</h4>
    <p style="font-family: 'Inter', sans-serif; color: #64748b; font-size: 0.95rem; margin-bottom: 1.5rem;">Install our mobile app for a faster, better learning experience!</p>
    <div style="display: flex; gap: 12px; width: 100%;">
        <button id="pwa-dismiss-btn" style="flex: 1; padding: 12px; border: none; background: #f1f5f9; color: #64748b; border-radius: 12px; font-weight: 700; cursor: pointer; transition: all 0.2s;">Maybe Later</button>
        <button id="pwa-install-btn" style="flex: 1; padding: 12px; border: none; background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%); color: white; border-radius: 12px; font-weight: 700; cursor: pointer; box-shadow: 0 8px 20px rgba(79, 70, 229, 0.3); transition: all 0.2s;">Install Now</button>
    </div>
  `;

  document.body.appendChild(banner);

  document.getElementById('pwa-dismiss-btn').addEventListener('click', () => {
    banner.classList.replace('animate__slideInUp', 'animate__slideOutDown');
    setTimeout(() => banner.remove(), 500);
  });

  document.getElementById('pwa-install-btn').addEventListener('click', async () => {
    if (deferredPrompt) {
        deferredPrompt.prompt();
        const { outcome } = await deferredPrompt.userChoice;
        console.log(`[PWA] User choice: ${outcome}`);
        deferredPrompt = null;
        banner.remove();
    } else {
        // Fallback for iOS or if event didn't fire
        alert("To install: \n1. Open this in Safari\n2. Tap the 'Share' button\n3. Select 'Add to Home Screen'");
        banner.remove();
    }
  });
}

// Detection for HTTPS (Essential for PWA)
if (window.location.protocol === 'http:' && window.location.hostname !== 'localhost') {
    console.warn('[PWA] PWA requires HTTPS to function on production. Redirecting...');
    // Optional: window.location.href = window.location.href.replace('http:', 'https:');
}

window.addEventListener('appinstalled', () => {
  const banner = document.getElementById('pwa-install-banner');
  if (banner) banner.remove();
  console.log('[PWA] QualiLearn was installed successfully.');
});
