// pwa-update.jsx — Banner "Đã có bản cập nhật" cho PWA.
// Lắng nghe 'swo:update-ready' (phát từ index.html khi service worker phát hiện
// phiên bản mới). Bấm "Cập nhật" → window.__swoUpdate.apply() (postMessage
// SKIP_WAITING) → SW mới kích hoạt → controllerchange → trang tự reload.
function PwaUpdateBanner() {
  const { t } = useLang();
  const [show, setShow] = React.useState(false);
  const [busy, setBusy] = React.useState(false);

  React.useEffect(() => {
    if (window.__swoUpdate) setShow(true);            // bản mới đã sẵn trước khi mount
    const onReady = () => setShow(true);
    window.addEventListener('swo:update-ready', onReady);
    return () => window.removeEventListener('swo:update-ready', onReady);
  }, []);

  if (!show) return null;

  const apply = () => {
    setBusy(true);
    if (window.__swoUpdate && window.__swoUpdate.apply) window.__swoUpdate.apply();
    else window.location.reload();                    // fallback nếu thiếu hook
  };

  return (
    <div className="pwa-update" role="status" aria-live="polite">
      <i className="bi bi-arrow-repeat" aria-hidden="true"></i>
      <div className="pwa-update-text">
        <strong>{t('pwa.title')}</strong>
        <span className="muted">{t('pwa.sub')}</span>
      </div>
      <div className="pwa-update-actions">
        <button className="btn btn-ghost btn-sm" onClick={() => setShow(false)} disabled={busy}>{t('pwa.later')}</button>
        <button className="btn btn-primary btn-sm" onClick={apply} disabled={busy}>
          {busy && <i className="bi bi-arrow-repeat spin" aria-hidden="true"></i>}{t('pwa.update')}
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { PwaUpdateBanner });
