import { describe, expect, test } from "bun:test";
import {
  createBlurPlaceholder,
  createCdnImageLoader,
  createPathImageLoader,
  createPicture,
  imagePreload,
} from "../src/index.ts";

describe("image package kit", () => {
  test("creates AVIF/WebP picture plans and preload hints", () => {
    const picture = createPicture({
      src: "/hero.jpg",
      alt: "Hero",
      width: 1200,
      height: 630,
      widths: [480, 768, 1200],
      formats: ["avif", "webp"],
    });
    expect(picture.sources.map((source) => source.type)).toEqual(["image/avif", "image/webp"]);
    expect(imagePreload(picture.image)).toContain('rel="preload"');
  });

  test("requires HTTPS CDN endpoints and safe placeholder colors", () => {
    expect(() => createCdnImageLoader("http://images.example.test")).toThrow();
    expect(() => createBlurPlaceholder({ color: 'url("javascript:alert(1)")' })).toThrow();
    expect(createBlurPlaceholder({ color: "#fff", accent: "var(--wire-color-surface)" })).toMatch(
      /^data:image\/svg\+xml/,
    );
  });

  test("keeps query parameters before URL fragments and rejects invalid dimensions", () => {
    const picture = createPicture({
      src: "/hero.jpg#preview",
      alt: "Hero",
      width: 640,
      height: 360,
    });
    expect(picture.image.src).toContain("?w=640");
    expect(picture.image.src.endsWith("#preview")).toBe(true);
    expect(() => createBlurPlaceholder({ width: Number.NaN })).toThrow("finite");
  });

  test("encodes source paths in the local loader", () => {
    const loader = createPathImageLoader();
    expect(loader({ src: "/images/hero one.jpg", width: 640 })).toContain(
      encodeURIComponent("/images/hero one.jpg"),
    );
  });
});
