/* Viamar — PWA install prompt.
   Captures `beforeinstallprompt` (Chrome/Edge/Android) and exposes
   window.ViamarInstall.maybeShow(context). Shows a dismissible branded card —
   "Track this shipment from your home screen" — with a real Install button
   where the event exists, or a 2-step Share → Add to Home Screen hint on iOS
   Safari. Never shows when already running standalone or after a dismissal
   (localStorage flag). Trigger points: booking confirmation (desktop-quote)
   and /mobile with >=1 real shipment (m-app). */

(function () {
  let viamarDeferredInstallEvt = null;
  window.addEventListener('beforeinstallprompt', (e) => {
    e.preventDefault();
    viamarDeferredInstallEvt = e;
  });

  const VIAMAR_INSTALL_DISMISS_KEY = 'viamar.install.dismissed.v1';
  const installDismissed = () => {
    try { return localStorage.getItem(VIAMAR_INSTALL_DISMISS_KEY) === '1'; } catch (e) { return false; }
  };
  const rememberInstallDismiss = () => {
    try { localStorage.setItem(VIAMAR_INSTALL_DISMISS_KEY, '1'); } catch (e) {}
  };
  const isStandaloneDisplay = () =>
    (window.matchMedia && window.matchMedia('(display-mode: standalone)').matches) ||
    window.navigator.standalone === true;
  const isIOSDevice = () =>
    /iphone|ipad|ipod/i.test(navigator.userAgent) ||
    (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);

  // Entrance animates transform only (hard rule — no opacity-from-0).
  const installPromptCss = document.createElement('style');
  installPromptCss.textContent =
    '@keyframes viamarInstallUp { from { transform: translateY(110%); } to { transform: translateY(0); } }' +
    '.viamar-install-up { animation: viamarInstallUp .34s cubic-bezier(.22,.61,.36,1) both; }';
  document.head.appendChild(installPromptCss);

  const installCardStyles = {
    wrap: {
      position: 'fixed', left: 12, right: 12,
      bottom: 'calc(12px + env(safe-area-inset-bottom, 0px))',
      zIndex: 9990, display: 'flex', justifyContent: 'center', pointerEvents: 'none',
    },
    card: {
      pointerEvents: 'auto', width: '100%', maxWidth: 480,
      background: '#0A1B2E', color: '#fff', borderRadius: 18,
      border: '1px solid rgba(255,255,255,0.12)',
      boxShadow: '0 18px 50px rgba(0,0,0,0.45)',
      padding: '16px 16px 14px',
      fontFamily: "'Archivo', system-ui, sans-serif",
    },
  };

  function ViamarInstallCard({ ios, onInstall, onClose }) {
    return (
      <div style={installCardStyles.wrap}>
        <div className="viamar-install-up" style={installCardStyles.card}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 13 }}>
            <img src="/uploads/icons/app/icon-192.png" alt="" width="44" height="44"
              style={{ borderRadius: 11, flexShrink: 0, display: 'block' }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 800, fontSize: 15, lineHeight: 1.25 }}>
                Track this shipment from your home screen
              </div>
              <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.65)', lineHeight: 1.45, marginTop: 4 }}>
                Your shipment is on a weeks-long journey — keep live status one tap away.
              </div>
            </div>
            <button onClick={onClose} aria-label="Dismiss"
              style={{ background: 'rgba(255,255,255,0.08)', border: 0, color: 'rgba(255,255,255,0.7)', width: 28, height: 28, borderRadius: 9, cursor: 'pointer', fontSize: 15, lineHeight: '28px', padding: 0, flexShrink: 0 }}>
              ×
            </button>
          </div>
          {ios ? (
            <div style={{ marginTop: 12, background: 'rgba(255,255,255,0.06)', borderRadius: 12, padding: '11px 13px', fontSize: 13, lineHeight: 1.5, color: 'rgba(255,255,255,0.85)' }}>
              <span style={{ fontWeight: 700, color: '#fff' }}>1.</span> Tap the <span style={{ fontWeight: 700, color: '#fff' }}>Share</span> button below
              &nbsp;·&nbsp; <span style={{ fontWeight: 700, color: '#fff' }}>2.</span> Choose <span style={{ fontWeight: 700, color: '#fff' }}>Add to Home Screen</span>
            </div>
          ) : (
            <button onClick={onInstall}
              style={{ marginTop: 12, width: '100%', background: '#DD1C24', border: 0, color: '#fff', fontFamily: 'inherit', fontWeight: 800, fontSize: 14.5, borderRadius: 12, padding: '12px 0', cursor: 'pointer' }}>
              Install
            </button>
          )}
        </div>
      </div>
    );
  }

  let installPromptShown = false;
  function viamarMaybeShowInstall(context) {
    if (installPromptShown || isStandaloneDisplay() || installDismissed()) return false;
    const ios = isIOSDevice();
    if (!viamarDeferredInstallEvt && !ios) return false; // this browser can't install
    installPromptShown = true;

    const host = document.createElement('div');
    document.body.appendChild(host);
    const root = ReactDOM.createRoot(host);
    const close = (remember) => {
      if (remember) rememberInstallDismiss();
      root.unmount();
      host.remove();
    };
    const install = () => {
      const evt = viamarDeferredInstallEvt;
      if (!evt) { close(false); return; }
      viamarDeferredInstallEvt = null;
      evt.prompt();
      evt.userChoice.then((choice) => {
        if (window.ViamarAnalytics) ViamarAnalytics.track('pwa_install_choice', { outcome: choice && choice.outcome, context: context || null });
        close(choice && choice.outcome === 'dismissed');
      }).catch(() => close(false));
    };
    root.render(<ViamarInstallCard ios={ios} onInstall={install} onClose={() => close(true)} />);
    if (window.ViamarAnalytics) ViamarAnalytics.track('pwa_install_prompt_shown', { context: context || null, platform: ios ? 'ios' : 'chromium' });
    return true;
  }

  window.ViamarInstall = { maybeShow: viamarMaybeShowInstall };
})();
