// InstallPrompt.jsx
// Floating "Install app" banner. Two flavors:
//   - Android/Chrome/Edge: uses the captured `beforeinstallprompt` event.
//   - iOS Safari: shows manual "Share → Add to Home Screen" instructions
//     (iOS doesn't expose a programmatic install API).

function InstallPrompt() {
  const [installable, setInstallable] = React.useState(!!window.__deferredInstallPrompt);
  const [showIosHint, setShowIosHint] = React.useState(false);
  const [dismissed, setDismissed] = React.useState(() => {
    return localStorage.getItem('powlee-install-dismissed') === '1';
  });
  const [isStandalone, setIsStandalone] = React.useState(() => {
    return window.matchMedia('(display-mode: standalone)').matches
      || window.navigator.standalone === true;
  });

  React.useEffect(() => {
    const onAvail = () => setInstallable(true);
    const onInstalled = () => { setInstallable(false); setIsStandalone(true); };
    window.addEventListener('pwa-installable', onAvail);
    window.addEventListener('pwa-installed', onInstalled);
    return () => {
      window.removeEventListener('pwa-installable', onAvail);
      window.removeEventListener('pwa-installed', onInstalled);
    };
  }, []);

  const isIos = /iphone|ipad|ipod/i.test(navigator.userAgent) && !window.MSStream;

  // Already running as installed app — nothing to do.
  if (isStandalone) return null;
  // User dismissed the banner this session/profile.
  if (dismissed) return null;
  // Nothing to show: not installable AND not iOS.
  if (!installable && !isIos) return null;

  const handleInstall = async () => {
    if (window.__deferredInstallPrompt) {
      window.__deferredInstallPrompt.prompt();
      const choice = await window.__deferredInstallPrompt.userChoice;
      if (choice && choice.outcome === 'accepted') {
        setInstallable(false);
      }
      window.__deferredInstallPrompt = null;
    } else if (isIos) {
      setShowIosHint(true);
    }
  };

  const handleDismiss = () => {
    setDismissed(true);
    localStorage.setItem('powlee-install-dismissed', '1');
  };

  return (
    <>
      <div className="install-banner">
        <div className="install-banner__icon">
          <img src="assets/icon-192.png" alt="" width="40" height="40"/>
        </div>
        <div className="install-banner__body">
          <div className="install-banner__title">Install Pow Lee on your phone</div>
          <div className="install-banner__sub">
            Faster open, works offline, receive push alerts when a job is assigned.
          </div>
        </div>
        <div className="install-banner__actions">
          <button className="btn btn--primary btn--sm" onClick={handleInstall}>
            <Download size={14}/> Install
          </button>
          <button className="install-banner__close" onClick={handleDismiss} aria-label="Dismiss">
            <X size={16}/>
          </button>
        </div>
      </div>

      {showIosHint ? (
        <div className="install-modal" onClick={() => setShowIosHint(false)}>
          <div className="install-modal__card" onClick={(e) => e.stopPropagation()}>
            <div style={{display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16}}>
              <img src="assets/icon-192.png" alt="" width="44" height="44" style={{borderRadius: 8}}/>
              <div>
                <div style={{fontWeight: 700, fontSize: 16}}>Install on iPhone / iPad</div>
                <div style={{fontSize: 13, color: 'var(--color-grey-500)'}}>3 quick steps in Safari</div>
              </div>
              <button className="install-banner__close" style={{marginLeft: 'auto'}} onClick={() => setShowIosHint(false)} aria-label="Close">
                <X size={18}/>
              </button>
            </div>

            <ol className="install-steps">
              <li>
                <span className="install-steps__num">1</span>
                <div>
                  <div className="install-steps__title">Tap the Share button</div>
                  <div className="install-steps__desc">It's the square with an up-arrow at the bottom of Safari.</div>
                </div>
              </li>
              <li>
                <span className="install-steps__num">2</span>
                <div>
                  <div className="install-steps__title">Choose “Add to Home Screen”</div>
                  <div className="install-steps__desc">Scroll down in the Share menu — it has a + icon.</div>
                </div>
              </li>
              <li>
                <span className="install-steps__num">3</span>
                <div>
                  <div className="install-steps__title">Tap “Add”</div>
                  <div className="install-steps__desc">The Pow Lee icon appears on your home screen — tap it to launch fullscreen.</div>
                </div>
              </li>
            </ol>

            <div style={{padding: 12, background: 'var(--color-grey-50)', borderRadius: 8, fontSize: 12, color: 'var(--color-grey-700)', marginTop: 16, lineHeight: 1.5}}>
              <strong>Note:</strong> iPhone push notifications require iOS 16.4 or later, and only work after the app is installed to the home screen.
            </div>
          </div>
        </div>
      ) : null}
    </>
  );
}

Object.assign(window, { InstallPrompt });
