import { describe, expect, it } from "vitest";
import { render } from "@testing-library/react";
import { autolink } from "./autolink";

describe("autolink", () => {
  it("returns empty array for empty input", () => {
    expect(autolink("")).toEqual([]);
  });

  it("returns plain text when no urls", () => {
    const { container } = render(<>{autolink("普通文本，没有链接")}</>);
    expect(container.textContent).toBe("普通文本，没有链接");
    expect(container.querySelector("a")).toBeNull();
  });

  it("wraps a single https url in an anchor with safe attrs", () => {
    const { container } = render(<>{autolink("点 https://x.com/path 看")}</>);
    const anchor = container.querySelector("a");
    expect(anchor).not.toBeNull();
    expect(anchor?.getAttribute("href")).toBe("https://x.com/path");
    expect(anchor?.getAttribute("target")).toBe("_blank");
    expect(anchor?.getAttribute("rel")).toBe("noopener noreferrer");
    expect(container.textContent).toBe("点 https://x.com/path 看");
  });

  it("handles multiple urls in one string", () => {
    const { container } = render(
      <>{autolink("a https://a.com b https://b.com c")}</>,
    );
    const anchors = container.querySelectorAll("a");
    expect(anchors).toHaveLength(2);
    expect(anchors[0].getAttribute("href")).toBe("https://a.com");
    expect(anchors[1].getAttribute("href")).toBe("https://b.com");
  });

  it("trims trailing punctuation outside the url", () => {
    const { container } = render(<>{autolink("see https://x.com.")}</>);
    const anchor = container.querySelector("a");
    expect(anchor?.getAttribute("href")).toBe("https://x.com");
    expect(container.textContent).toBe("see https://x.com.");
  });
});
