import { afterEach, describe, expect, it } from "vitest";
import { applyResult, removeOrphanedPlaceholders, restore } from "../src/content/filter";
import { DEFAULT_SETTINGS } from "../src/shared/types";

describe("content filtering", () => {
  afterEach(() => document.body.replaceChildren());

  it("collapses toxic content and restores it", () => {
    const element = document.createElement("article");
    document.body.append(element);
    applyResult(element, { requestId: "1", id: "1", textHash: "x", label: "toxic", probability: .91, navigationId: "n" }, DEFAULT_SETTINGS);
    expect(element.style.display).toBe("none");
    expect(document.querySelector("[data-vibeguard-placeholder]")).not.toBeNull();
    restore(element);
    expect(element.style.display).toBe("");
    expect(document.querySelector("[data-vibeguard-placeholder]")).toBeNull();
  });

  it("preserves the original display value when filtering is reconciled repeatedly", () => {
    const element = document.createElement("article");
    document.body.append(element);
    const result = { requestId: "1", id: "1", textHash: "x", label: "toxic" as const, probability: .91, navigationId: "n" };
    applyResult(element, result, DEFAULT_SETTINGS);
    applyResult(element, result, DEFAULT_SETTINGS);
    restore(element);
    expect(element.style.display).toBe("");
  });

  it("removes placeholders no longer paired with the current post element", () => {
    const stale = document.createElement("div");
    const orphan = document.createElement("div");
    orphan.setAttribute("data-vibeguard-placeholder-for", "mastodon:1");
    const current = document.createElement("article");
    const currentPlaceholder = document.createElement("div");
    currentPlaceholder.setAttribute("data-vibeguard-placeholder-for", "mastodon:1");
    document.body.append(stale, orphan, current, currentPlaceholder);
    removeOrphanedPlaceholders("mastodon:1", [current]);
    expect(orphan.isConnected).toBe(false);
    expect(currentPlaceholder.isConnected).toBe(true);
  });
});
