import { describe, expect, it, vi } from "vitest";

import { ArchivedFontLoader, fontFamilyName } from "../../apps/web/src/text-font-loader.js";

describe("TASK-WP4-03 archived FontFace gate", () => {
  it("waits for FontFace load and document.fonts ready before exposing a family", async () => {
    const add = vi.fn();
    const load = vi.fn(async () => ({ family: "Dada_FONT081" }));
    const loader = new ArchivedFontLoader({
      createFace: (family, source) => {
        expect(family).toBe("Dada_FONT081");
        expect(source).toBe("url(\"/api/v1/assets/public/p0a-complex-v1/FONT081\")");
        return { load };
      },
      fontSet: { add, check: () => true, ready: Promise.resolve() },
    });
    await expect(loader.ensure({ fontId: "FONT081", url: "/api/v1/assets/public/p0a-complex-v1/FONT081" })).resolves.toBe("ready");
    expect(load).toHaveBeenCalledOnce();
    expect(add).toHaveBeenCalledOnce();
    expect(loader.status("FONT081")).toBe("ready");
    expect(fontFamilyName("FONT081")).toBe("Dada_FONT081");
  });

  it("marks a missing archived font unavailable without a fallback family", async () => {
    const loader = new ArchivedFontLoader({
      createFace: () => ({ load: async () => { throw new Error("404"); } }),
      fontSet: { add: vi.fn(), check: () => false, ready: Promise.resolve() },
    });
    await expect(loader.ensure({ fontId: "FONT404", url: "/missing.ttf" })).resolves.toBe("unavailable");
    expect(loader.status("FONT404")).toBe("unavailable");
    expect(fontFamilyName("FONT404")).not.toContain(",");
    expect(fontFamilyName("FONT404")).not.toMatch(/Arial|sans-serif|YaHei/i);
  });
});
