import { render, screen } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import { describe, expect, it, vi } from "vitest"

import { Button } from "@/shared/ui/button"

describe("Button", () => {
  it("uses the shared primary and interaction states by default", () => {
    render(<Button>执行调度</Button>)

    const button = screen.getByRole("button", { name: "执行调度" })
    expect(button).toHaveAttribute("data-slot", "button")
    expect(button.className).toContain("bg-[var(--action-blue)]")
    expect(button.className).toContain("focus-visible:ring-[var(--action-focus-ring)]")
    expect(button.className).toContain("[&:active:not(:disabled)]:bg-[var(--action-blue-pressed)]")
    expect(button.className).toContain(
      "[&:active:not(:disabled)]:shadow-[var(--action-shadow-primary-pressed)]"
    )
    expect(button.className).not.toContain("translate-y")
  })

  it("keeps compact controls visually small with an expanded hit target", () => {
    render(
      <Button aria-label="刷新" size="icon-sm" variant="ghost">
        R
      </Button>
    )

    const button = screen.getByRole("button", { name: "刷新" })
    expect(button.className).toContain("h-8")
    expect(button.className).toContain("w-8")
    expect(button.className).toContain("after:-inset-1")
  })

  it("exposes a stable and inaccessible-to-repeat loading state", async () => {
    const onClick = vi.fn()
    const user = userEvent.setup()

    render(
      <Button loading loadingLabel="正在提交调度" onClick={onClick}>
        提交调度
      </Button>
    )

    const button = screen.getByRole("button", { name: /提交调度/ })
    expect(button).toBeDisabled()
    expect(button).toHaveAttribute("aria-busy", "true")
    expect(button).toHaveAttribute("data-loading", "true")
    expect(screen.getByText("正在提交调度")).toHaveClass("sr-only")

    await user.click(button)
    expect(onClick).not.toHaveBeenCalled()
  })

  it("preserves asChild composition", () => {
    render(
      <Button asChild variant="link">
        <a href="/sessions">查看会话</a>
      </Button>
    )

    const link = screen.getByRole("link", { name: "查看会话" })
    expect(link).toHaveAttribute("href", "/sessions")
    expect(link).toHaveAttribute("data-slot", "button")
  })

  it("blocks and labels loading asChild links", async () => {
    const onClick = vi.fn()
    const user = userEvent.setup()
    render(
      <Button asChild loading loadingLabel="正在打开会话" onClick={onClick}>
        <a href="/sessions">查看会话</a>
      </Button>
    )

    const link = screen.getByRole("link", { name: "正在打开会话" })
    expect(link).toHaveAttribute("aria-busy", "true")
    expect(link).toHaveAttribute("aria-disabled", "true")
    expect(link).toHaveAttribute("tabindex", "-1")
    await user.click(link)
    expect(onClick).not.toHaveBeenCalled()
  })
})
