'use client'; import { Button } from '@/components/ui/Button'; import { Icon } from '@/components/ui/Icon'; import React, { useEffect, useState } from 'react'; interface BeforeInstallPromptEvent extends Event { prompt: () => Promise; userChoice: Promise<{ outcome: 'accepted' | 'dismissed'; platform: string }>; } export function usePWAInstall() { const [deferredPrompt, setDeferredPrompt] = useState(null); const [isInstalled, setIsInstalled] = useState(false); const [isIOS, setIsIOS] = useState(false); useEffect(() => { const isStandalone = window.matchMedia('(display-mode: standalone)').matches || (window.navigator as unknown as { standalone?: boolean }).standalone === true; setIsInstalled(isStandalone); const ua = window.navigator.userAgent.toLowerCase(); setIsIOS(/iphone|ipad|ipod/.test(ua)); const handleBeforeInstallPrompt = (e: Event) => { e.preventDefault(); setDeferredPrompt(e as BeforeInstallPromptEvent); }; const handleAppInstalled = () => { setIsInstalled(true); setDeferredPrompt(null); }; window.addEventListener('beforeinstallprompt', handleBeforeInstallPrompt); window.addEventListener('appinstalled', handleAppInstalled); return () => { window.removeEventListener('beforeinstallprompt', handleBeforeInstallPrompt); window.removeEventListener('appinstalled', handleAppInstalled); }; }, []); const install = async () => { if (!deferredPrompt) return false; await deferredPrompt.prompt(); const { outcome } = await deferredPrompt.userChoice; if (outcome === 'accepted') { setIsInstalled(true); setDeferredPrompt(null); return true; } return false; }; return { isInstallable: Boolean(deferredPrompt), isInstalled, isIOS, install, }; } export const PWAInstallButton: React.FC = () => { const { isInstallable, isInstalled, isIOS, install } = usePWAInstall(); const [showIOSGuide, setShowIOSGuide] = useState(false); if (isInstalled) return null; if (isInstallable) { return ( ); } if (isIOS) { return ( <> {showIOSGuide && (

Install DataStack on iOS

1. Tap the Share icon in Safari.
2. Select Add to Home Screen.

)} ); } return null; }; export const PwaLifecycle: React.FC = () => { const [isOnline, setIsOnline] = useState(true); useEffect(() => { setIsOnline(typeof navigator !== 'undefined' ? navigator.onLine : true); const onOnline = () => setIsOnline(true); const onOffline = () => setIsOnline(false); window.addEventListener('online', onOnline); window.addEventListener('offline', onOffline); if (typeof navigator !== 'undefined' && 'serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js', { scope: '/' }).catch(() => { // Non-fatal in environments without SW origin permissions }); } return () => { window.removeEventListener('online', onOnline); window.removeEventListener('offline', onOffline); }; }, []); if (isOnline) return null; return (
Offline mode — cached shell active
); }; export default PwaLifecycle;