import { useSyncExternalStore } from "react";
import Snackbar from "@mui/material/Snackbar";
import Button from "@mui/material/Button";
import { subscribeNewVersion, getNewVersion } from "../utils/appVersion";

/**
 * Shows a persistent banner when the server reports a newer build than the one
 * this tab is running (detected via the X-App-Version header in apiFetch). The
 * reload is user-initiated — we never force it, so an in-progress form is safe.
 */
export default function UpdateBanner() {
  const newVersion = useSyncExternalStore(
    subscribeNewVersion,
    getNewVersion,
    () => null,
  );

  return (
    <Snackbar
      open={Boolean(newVersion)}
      anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
      message="Je k dispozici nová verze aplikace."
      action={
        <Button
          color="primary"
          size="small"
          variant="contained"
          onClick={() => window.location.reload()}
        >
          Obnovit
        </Button>
      }
    />
  );
}
