import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Empty frontmatter preserves the following heading and horizontal rule", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("markdown-demo", {
    "empty-frontmatter.md": "---\n---\n# Visible heading\n\n---\nVisible paragraph\n",
    "control.md": "---\ntitle: x\n---\n# Control heading\n\n---\nControl paragraph\n",
  });
  const thread = await t3.thread({ project, title: "Markdown preview", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Files", { exact: true }).tap();
  const openFile = async (path: string) => {
    await browser.evaluate((path) => {
      for (const host of document.querySelectorAll("*")) {
        const row = host.shadowRoot?.querySelector<HTMLElement>(`[data-item-path="${path}"]`);
        if (row) { row.click(); return; }
      }
      throw new Error("File row not loaded: " + path);
    }, path);
  };
  await screen.getByRole("button", "Refresh workspace files").waitFor();
  await openFile("control.md");
  await screen.getByRole("button", "Show rendered markdown", { exact: true }).tap();
  await screen.getByRole("heading", "Control heading", { exact: true }).waitFor();
  await screen.getByText("Control paragraph", { exact: true }).waitFor();
  await app.screenshot("control-rendered");
  await screen.getByRole("button", "Show markdown source", { exact: true }).tap();
  await openFile("empty-frontmatter.md");
  await screen.getByRole("button", "Show rendered markdown", { exact: true }).waitFor();
  await app.screenshot("empty-frontmatter-source");
  await screen.getByRole("button", "Show rendered markdown", { exact: true }).tap();
  await screen.getByText("Visible paragraph", { exact: true }).waitFor();
  await app.screenshot("empty-frontmatter-rendered");
  await expect(screen.getByRole("heading", "Visible heading", { exact: true })).toBeVisible();
  await expect(browser.locator('[data-right-panel-surface-content] hr')).toHaveCount(1);
});
