import { useRegisterSW } from "virtual:pwa-register/react";

/** 检测到新版本 Service Worker 等待激活时提示刷新（需 vite-plugin-pwa registerType: prompt） */
export function PwaUpdatePrompt() {
  const {
    needRefresh: [needRefresh, setNeedRefresh],
    updateServiceWorker,
  } = useRegisterSW({ immediate: true });

  if (!needRefresh) return null;

  return (
    <div className="pwa-update-bar" role="status" aria-live="polite">
      <span className="pwa-update-bar-text">发现新版本，刷新后即可使用最新功能</span>
      <div className="pwa-update-bar-actions">
        <button type="button" className="btn ghost tiny" onClick={() => setNeedRefresh(false)}>
          稍后
        </button>
        <button
          type="button"
          className="btn primary tiny"
          onClick={() => void updateServiceWorker(true)}
        >
          立即刷新
        </button>
      </div>
    </div>
  );
}
