import { describe, it, expect, vi } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
import { FluentProvider, webLightTheme } from "@fluentui/react-components";
import { AutoSaveIndicator } from "../AutoSaveIndicator";

function renderIndicator(props: Parameters<typeof AutoSaveIndicator>[0]) {
  return render(
    <FluentProvider theme={webLightTheme}>
      <AutoSaveIndicator {...props} />
    </FluentProvider>,
  );
}

describe("AutoSaveIndicator", () => {
  it("renders aria-live region when idle with no visible text", () => {
    renderIndicator({ status: "idle" });
    const region = screen.getByRole("status");
    expect(region).toBeInTheDocument();
    expect(region).toHaveAttribute("aria-live", "polite");
    // No visible text content for idle
    expect(region.textContent).toBe("");
  });

  it("shows spinner and Saving text when saving", () => {
    renderIndicator({ status: "saving" });
    expect(screen.getByText(/saving/i)).toBeInTheDocument();
  });

  it("shows Saved badge when saved", () => {
    renderIndicator({ status: "saved" });
    expect(screen.getByText(/saved/i)).toBeInTheDocument();
  });

  it("shows error text when status is error", () => {
    renderIndicator({ status: "error", errorText: "Network error" });
    expect(screen.getByText(/network error/i)).toBeInTheDocument();
  });

  it("shows fallback error text when errorText is null", () => {
    renderIndicator({ status: "error", errorText: null });
    expect(screen.getByText(/save failed/i)).toBeInTheDocument();
  });

  it("calls onRetry when retry button is clicked", () => {
    const onRetry = vi.fn();
    renderIndicator({ status: "error", errorText: "Oops", onRetry });
    const retryBtn = screen.getByRole("button", { name: /retry/i });
    fireEvent.click(retryBtn);
    expect(onRetry).toHaveBeenCalledOnce();
  });
});
