import { describe, it, expect, vi } from "vitest"
import { render, screen } from "@testing-library/react"
import { DashboardSection, DashboardSectionSkeleton } from "./dashboard-section"

// Mock next-intl to avoid provider setup
vi.mock("next-intl", () => ({
  useTranslations: () => (key: string) => {
    const messages: Record<string, string> = {
      "sectionLoadFailed": "区块加载失败",
      "sectionLoadFailedDesc": "请重试",
      "retry": "重试",
    }
    return messages[key] ?? key
  },
}))

describe("DashboardSectionSkeleton", () => {
  it("renders stats variant with 4 skeleton cards", () => {
    const { container } = render(<DashboardSectionSkeleton variant="stats" />)
    const cards = container.querySelectorAll('[class*="card"]')
    expect(cards.length).toBeGreaterThanOrEqual(4)
  })

  it("renders chart variant with skeleton", () => {
    const { container } = render(<DashboardSectionSkeleton variant="chart" />)
    expect(container.querySelector('[class*="h-[200px]"]')).toBeTruthy()
  })

  it("renders table variant with 5 skeleton rows", () => {
    const { container } = render(<DashboardSectionSkeleton variant="table" />)
    const skeletons = container.querySelectorAll('[class*="h-10"]')
    expect(skeletons.length).toBe(5)
  })

  it("renders card variant by default", () => {
    const { container } = render(<DashboardSectionSkeleton />)
    expect(container.querySelector('[class*="h-4"]')).toBeTruthy()
  })
})

describe("DashboardSection", () => {
  it("renders children when no error", () => {
    render(
      <DashboardSection variant="card">
        <div data-testid="child">Content</div>
      </DashboardSection>
    )
    expect(screen.getByTestId("child")).toBeTruthy()
    expect(screen.getByText("Content")).toBeTruthy()
  })

  it("renders error fallback when child throws", () => {
    const ThrowingChild = (): never => {
      throw new Error("test error")
    }

    // Suppress console.error for this test
    const spy = vi.spyOn(console, "error").mockImplementation(() => {})

    render(
      <DashboardSection variant="card">
        <ThrowingChild />
      </DashboardSection>
    )

    expect(screen.getByText("区块加载失败")).toBeTruthy()
    expect(screen.getByText("重试")).toBeTruthy()
    spy.mockRestore()
  })
})
