// Install prompt banner — shows when browser fires beforeinstallprompt.
function InstallPrompt() {
  const [event, setEvent] = React.useState(null);
  const [hidden, setHidden] = React.useState(() => {
    try { return localStorage.getItem('oma-aktif:install-dismissed') === '1'; } catch (e) { return false; }
  });

  React.useEffect(() => {
    const handler = (e) => {
      e.preventDefault();
      setEvent(e);
    };
    window.addEventListener('beforeinstallprompt', handler);
    return () => window.removeEventListener('beforeinstallprompt', handler);
  }, []);

  React.useEffect(() => {
    const installed = () => setEvent(null);
    window.addEventListener('appinstalled', installed);
    return () => window.removeEventListener('appinstalled', installed);
  }, []);

  if (!event || hidden) return null;

  const dismiss = () => {
    setHidden(true);
    try { localStorage.setItem('oma-aktif:install-dismissed', '1'); } catch (e) {}
  };

  const install = async () => {
    OASound.tap();
    try {
      event.prompt();
      const choice = await event.userChoice;
      if (choice.outcome !== 'accepted') dismiss();
      setEvent(null);
    } catch (err) {
      setEvent(null);
    }
  };

  return (
    <div style={{
      position: 'fixed', left: 14, right: 14, top: 'max(14px, env(safe-area-inset-top))',
      maxWidth: 452, margin: '0 auto',
      background: OA_THEME.card,
      border: `2px solid ${OA_THEME.sage}`,
      borderRadius: 20, padding: '12px 14px',
      boxShadow: '0 8px 24px rgba(60,82,76,0.18)',
      display: 'flex', alignItems: 'center', gap: 12,
      zIndex: 50,
      animation: 'oaFadeUp .4s ease',
    }}>
      <div style={{
        width: 44, height: 44, borderRadius: 12,
        background: `radial-gradient(circle at 30% 30%, #A6C3B6, ${OA_THEME.sageDeep})`,
        color: '#fff', fontFamily: 'Lora, serif', fontStyle: 'italic', fontWeight: 600, fontSize: 24,
        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
      }}>O</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 800, fontSize: 16, color: OA_THEME.ink }}>Pasang Oma Aktif</div>
        <div style={{ fontSize: 13, color: OA_THEME.inkSoft }}>Buka cepat dari layar utama Oma.</div>
      </div>
      <button onClick={install} className="oa-no-tap" style={{
        background: OA_THEME.sageDeep, color: '#fff',
        border: 'none', borderRadius: 12,
        padding: '10px 14px', fontWeight: 800, fontSize: 14,
        cursor: 'pointer', boxShadow: `0 3px 0 ${OA_THEME.ink}40`,
      }}>Pasang</button>
      <button onClick={dismiss} className="oa-no-tap" aria-label="Tutup" style={{
        background: 'transparent', border: 'none',
        fontSize: 22, color: OA_THEME.inkSoft, cursor: 'pointer',
        padding: 4, flexShrink: 0,
      }}>✕</button>
    </div>
  );
}

window.InstallPrompt = InstallPrompt;
