// @vitest-environment jsdom
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { SharePanel } from "./SharePanel.js";

vi.mock("@/i18n/provider.js", () => ({
  useTranslation: () => ({ t: (k: string) => k }),
}));

describe("SharePanel", () => {
  let writeTextMock: ReturnType<typeof vi.fn>;

  beforeEach(() => {
    writeTextMock = vi.fn().mockResolvedValue(undefined);
    Object.defineProperty(navigator, "clipboard", {
      value: { writeText: writeTextMock },
      writable: true,
      configurable: true,
    });
  });

  it("renders 3 social links for en locale (no Weibo)", () => {
    render(<SharePanel url="https://example.com/flight" locale="en" onClose={() => {}} />);
    expect(screen.getByTestId("share-facebook")).toBeTruthy();
    expect(screen.getByTestId("share-vk")).toBeTruthy();
    expect(screen.getByTestId("share-twitter")).toBeTruthy();
    expect(screen.queryByTestId("share-weibo")).toBeNull();
  });

  it("renders 4 social links for zh locale (includes Weibo)", () => {
    render(<SharePanel url="https://example.com/flight" locale="zh" onClose={() => {}} />);
    expect(screen.getByTestId("share-facebook")).toBeTruthy();
    expect(screen.getByTestId("share-vk")).toBeTruthy();
    expect(screen.getByTestId("share-twitter")).toBeTruthy();
    expect(screen.getByTestId("share-weibo")).toBeTruthy();
  });

  it("Facebook href contains encoded URL", () => {
    render(<SharePanel url="https://example.com/flight?a=1" locale="en" onClose={() => {}} />);
    const link = screen.getByTestId("share-facebook") as HTMLAnchorElement;
    expect(link.href).toContain(encodeURIComponent("https://example.com/flight?a=1"));
  });

  it("copy button calls navigator.clipboard.writeText and onClose", async () => {
    const onClose = vi.fn();
    render(<SharePanel url="https://example.com/flight" locale="en" onClose={onClose} />);
    fireEvent.click(screen.getByTestId("share-copy"));
    await waitFor(() => {
      expect(writeTextMock).toHaveBeenCalledWith("https://example.com/flight");
    });
    await waitFor(() => {
      expect(onClose).toHaveBeenCalled();
    });
  });
});
