import { describe, expect, it, vi } from "vitest";
import { render, screen, fireEvent } from "@testing-library/svelte";
import ErrorBoundary from "./ErrorBoundary.svelte";

describe("ErrorBoundary", () => {
  it("renders with default title and message", () => {
    render(ErrorBoundary);

    expect(screen.getByText("Something went wrong")).toBeInTheDocument();
    expect(
      screen.getByText("An unexpected error occurred"),
    ).toBeInTheDocument();
  });

  it("renders with custom title and message", () => {
    render(ErrorBoundary, {
      props: {
        title: "Custom Error",
        message: "Something specific happened",
      },
    });

    expect(screen.getByText("Custom Error")).toBeInTheDocument();
    expect(screen.getByText("Something specific happened")).toBeInTheDocument();
  });

  it("renders error icon", () => {
    const { container } = render(ErrorBoundary);

    expect(container.querySelector(".error-icon")).toBeInTheDocument();
  });

  it("renders Retry button and Go Home link", () => {
    render(ErrorBoundary);

    expect(screen.getByText("Retry")).toBeInTheDocument();
    expect(screen.getByText("Go Home")).toBeInTheDocument();
  });

  it("shows details toggle when details are provided", () => {
    render(ErrorBoundary, {
      props: {
        details: { error: "stack trace" },
      },
    });

    expect(screen.getByText("Show Error Details")).toBeInTheDocument();
  });

  it("does not show details toggle when no details", () => {
    render(ErrorBoundary);

    expect(screen.queryByText("Show Error Details")).not.toBeInTheDocument();
  });

  it("toggles error details on click", async () => {
    render(ErrorBoundary, {
      props: {
        details: { error: "stack trace" },
      },
    });

    const toggle = screen.getByText("Show Error Details");
    await fireEvent.click(toggle);

    expect(screen.getByText("Hide Error Details")).toBeInTheDocument();
    expect(screen.getByText("Error Information")).toBeInTheDocument();
  });

  it("Go Home link points to /", () => {
    render(ErrorBoundary);

    const homeLink = screen.getByText("Go Home");
    expect(homeLink).toHaveAttribute("href", "/");
  });

  it("logs error details on mount", () => {
    const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});

    render(ErrorBoundary, {
      props: {
        details: { key: "value" },
      },
    });

    expect(consoleSpy).toHaveBeenCalledWith("Error details:", {
      key: "value",
    });
    consoleSpy.mockRestore();
  });
});
