import test from "node:test";
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";

test("settings consolidates account controls behind one account management page", async () => {
  const [settings, accountManagement, css] = await Promise.all([
    readFile(new URL("../context/SettingsWindow.jsx", import.meta.url), "utf8"),
    readFile(new URL("./AccountManagementPage.jsx", import.meta.url), "utf8").catch(() => ""),
    readFile(new URL("../context/context.css", import.meta.url), "utf8")
  ]);

  assert.match(settings, /const \[accountManagementOpen, setAccountManagementOpen\] = useState\(false\)/);
  assert.match(settings, /useBackLayer\(accountManagementOpen, \(\) => setAccountManagementOpen\(false\), "settings-account-management"\)/);
  assert.match(settings, /if \(accountManagementOpen\) return <AccountManagementPage/);
  assert.match(settings, /t\("settings\.accountManagement"\)/);
  assert.match(settings, /setAccountManagementOpen\(true\)/);
  assert.equal(settings.match(/setAccountManagementOpen\(true\)/g)?.length, 1);
  assert.doesNotMatch(settings, /<AccountsPanel/);
  assert.doesNotMatch(settings, /<ProSettingsSection/);
  assert.doesNotMatch(settings, /t\("settings\.viewUsage"\)/);
  assert.doesNotMatch(settings, /t\("settings\.accountMosaic"\)/);
  assert.doesNotMatch(settings, /t\("settings\.conversationAccountVisible"\)/);
  assert.ok(settings.indexOf("if (usageOpen)") < settings.indexOf("if (accountManagementOpen)"), "usage renders above account management while both layers stay open");
  assert.match(settings, /onUsageOpen=\{\(\) => setUsageOpen\(true\)\}/);
  assert.match(settings, /onBack=\{closeAccountManagement\}/);

  const accountsIndex = accountManagement.indexOf("<AccountsPanel");
  const proIndex = accountManagement.indexOf("<ProSettingsSection");
  const usageIndex = accountManagement.indexOf('t("settings.viewUsage")');
  const mosaicIndex = accountManagement.indexOf('t("settings.accountMosaic")');
  const conversationAccountIndex = accountManagement.indexOf('t("settings.conversationAccountVisible")');

  assert.ok(accountsIndex >= 0, "account list is shown in account management");
  assert.ok(proIndex > accountsIndex, "Pro controls follow the account list");
  assert.ok(usageIndex > proIndex, "usage navigation follows Pro controls");
  assert.ok(mosaicIndex > usageIndex, "account mosaic setting follows usage");
  assert.ok(conversationAccountIndex > mosaicIndex, "last-chat account setting follows mosaic");
  assert.match(accountManagement, /className="settings-page account-management-page"/);
  assert.match(accountManagement, /className="settings-content account-management-content"/);
  assert.match(accountManagement, /onClick=\{onUsageOpen\}/);
  assert.match(accountManagement, /onClick=\{onBack\}/);
  assert.match(css, /\.settings-content\{[^}]*overflow:auto[^}]*height:100%/s);
  assert.match(css, /\.settings-select,\.settings-action\{[^}]*min-height:48px/s);
});
