import React, { useState, useEffect } from 'react';
import './InstallBanner.css';

const DISMISSED_KEY = 'pwa-install-dismissed';

function isIOS() {
  return /iphone|ipad|ipod/i.test(navigator.userAgent) && !window.MSStream;
}

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

export default function InstallBanner() {
  const [deferredPrompt, setDeferredPrompt] = useState(null);
  const [showAndroid, setShowAndroid] = useState(false);
  const [showIOS, setShowIOS] = useState(false);

  useEffect(() => {
    if (isInStandaloneMode()) return;
    if (localStorage.getItem(DISMISSED_KEY)) return;

    if (isIOS()) {
      setShowIOS(true);
      return;
    }

    const handler = (e) => {
      e.preventDefault();
      setDeferredPrompt(e);
      setShowAndroid(true);
    };
    window.addEventListener('beforeinstallprompt', handler);
    return () => window.removeEventListener('beforeinstallprompt', handler);
  }, []);

  const handleInstall = async () => {
    if (!deferredPrompt) return;
    deferredPrompt.prompt();
    const { outcome } = await deferredPrompt.userChoice;
    if (outcome === 'accepted') {
      setShowAndroid(false);
    }
    setDeferredPrompt(null);
  };

  const dismiss = () => {
    localStorage.setItem(DISMISSED_KEY, '1');
    setShowAndroid(false);
    setShowIOS(false);
  };

  if (!showAndroid && !showIOS) return null;

  return (
    <div className="install-banner" role="banner">
      <div className="install-banner__content">
        {showAndroid && (
          <>
            <span className="install-banner__text">
              📲 App auf dem Homescreen installieren
            </span>
            <button className="install-banner__btn" onClick={handleInstall}>
              Installieren
            </button>
          </>
        )}
        {showIOS && (
          <span className="install-banner__text">
            📲 Zum Homescreen hinzufügen:{' '}
            <strong>Teilen</strong>
            {' '}
            <span className="install-banner__share-icon" aria-label="Teilen-Icon">⬆️</span>
            {' '}→{' '}
            <strong>„Zum Home-Bildschirm"</strong>
          </span>
        )}
        <button
          className="install-banner__close"
          onClick={dismiss}
          aria-label="Banner schließen"
        >
          ✕
        </button>
      </div>
    </div>
  );
}
