import { afterEach, describe, expect, it, vi } from "vitest";
import { onlineRepository } from "./onlineRepository";
import { hasPendingSaveSync } from "./saveSync";
import { useFrontendStore } from "./store";

afterEach(() => {
  vi.restoreAllMocks();
  vi.unstubAllGlobals();
});

describe("offline leaderboard publishing", () => {
  it("keeps earned stats pending without attempting an offline upload", async () => {
    const original = useFrontendStore.getState();
    original.deleteSlot(3);
    expect(original.createSlot(3, "Offline Hunter")).toBe(true);
    original.playSlot(3);
    useFrontendStore.setState({ accountId: "offline-account" });
    useFrontendStore.getState().recordBossVictory("bulldrome", "initiate");
    useFrontendStore.getState().recordAetherAssaultDefeat(18_750, 6, 214.5);
    expect(hasPendingSaveSync(3)).toBe(true);

    vi.stubGlobal("navigator", { onLine: false });
    const write = vi.spyOn(onlineRepository, "writeSave");
    expect(await useFrontendStore.getState().uploadSlot(3)).toBe(false);
    expect(write).not.toHaveBeenCalled();
    expect(useFrontendStore.getState().slots[2].local?.stats.bossKills.bulldrome).toBe(1);
    expect(useFrontendStore.getState().slots[2].local?.stats).toMatchObject({
      highestAetherAssaultScore: 18_750,
      highestAetherAssaultWaveAtBest: 6,
      longestAetherAssaultSecondsAtBest: 214.5,
    });

    useFrontendStore.getState().deleteSlot(3);
    useFrontendStore.setState({
      accountId: original.accountId,
      activeSlotId: original.activeSlotId,
      selectedSlotId: original.selectedSlotId,
      screen: original.screen,
      notice: original.notice,
    });
  });
});
