import { act, renderHook } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useInstallPrompt } from "./useInstallPrompt";

const DISMISSED_KEY = "pwa-install-dismissed";

describe("useInstallPrompt", () => {
  beforeEach(() => {
    localStorage.clear();
  });

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

  it("starts with canInstall false and isStandalone false", () => {
    const { result } = renderHook(() => useInstallPrompt());
    expect(result.current.canInstall).toBe(false);
    expect(result.current.isStandalone).toBe(false);
    expect(result.current.isDismissed).toBe(false);
  });

  it("captures beforeinstallprompt event and sets canInstall to true", () => {
    const { result } = renderHook(() => useInstallPrompt());

    const event = new Event("beforeinstallprompt");
    Object.assign(event, { preventDefault: vi.fn(), prompt: vi.fn() });

    act(() => {
      window.dispatchEvent(event);
    });

    expect(result.current.canInstall).toBe(true);
  });

  it("dismiss persists to localStorage and sets isDismissed", () => {
    const { result } = renderHook(() => useInstallPrompt());

    act(() => {
      result.current.dismiss();
    });

    expect(result.current.isDismissed).toBe(true);
    expect(localStorage.getItem(DISMISSED_KEY)).toBe("true");
  });

  it("reads dismissed state from localStorage on mount", () => {
    localStorage.setItem(DISMISSED_KEY, "true");
    const { result } = renderHook(() => useInstallPrompt());
    expect(result.current.isDismissed).toBe(true);
  });

  it("detects iOS Safari", () => {
    vi.spyOn(navigator, "userAgent", "get").mockReturnValue(
      "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1"
    );
    const { result } = renderHook(() => useInstallPrompt());
    expect(result.current.isIOS).toBe(true);
  });
});
