// install-prompt.jsx — "Add to Home Screen" banner.
// Android Chrome: captures `beforeinstallprompt` and triggers the native prompt.
// iOS Safari: no programmatic API exists, so we open an instructional sheet.

const AP_INSTALL_KEY = 'ap-install-dismissed-v1';

function isStandalone() {
  return (
    window.matchMedia('(display-mode: standalone)').matches ||
    window.navigator.standalone === true
  );
}

function isIOS() {
  const ua = window.navigator.userAgent || '';
  const platform = window.navigator.platform || '';
  // iPhone, iPad, iPod (iPadOS 13+ identifies as Mac with touch)
  if (/iPad|iPhone|iPod/.test(platform)) return true;
  if (/Mac/.test(platform) && navigator.maxTouchPoints > 1) return true;
  return /iPad|iPhone|iPod/.test(ua);
}

function isIOSSafari() {
  if (!isIOS()) return false;
  const ua = window.navigator.userAgent || '';
  // Exclude in-app browsers (FBAN, Instagram, etc.) and Chrome iOS (CriOS) —
  // they cannot add to home screen reliably.
  if (/CriOS|FxiOS|EdgiOS|OPiOS|FBAN|FBAV|Instagram|Line/.test(ua)) return false;
  return /Safari/.test(ua);
}

function InstallPrompt() {
  const [deferred, setDeferred] = React.useState(null);
  const [show, setShow] = React.useState(false);
  const [iosSheet, setIosSheet] = React.useState(false);

  React.useEffect(() => {
    if (isStandalone()) return;
    let dismissedAt = 0;
    try { dismissedAt = parseInt(localStorage.getItem(AP_INSTALL_KEY) || '0', 10); } catch {}
    // re-prompt 14 days after dismissal
    if (dismissedAt && Date.now() - dismissedAt < 14 * 24 * 60 * 60 * 1000) return;

    const onBip = (e) => {
      e.preventDefault();
      setDeferred(e);
      setShow(true);
    };
    window.addEventListener('beforeinstallprompt', onBip);

    const onInstalled = () => {
      setShow(false);
      setDeferred(null);
      try { localStorage.setItem(AP_INSTALL_KEY, String(Date.now())); } catch {}
    };
    window.addEventListener('appinstalled', onInstalled);

    // iOS path — show the banner after a short delay so it doesn't fight the boot screen.
    let iosTimer;
    if (isIOSSafari()) {
      iosTimer = setTimeout(() => setShow(true), 4000);
    }

    return () => {
      window.removeEventListener('beforeinstallprompt', onBip);
      window.removeEventListener('appinstalled', onInstalled);
      if (iosTimer) clearTimeout(iosTimer);
    };
  }, []);

  const dismiss = () => {
    setShow(false);
    setIosSheet(false);
    try { localStorage.setItem(AP_INSTALL_KEY, String(Date.now())); } catch {}
  };

  const install = async () => {
    if (deferred) {
      deferred.prompt();
      try {
        const choice = await deferred.userChoice;
        if (choice && choice.outcome === 'accepted') {
          setShow(false);
          try { localStorage.setItem(AP_INSTALL_KEY, String(Date.now())); } catch {}
        } else {
          dismiss();
        }
      } catch {
        dismiss();
      }
      setDeferred(null);
      return;
    }
    if (isIOSSafari()) {
      setIosSheet(true);
      return;
    }
    dismiss();
  };

  if (!show) return null;

  return (
    <>
      <div className="ap-install-banner" role="dialog" aria-label="Install Astral Project">
        <div className="ap-install-icon">★</div>
        <div className="ap-install-text">
          <div className="ap-install-title">Add Astral to your home screen</div>
          <div className="ap-install-sub">Open it like an app — no browser bar.</div>
        </div>
        <div className="ap-install-actions">
          <button className="w95-btn" onClick={install}>Add</button>
          <button className="w95-btn" onClick={dismiss} aria-label="Dismiss">✕</button>
        </div>
      </div>

      {iosSheet && (
        <div className="ap-install-sheet-backdrop" onClick={() => setIosSheet(false)}>
          <div className="ap-install-sheet" onClick={(e) => e.stopPropagation()}>
            <div className="ap-install-sheet-title">Add to Home Screen</div>
            <ol className="ap-install-sheet-steps">
              <li>
                <span className="ap-install-step-num">1</span>
                Tap the <b>Share</b> button
                <svg width="14" height="18" viewBox="0 0 14 18" style={{ verticalAlign: '-3px', margin: '0 4px' }}>
                  <path d="M7 1l-3 3M7 1l3 3M7 1v11" stroke="#06f" strokeWidth="1.5" fill="none" strokeLinecap="round"/>
                  <path d="M2 8v8h10V8" stroke="#06f" strokeWidth="1.5" fill="none" strokeLinecap="round"/>
                </svg>
                in Safari's toolbar.
              </li>
              <li>
                <span className="ap-install-step-num">2</span>
                Scroll down and tap <b>Add to Home Screen</b>
                <span style={{
                  display: 'inline-block', border: '1px solid #888',
                  borderRadius: 4, padding: '0 4px', marginLeft: 4, fontSize: 12,
                }}>＋</span>.
              </li>
              <li>
                <span className="ap-install-step-num">3</span>
                Tap <b>Add</b> in the top-right.
              </li>
            </ol>
            <button className="w95-btn" style={{ width: '100%', marginTop: 8 }}
                    onClick={() => setIosSheet(false)}>Got it</button>
          </div>
        </div>
      )}
    </>
  );
}

window.InstallPrompt = InstallPrompt;
