import { afterEach, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { basename, join } from "node:path";
import { tmpdir } from "node:os";
import { buildRouter } from "@wrnexus/router";
import { resolveI18n } from "@wrnexus/i18n";
import { createHandlers, type RuntimeDeps } from "../src/runtime.ts";

const roots: string[] = [];
afterEach(() => roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true })));

test("a component nested in another component's slot keeps its boundary", async () => {
  const root = mkdtempSync(join(tmpdir(), "wrnexus-component-slot-"));
  roots.push(root);
  const app = join(root, "app");
  mkdirSync(join(app, "pages"), { recursive: true });
  mkdirSync(join(app, "components"), { recursive: true });
  writeFileSync(join(app, "pages/index.ts"), "export default () => '';\n");
  writeFileSync(join(app, "components/Card.wrn"), "component Card { view { <slot /> } }\n");
  writeFileSync(join(app, "components/Badge.wrn"), "component Badge { view { <b></b> } }\n");

  const handlers = createHandlers({
    mode: "development",
    hmr: false,
    router: buildRouter(app),
    loadModule: async (file) => {
      if (basename(file) === "Card.wrn") {
        return { render: () => '<article class="card"><slot /></article>' };
      }
      if (basename(file) === "Badge.wrn") {
        return { render: (props: Record<string, string>) => `<b class="badge">${props.label}</b>` };
      }
      return {
        default: () =>
          '<div data-component="Card"><div data-component="Badge" label="x"></div></div>',
      };
    },
    getMiddleware: async () => [],
    assets: { serve: async () => null },
  } satisfies RuntimeDeps);

  const response = await handlers.fetch(new Request("https://example.test/"), {
    upgrade: () => false,
  });
  const html = await response!.text();
  expect(html).toContain('<article class="card">');
  expect(html).toContain('<b class="badge">x</b>');
  expect(html).not.toContain('data-component="Badge"');
});

test("translated text is present in the raw server response", async () => {
  const root = mkdtempSync(join(tmpdir(), "wrnexus-ssr-i18n-"));
  roots.push(root);
  const app = join(root, "app");
  mkdirSync(join(app, "pages"), { recursive: true });
  writeFileSync(join(app, "pages/index.ts"), "export default () => '';\n");

  const handlers = createHandlers({
    mode: "development",
    hmr: false,
    router: buildRouter(app),
    i18n: resolveI18n({ en: { nav: { title: "Navigation" } } }, { default: "en" }),
    loadModule: async () => ({
      default: () => '<nav><span data-t="nav.title"></span></nav>',
    }),
    getMiddleware: async () => [],
    assets: { serve: async () => null },
  } satisfies RuntimeDeps);

  const response = await handlers.fetch(new Request("https://example.test/"), {
    upgrade: () => false,
  });
  const html = await response!.text();
  expect(html).toContain('<span data-t="nav.title">Navigation</span>');
});

test("translated layout text survives document-template rendering", async () => {
  const root = mkdtempSync(join(tmpdir(), "wrnexus-layout-ssr-i18n-"));
  roots.push(root);
  const app = join(root, "app");
  mkdirSync(join(app, "pages"), { recursive: true });
  mkdirSync(join(app, "layouts"), { recursive: true });
  writeFileSync(join(app, "pages/index.ts"), "export default () => '';\n");
  writeFileSync(join(app, "layouts/public.wrn"), "layout Public { view { <slot /> } }\n");
  writeFileSync(
    join(app, "layouts/document.wrn"),
    "layout Document { view { <html><head></head><body><slot /></body></html> } }\n",
  );

  const handlers = createHandlers({
    mode: "development",
    hmr: false,
    router: buildRouter(app),
    i18n: resolveI18n({ en: { nav: { home: "Home" } } }, { default: "en" }),
    loadModule: async (file) => {
      if (basename(file) === "public.wrn") {
        return { render: () => '<nav><span data-t="nav.home"></span></nav>' };
      }
      if (basename(file) === "document.wrn") {
        return { render: () => "<html><head></head><body><slot /></body></html>" };
      }
      return { default: () => "<main>Page</main>", layout: "public" };
    },
    getMiddleware: async () => [],
    assets: { serve: async () => null },
  } satisfies RuntimeDeps);

  const response = await handlers.fetch(new Request("https://example.test/"), {
    upgrade: () => false,
  });
  const html = await response!.text();
  expect(html).toContain('<span data-t="nav.home">Home</span>');
  expect(html).not.toContain('<span data-t="nav.home"></span>');
});
