import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { Inspector, InspectorSelectField, Select } from "../packages/ui-react/dist/index.js";

test("InspectorSelectField renders a stacked label and split control", () => {
  const markup = renderToStaticMarkup(createElement(InspectorSelectField, {
    label: "Профиль покрытия",
    value: "profile-1",
    options: [{ value: "profile-1", label: "Профиль 1 · 80 м" }],
    onChange: () => {},
  }));

  assert.match(markup, /class="nodedc-control-row" data-layout="stack"/);
  assert.match(markup, /class="nodedc-control-row__label">Профиль покрытия</);
  assert.match(markup, /class="nodedc-select__value"/);
  assert.match(markup, /class="nodedc-select__toggle"/);
  assert.match(markup, /aria-label="Профиль покрытия"/);
  assert.doesNotMatch(markup, /class="[^"]*\bnodedc-select-trigger(?:\s|\")/);

  assert.ok(
    markup.indexOf("nodedc-control-row__label") < markup.indexOf("nodedc-select__control"),
    "the visible Inspector label must precede the split control",
  );
});

test("Inspector hard-forces a raw integrated Select to the split presentation", () => {
  const markup = renderToStaticMarkup(createElement(Inspector, {
    defaultOpen: ["selection"],
    sections: [{
      id: "selection",
      label: "Selection",
      content: createElement(Select, {
        variant: "integrated",
        label: "Нарушающий consumer",
        value: "one",
        options: [{ value: "one", label: "One" }],
        onChange: () => {},
      }),
    }],
  }));

  assert.match(markup, /class="nodedc-select__value"/);
  assert.match(markup, /class="nodedc-select__toggle"/);
  assert.doesNotMatch(markup, /class="[^"]*\bnodedc-select-trigger(?:\s|\")/);
});

test("Foundry Inspector screens consume the semantic selection field", async () => {
  const [mapPreview, catalog, coreStyles] = await Promise.all([
    readFile(new URL("../apps/catalog/src/MapFixturePreview.tsx", import.meta.url), "utf8"),
    readFile(new URL("../apps/catalog/src/CatalogApp.tsx", import.meta.url), "utf8"),
    readFile(new URL("../packages/ui-core/styles.css", import.meta.url), "utf8"),
  ]);

  assert.match(mapPreview, /<InspectorSelectField\s+label="Профиль покрытия"/);
  assert.doesNotMatch(mapPreview, /<ControlRow label="Профиль покрытия">/);
  assert.equal((catalog.match(/<InspectorSelectField/g) ?? []).length, 2);
  assert.match(coreStyles, /\.nodedc-inspector \.nodedc-control-row:has\(\.nodedc-select-anchor\)/);
});
