import { useRegisterSW } from "virtual:pwa-register/react";
import styles from "./PwaUpdatePrompt.module.css";

export function PwaUpdatePrompt() {
	const {
		needRefresh: [needRefresh, setNeedRefresh],
		updateServiceWorker,
	} = useRegisterSW({
		onRegistered(registration) {
			if (!registration) return;
			window.setInterval(() => {
				void registration.update();
			}, 60 * 60 * 1000);
		},
		onRegisterError(error) {
			console.error("[PWA] service worker registration failed:", error);
		},
	});

	if (!needRefresh) return null;

	return (
		<div className={styles.bar} role="status" aria-live="polite">
			<div className={styles.text}>发现新版本，更新后即可使用最新功能。</div>
			<div className={styles.actions}>
				<button type="button" className={styles.secondary} onClick={() => setNeedRefresh(false)}>
					稍后
				</button>
				<button
					type="button"
					className={styles.primary}
					onClick={() => void updateServiceWorker(true)}
				>
					立即更新
				</button>
			</div>
		</div>
	);
}
