<?php
// PWA Service Worker Registration & Install Prompt
// Include this before </body>
?>
<!-- PWA Install Banner -->
<div id="pwaInstallBanner" style="display:none;position:fixed;bottom:0;left:0;right:0;z-index:9999;padding:16px;background:#fff;border-top:1px solid rgba(0,0,0,.08);box-shadow:0 -4px 24px rgba(0,0,0,.1);animation:slideUp .4s ease;">
  <div style="max-width:600px;margin:0 auto;display:flex;align-items:center;gap:12px;">
    <img src="<?php echo htmlspecialchars(!empty($site_data['logo_url']) ? $site_data['logo_url'] : $site_data['web_url'] . '/images/softbills.png'); ?>" alt="" style="width:44px;height:44px;border-radius:12px;object-fit:contain;background:#f4f6fb;padding:4px;">
    <div style="flex:1;min-width:0;">
      <div style="font-size:.85rem;font-weight:700;color:#0c0f14;margin-bottom:2px;">Install <?php echo htmlspecialchars($site_data['web_name']); ?></div>
      <div style="font-size:.72rem;color:#64748b;">Add to home screen for quick access</div>
    </div>
    <button id="pwaInstallBtn" style="padding:8px 16px;background:#4D148C;color:#fff;border:none;border-radius:10px;font-size:.78rem;font-weight:700;cursor:pointer;white-space:nowrap;box-shadow:0 3px 12px rgba(77,20,140,.25);">Install</button>
    <button id="pwaDismissBtn" style="padding:8px;background:none;border:none;cursor:pointer;color:#94a3b8;font-size:1.1rem;line-height:1;">&times;</button>
  </div>
</div>

<!-- iOS Install Instructions Modal -->
<div id="pwaIosModal" style="display:none;position:fixed;inset:0;z-index:10000;background:rgba(0,0,0,.5);backdrop-filter:blur(4px);align-items:center;justify-content:center;padding:1rem;">
  <div style="background:#fff;border-radius:20px;max-width:360px;width:100%;padding:2rem;text-align:center;box-shadow:0 20px 60px rgba(0,0,0,.15);">
    <div style="width:56px;height:56px;border-radius:14px;background:rgba(77,20,140,.08);display:flex;align-items:center;justify-content:center;margin:0 auto 1rem;">
      <svg width="24" height="24" fill="none" stroke="#4D148C" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/></svg>
    </div>
    <h3 style="font-size:1.1rem;font-weight:800;margin-bottom:.5rem;color:#0c0f14;">Install <?php echo htmlspecialchars($site_data['web_name']); ?></h3>
    <p style="font-size:.82rem;color:#64748b;line-height:1.6;margin-bottom:1.25rem;">To install this app on your iPhone/iPad:</p>
    <div style="text-align:left;background:#f8fafc;border-radius:12px;padding:1rem;margin-bottom:1.25rem;">
      <div style="display:flex;align-items:center;gap:10px;margin-bottom:10px;">
        <span style="width:24px;height:24px;border-radius:6px;background:#4D148C;color:#fff;display:flex;align-items:center;justify-content:center;font-size:.7rem;font-weight:700;flex-shrink:0;">1</span>
        <span style="font-size:.8rem;color:#334155;">Tap the <strong>Share</strong> button <svg width="14" height="14" fill="none" stroke="#4D148C" stroke-width="2" viewBox="0 0 24 24" style="display:inline;vertical-align:middle;"><path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/></svg> at the bottom</span>
      </div>
      <div style="display:flex;align-items:center;gap:10px;margin-bottom:10px;">
        <span style="width:24px;height:24px;border-radius:6px;background:#4D148C;color:#fff;display:flex;align-items:center;justify-content:center;font-size:.7rem;font-weight:700;flex-shrink:0;">2</span>
        <span style="font-size:.8rem;color:#334155;">Scroll down and tap <strong>"Add to Home Screen"</strong></span>
      </div>
      <div style="display:flex;align-items:center;gap:10px;">
        <span style="width:24px;height:24px;border-radius:6px;background:#4D148C;color:#fff;display:flex;align-items:center;justify-content:center;font-size:.7rem;font-weight:700;flex-shrink:0;">3</span>
        <span style="font-size:.8rem;color:#334155;">Tap <strong>"Add"</strong> to confirm</span>
      </div>
    </div>
    <button onclick="document.getElementById('pwaIosModal').style.display='none'" style="width:100%;padding:12px;background:#4D148C;color:#fff;border:none;border-radius:12px;font-size:.85rem;font-weight:700;cursor:pointer;box-shadow:0 4px 16px rgba(77,20,140,.25);">Got it</button>
  </div>
