// PWA install hint. Two flavours:
//   - Android Chrome: capture `beforeinstallprompt` and surface an install button
//   - iOS Safari: show a banner explaining "Share → Add to Home Screen"
// Hidden once the app is launched in standalone mode, or after the user dismisses.

(function () {
  const DISMISS_KEY = 'resdri:pwa-dismissed-at';
  const DISMISS_TTL_MS = 7 * 24 * 60 * 60 * 1000; // 7 days

  function isStandalone() {
    return (
      window.matchMedia && window.matchMedia('(display-mode: standalone)').matches
    ) || window.navigator.standalone === true;
  }

  function isIos() {
    return /iPhone|iPad|iPod/i.test(navigator.userAgent) && !window.MSStream;
  }

  function wasRecentlyDismissed() {
    const t = parseInt(localStorage.getItem(DISMISS_KEY) || '0', 10);
    return t && Date.now() - t < DISMISS_TTL_MS;
  }

  // ─ Android: capture event
  let deferredPrompt = null;
  window.addEventListener('beforeinstallprompt', (e) => {
    e.preventDefault();
    deferredPrompt = e;
    window.dispatchEvent(new CustomEvent('resdri:install-available'));
  });
  window.addEventListener('appinstalled', () => {
    deferredPrompt = null;
    localStorage.setItem(DISMISS_KEY, String(Date.now())); // stop reprompting
  });

  // ─ Public API
  window.resdriPwa = {
    isStandalone,
    isIos,
    wasRecentlyDismissed,
    hasDeferredPrompt: () => !!deferredPrompt,
    async install() {
      if (!deferredPrompt) return false;
      deferredPrompt.prompt();
      try { await deferredPrompt.userChoice; } catch {}
      deferredPrompt = null;
      return true;
    },
    dismiss() {
      localStorage.setItem(DISMISS_KEY, String(Date.now()));
    },
  };
})();

// ─ React component injected into the App tree
function InstallHint() {
  const [available, setAvailable] = React.useState(false);
  const [dismissed, setDismissed] = React.useState(window.resdriPwa.wasRecentlyDismissed());

  React.useEffect(() => {
    if (window.resdriPwa.isStandalone()) { setDismissed(true); return; }
    const onAvail = () => setAvailable(true);
    window.addEventListener('resdri:install-available', onAvail);
    // On iOS there's no beforeinstallprompt; surface the hint immediately.
    if (window.resdriPwa.isIos()) setAvailable(true);
    // Check after a moment in case the event already fired
    setTimeout(() => setAvailable(window.resdriPwa.hasDeferredPrompt() || window.resdriPwa.isIos()), 300);
    return () => window.removeEventListener('resdri:install-available', onAvail);
  }, []);

  if (dismissed || !available || window.resdriPwa.isStandalone()) return null;

  const ios = window.resdriPwa.isIos();
  const dismiss = () => { window.resdriPwa.dismiss(); setDismissed(true); };
  const install = async () => {
    const ok = await window.resdriPwa.install();
    if (ok) setDismissed(true);
  };

  return (
    <div style={{
      position: 'fixed', insetInline: 0, bottom: 0, zIndex: 1000,
      pointerEvents: 'none',
      padding: '12px 12px max(12px, env(safe-area-inset-bottom))',
      display: 'flex', justifyContent: 'center',
    }}>
      <div style={{
        pointerEvents: 'auto',
        background: 'var(--surface, #fff)',
        borderRadius: 18,
        border: '1px solid var(--line, #E2E8F0)',
        boxShadow: '0 12px 32px rgba(15,23,42,0.18)',
        padding: 14,
        display: 'flex', alignItems: 'center', gap: 12,
        maxWidth: 420, width: '100%',
        fontFamily: 'var(--font)',
      }} dir="rtl">
        <div style={{
          width: 44, height: 44, borderRadius: 12, flexShrink: 0,
          background: 'var(--primary, #0F766E)', color: 'white',
          display: 'grid', placeItems: 'center', fontWeight: 900, fontSize: 20,
        }}>R</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 800, color: 'var(--text, #0F172A)' }}>تثبيت تطبيق ResDri</div>
          <div style={{ fontSize: 12, color: 'var(--text-2, #475569)', marginTop: 2, lineHeight: 1.4 }}>
            {ios
              ? <>اضغط <span style={{ display: 'inline-flex', verticalAlign: 'middle', width: 16, height: 16, alignItems: 'center', justifyContent: 'center' }}>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 16V4M7 9l5-5 5 5"/><rect x="4" y="14" width="16" height="6" rx="2"/></svg>
                </span> ثم "أضف إلى الشاشة الرئيسية"</>
              : 'ثبّت التطبيق على شاشتك الرئيسية للوصول السريع'
            }
          </div>
        </div>
        {!ios && (
          <button onClick={install} className="tap" style={{
            height: 36, padding: '0 14px', borderRadius: 10, border: 'none',
            background: 'var(--primary, #0F766E)', color: 'white',
            fontFamily: 'inherit', fontWeight: 800, fontSize: 13, cursor: 'pointer',
            flexShrink: 0,
          }}>تثبيت</button>
        )}
        <button onClick={dismiss} className="tap" style={{
          width: 30, height: 30, borderRadius: 999, border: 'none',
          background: 'var(--surface-2, #F8FAFC)', color: 'var(--text-2, #475569)',
          fontSize: 16, cursor: 'pointer', flexShrink: 0,
          display: 'grid', placeItems: 'center',
        }} aria-label="إخفاء">✕</button>
      </div>
    </div>
  );
}

Object.assign(window, { InstallHint });
