// SIMAK PWA - Main Registration & UI
(function() {
  'use strict';

  if (!('serviceWorker' in navigator)) return;

  const VERSION = 'simak-v2';
  let deferredPrompt = null;
  let registration = null;
  let updateAvailable = false;
  let newWorker = null;

  // ─── DOM ELEMENTS ──────────────────────────────────────────
  function createPWAUI() {
    // Status Bar
    const statusBar = document.createElement('div');
    statusBar.className = 'pwa-status-bar';
    statusBar.id = 'pwaStatusBar';
    document.body.prepend(statusBar);

    // Install Banner
    const installBanner = document.createElement('div');
    installBanner.className = 'pwa-install-banner';
    installBanner.id = 'pwaInstallBanner';
    installBanner.innerHTML = `
      <img src="/assets/img/icons/icon-96x96.png" alt="SIMAK" class="pwa-install-icon" />
      <div class="pwa-install-info">
        <div class="pwa-install-title">Install SIMAK PPDS</div>
        <div class="pwa-install-desc">Akses cepat tanpa buka browser</div>
      </div>
      <button class="pwa-install-btn" id="pwaInstallBtn">
        <i class="bi bi-download"></i> Install
      </button>
      <button class="pwa-install-close" id="pwaInstallClose" aria-label="Tutup">
        <i class="bi bi-x-lg"></i>
      </button>
    `;
    document.body.appendChild(installBanner);

    // Update Toast
    const updateToast = document.createElement('div');
    updateToast.className = 'pwa-update-toast';
    updateToast.id = 'pwaUpdateToast';
    updateToast.innerHTML = `
      <span class="pwa-update-icon"><i class="bi bi-arrow-repeat"></i></span>
      <span class="pwa-update-text">Versi baru tersedia</span>
      <button class="pwa-update-btn" id="pwaUpdateBtn">Perbarui</button>
      <button class="pwa-update-dismiss" id="pwaUpdateDismiss" aria-label="Nanti">
        <i class="bi bi-x-lg"></i>
      </button>
    `;
    document.body.appendChild(updateToast);

    // Install Instructions Modal
    const installModal = document.createElement('div');
    installModal.className = 'pwa-install-modal-overlay';
    installModal.id = 'pwaInstallModal';
    installModal.innerHTML = `
      <div class="pwa-install-modal">
        <img src="/assets/img/icons/icon-192x192.png" alt="SIMAK" class="pwa-install-modal-icon" />
        <h3>Install Aplikasi</h3>
        <p>Pasang SIMAK di perangkat Anda untuk akses yang lebih cepat dan mudah.</p>
        <div class="pwa-install-modal-steps">
          <div class="step">
            <span class="step-num">1</span>
            <span>Buka menu browser <strong id="pwaBrowserMenu">⚙️</strong></span>
          </div>
          <div class="step">
            <span class="step-num">2</span>
            <span>Pilih <strong>"Tambahkan ke Layar Utama"</strong> atau <strong>"Install App"</strong></span>
          </div>
          <div class="step">
            <span class="step-num">3</span>
            <span>Konfirmasi untuk menginstall</span>
          </div>
        </div>
        <button class="pwa-install-modal-close" id="pwaInstallModalClose">Mengerti</button>
      </div>
    `;
    document.body.appendChild(installModal);
  }

  // ─── SERVICE WORKER REGISTRATION ───────────────────────────
  function registerSW() {
    navigator.serviceWorker.register('/sw.js', { scope: '/' }).then(reg => {
      registration = reg;

      // Check for updates
      reg.addEventListener('updatefound', () => {
        newWorker = reg.installing;
        newWorker.addEventListener('statechange', () => {
          if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
            updateAvailable = true;
            showUpdateNotification();
          }
        });
      });
    });

    // Watch for controller change
    let refreshing = false;
    navigator.serviceWorker.addEventListener('controllerchange', () => {
      if (!refreshing) {
        refreshing = true;
        window.location.reload();
      }
    });
  }

  // ─── ONLINE / OFFLINE INDICATOR ───────────────────────────
  function setupNetworkStatus() {
    const bar = document.getElementById('pwaStatusBar');

    function showOnline() {
      if (!bar) return;
      bar.className = 'pwa-status-bar online show';
      bar.innerHTML = '<i class="bi bi-wifi"></i> Koneksi kembali tersambung';
      setTimeout(() => bar.classList.remove('show'), 2500);
    }

    function showOffline() {
      if (!bar) return;
      bar.className = 'pwa-status-bar offline show';
      bar.innerHTML = '<i class="bi bi-wifi-off"></i> Anda sedang offline';
    }

    window.addEventListener('online', () => {
      showOnline();
      // Reload current page data when coming back online
      if (document.querySelector('.content-area')) {
        setTimeout(() => {
          if (document.querySelector('.alert-danger') === null) {
            // Only reload if we're not in the middle of a form submission
            const activeEl = document.activeElement;
            if (!activeEl || (activeEl.tagName !== 'INPUT' && activeEl.tagName !== 'TEXTAREA')) {
              window.location.reload();
            }
          }
        }, 1500);
      }
    });

    window.addEventListener('offline', showOffline);
  }

  // ─── INSTALL PROMPT ────────────────────────────────────────
  function setupInstallPrompt() {
    const banner = document.getElementById('pwaInstallBanner');
    const installBtn = document.getElementById('pwaInstallBtn');
    const closeBtn = document.getElementById('pwaInstallClose');
    const modal = document.getElementById('pwaInstallModal');
    const modalClose = document.getElementById('pwaInstallModalClose');

    if (!banner || !installBtn) return;

    // Check if already installed
    if (window.matchMedia('(display-mode: standalone)').matches) {
      return;
    }

    // Capture beforeinstallprompt
    window.addEventListener('beforeinstallprompt', (event) => {
      // Tahan banner bawaan browser karena aplikasi memiliki banner sendiri.
      event.preventDefault();
      deferredPrompt = event;

      const dismissed = sessionStorage.getItem('pwa_install_dismissed');
      if (!dismissed) {
        setTimeout(() => banner.classList.add('show'), 2000);
      }
    });

    // Install button click
    installBtn.addEventListener('click', async () => {
      if (!deferredPrompt) {
        showManualInstallModal();
        return;
      }

      const installEvent = deferredPrompt;
      deferredPrompt = null;
      installBtn.classList.add('loading');
      installBtn.innerHTML = '<span class="spinner"></span> Memasang...';

      try {
        installEvent.prompt();
        const { outcome } = await installEvent.userChoice;

        if (outcome === 'accepted') {
          banner.classList.remove('show');
        } else {
          showManualInstallModal();
        }
      } catch (error) {
        console.error('PWA install error:', error);
        showManualInstallModal();
      } finally {
        installBtn.classList.remove('loading');
        installBtn.innerHTML = '<i class="bi bi-download"></i> Install';
      }
    });

    // Close button
    closeBtn.addEventListener('click', () => {
      banner.classList.remove('show');
      sessionStorage.setItem('pwa_install_dismissed', 'true');
    });

    // Modal
    modalClose.addEventListener('click', () => {
      modal.classList.remove('show');
    });
    modal.addEventListener('click', (e) => {
      if (e.target === modal) modal.classList.remove('show');
    });

    // Hide banner when installed
    window.addEventListener('appinstalled', () => {
      banner.classList.remove('show');
    });
  }

  function showManualInstallModal() {
    const modal = document.getElementById('pwaInstallModal');
    if (!modal) return;

    const menuEl = document.getElementById('pwaBrowserMenu');
    if (menuEl) {
      const ua = navigator.userAgent;
      if (ua.includes('Chrome') || ua.includes('Edge')) {
        menuEl.textContent = '⋮';
      } else if (ua.includes('Safari') && !ua.includes('Chrome')) {
        menuEl.textContent = '⎋';
      } else {
        menuEl.textContent = '⋮';
      }
    }
    modal.classList.add('show');
  }

  // ─── UPDATE NOTIFICATION ───────────────────────────────────
  function showUpdateNotification() {
    const toast = document.getElementById('pwaUpdateToast');
    const updateBtn = document.getElementById('pwaUpdateBtn');
    const dismissBtn = document.getElementById('pwaUpdateDismiss');

    if (!toast) return;

    toast.classList.add('show');

    updateBtn.addEventListener('click', () => {
      updateSW();
    }, { once: true });

    dismissBtn.addEventListener('click', () => {
      toast.classList.remove('show');
      // Will show again on next page load
    }, { once: true });
  }

  function updateSW() {
    if (!newWorker) return;
    newWorker.postMessage({ type: 'SKIP_WAITING' });
  }

  // ─── INIT ──────────────────────────────────────────────────
  function init() {
    createPWAUI();
    registerSW();
    setupNetworkStatus();
    setupInstallPrompt();
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();