</div>

<style>
@keyframes slideUp{from{transform:translateY(100%);opacity:0}to{transform:translateY(0);opacity:1}}
</style>

<script>
// ── PWA Service Worker Registration ──
if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('<?php echo $site_data['web_url']; ?>/sw.js', { scope: '<?php echo $site_data['web_url']; ?>/' })
      .then(function(reg) { console.log('SW registered:', reg.scope); })
      .catch(function(err) { console.log('SW registration failed:', err); });
  });
}

// ── PWA Install Prompt ──
var _pwaPrompt = null;
var _pwaIsIos = /iphone|ipad|ipod/.test(navigator.userAgent.toLowerCase());
var _pwaIsSafari = /safari/.test(navigator.userAgent.toLowerCase()) && !/chrome/.test(navigator.userAgent.toLowerCase());

function triggerPwaInstall() {
  if (_pwaPrompt) {
    _pwaPrompt.prompt();
    _pwaPrompt.userChoice.then(function(choice) {
      if (choice.outcome === 'accepted') {
        _hideInstallUI();
      }
      _pwaPrompt = null;
    });
  } else if (_pwaIsIos && _pwaIsSafari) {
    var iosModal = document.getElementById('pwaIosModal');
    if (iosModal) iosModal.style.display = 'flex';
  } else {
    // Fallback: show the banner
    var banner = document.getElementById('pwaInstallBanner');
    if (banner) banner.style.display = 'block';
  }
}

function _hideInstallUI() {
  var banner = document.getElementById('pwaInstallBanner');
  if (banner) banner.style.display = 'none';
  var navBtn = document.getElementById('navInstallBtn');
  if (navBtn) navBtn.style.display = 'none';
  var mobBtn = document.getElementById('mobInstallBtn');
  if (mobBtn) mobBtn.style.display = 'none';
  var userBtn = document.getElementById('userInstallBtn');
  if (userBtn) userBtn.style.display = 'none';
}

function _showInstallUI() {
  var navBtn = document.getElementById('navInstallBtn');
  if (navBtn) navBtn.style.display = 'inline-flex';
  var mobBtn = document.getElementById('mobInstallBtn');
  if (mobBtn) mobBtn.style.display = 'flex';
  var userBtn = document.getElementById('userInstallBtn');
  if (userBtn) userBtn.style.display = 'flex';
}

(function() {
  var banner = document.getElementById('pwaInstallBanner');
  var installBtn = document.getElementById('pwaInstallBtn');
  var dismissBtn = document.getElementById('pwaDismissBtn');

  // Check if already installed or dismissed
  var isStandalone = window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone;
  var dismissed = localStorage.getItem('pwa-dismissed');
  if (isStandalone) { _hideInstallUI(); return; }

  // Check if on signin page for immediate display
  var isSigninPage = window.location.pathname.indexOf('/signin') !== -1 || window.location.pathname.indexOf('/signup') !== -1;
  var showDelay = isSigninPage ? 1000 : 3000;

  // Android/Desktop — beforeinstallprompt
  window.addEventListener('beforeinstallprompt', function(e) {
    e.preventDefault();
    _pwaPrompt = e;
    _showInstallUI();
    if (!dismissed || Date.now() - parseInt(dismissed) > 7 * 24 * 60 * 60 * 1000) {
      setTimeout(function() { if (banner) banner.style.display = 'block'; }, showDelay);
    }
  });

  // iOS Safari — show instructions
  if (_pwaIsIos && _pwaIsSafari && !isStandalone) {
    _showInstallUI();
    if (!dismissed || Date.now() - parseInt(dismissed) > 7 * 24 * 60 * 60 * 1000) {
      setTimeout(function() { if (banner) banner.style.display = 'block'; }, showDelay);
    }
  }

  // Install button click
  if (installBtn) {
    installBtn.addEventListener('click', function() { triggerPwaInstall(); });
  }

  // Dismiss button
  if (dismissBtn) {
    dismissBtn.addEventListener('click', function() {
      if (banner) banner.style.display = 'none';
      localStorage.setItem('pwa-dismissed', Date.now().toString());
    });
  }

  // Hide banner if app gets installed
  window.addEventListener('appinstalled', function() {
    _hideInstallUI();
    _pwaPrompt = null;
  });
})();
</script>
