(function () {
  'use strict';

  var currentScript = document.currentScript || (function () {
    var scripts = document.getElementsByTagName('script');
    return scripts[scripts.length - 1];
  })();

  var config = {
    apkUrl: currentScript.getAttribute('data-apk-url') || '/download/pos-mobile.apk',
    appName: currentScript.getAttribute('data-app-name') || 'POS Mobile',
    remindHours: parseInt(currentScript.getAttribute('data-remind-hours') || '24', 10)
  };

  var userAgent = navigator.userAgent || '';
  var isAndroid = /Android/i.test(userAgent);
  var isBrowser = !/; wv\)|\bwv\b|Capacitor|Cordova/i.test(userAgent) && !window.Capacitor;
  var storageKey = 'pos_mobile_android_prompt_dismissed_until';

  if (!isAndroid || !isBrowser) {
    return;
  }

  function now() {
    return Date.now ? Date.now() : new Date().getTime();
  }

  function shouldShow() {
    try {
      var dismissedUntil = parseInt(localStorage.getItem(storageKey) || '0', 10);
      return !dismissedUntil || now() > dismissedUntil;
    } catch (error) {
      return true;
    }
  }

  function dismissTemporarily() {
    try {
      localStorage.setItem(storageKey, String(now() + (config.remindHours * 60 * 60 * 1000)));
    } catch (error) {}
  }

  function addStyle() {
    if (document.getElementById('androidAppPromptStyle')) {
      return;
    }

    var style = document.createElement('style');
    style.id = 'androidAppPromptStyle';
    style.textContent = [
      '.android-app-prompt-backdrop{position:fixed;inset:0;z-index:2147483000;background:rgba(15,23,42,.58);display:flex;align-items:flex-end;justify-content:center;padding:16px;}',
      '.android-app-prompt{width:min(100%,430px);background:#fff;color:#111827;border-radius:12px;padding:18px;box-shadow:0 22px 70px rgba(15,23,42,.28);font-family:Inter,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;}',
      '.android-app-prompt__title{margin:0 0 8px;font-size:19px;font-weight:800;line-height:1.25;color:#111827;}',
      '.android-app-prompt__text{margin:0 0 14px;font-size:14px;line-height:1.45;color:#4b5563;}',
      '.android-app-prompt__actions{display:flex;gap:10px;align-items:center;}',
      '.android-app-prompt__download,.android-app-prompt__later{min-height:42px;border-radius:8px;font-size:14px;font-weight:700;text-align:center;}',
      '.android-app-prompt__download{flex:1;display:inline-flex;align-items:center;justify-content:center;background:#0f172a;color:#fff;text-decoration:none;padding:0 14px;}',
      '.android-app-prompt__download:hover{color:#fff;text-decoration:none;}',
      '.android-app-prompt__download.is-disabled{pointer-events:none;opacity:.58;background:#64748b;}',
      '.android-app-prompt__later{border:1px solid #d1d5db;background:#fff;color:#374151;padding:0 14px;}',
      '.android-app-prompt__note{display:block;margin-top:10px;font-size:12px;line-height:1.4;color:#6b7280;}',
      '@media (min-width:576px){.android-app-prompt-backdrop{align-items:center}.android-app-prompt{padding:22px}}'
    ].join('');
    document.head.appendChild(style);
  }

  function render(apkIsAvailable) {
    if (document.getElementById('androidAppPrompt')) {
      return;
    }

    addStyle();

    var backdrop = document.createElement('div');
    backdrop.id = 'androidAppPrompt';
    backdrop.className = 'android-app-prompt-backdrop';
    backdrop.setAttribute('role', 'dialog');
    backdrop.setAttribute('aria-modal', 'true');
    backdrop.innerHTML =
      '<div class="android-app-prompt">' +
        '<h2 class="android-app-prompt__title">Install ' + escapeHtml(config.appName) + ' di Android</h2>' +
        '<p class="android-app-prompt__text">Akses POS lebih nyaman dari aplikasi Android. Login, transaksi, produk, dan laporan tetap memakai data server yang sama.</p>' +
        '<div class="android-app-prompt__actions">' +
          '<a class="android-app-prompt__download' + (apkIsAvailable ? '' : ' is-disabled') + '" href="' + encodeURI(config.apkUrl) + '" download>Download APK</a>' +
          '<button class="android-app-prompt__later" type="button">Nanti</button>' +
        '</div>' +
        '<span class="android-app-prompt__note">' + (apkIsAvailable ? 'Setelah download selesai, buka file APK lalu pilih Install.' : 'File APK belum tersedia. Build APK dulu, lalu simpan sebagai download/pos-mobile.apk.') + '</span>' +
      '</div>';

    backdrop.querySelector('.android-app-prompt__later').addEventListener('click', function () {
      dismissTemporarily();
      backdrop.remove();
    });

    backdrop.addEventListener('click', function (event) {
      if (event.target === backdrop) {
        dismissTemporarily();
        backdrop.remove();
      }
    });

    document.body.appendChild(backdrop);
  }

  function escapeHtml(value) {
    return String(value).replace(/[&<>"']/g, function (char) {
      return {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
      }[char];
    });
  }

  function checkApkAndRender() {
    var request = new XMLHttpRequest();
    request.open('HEAD', config.apkUrl, true);
    request.timeout = 4000;
    request.onreadystatechange = function () {
      if (request.readyState === 4) {
        render(request.status >= 200 && request.status < 400);
      }
    };
    request.onerror = function () {
      render(false);
    };
    request.ontimeout = function () {
      render(false);
    };
    request.send();
  }

  if (!shouldShow()) {
    return;
  }

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

