import assert from 'node:assert/strict';
import test from 'node:test';

import { HELP_SECTION_IDS, helpSectionBodyKey, helpSectionTitleKey } from '../help/helpSections';

import { EDITOR_MESSAGES, inferEditorLocaleFromSystem, normalizeEditorLocale } from './editorMessages';

void test('inferEditorLocaleFromSystem: en-* wins when listed first', () => {
  assert.equal(inferEditorLocaleFromSystem(['en-GB', 'ru-RU']), 'en');
});

void test('inferEditorLocaleFromSystem: ru-* wins when listed first', () => {
  assert.equal(inferEditorLocaleFromSystem(['ru-RU', 'en-US']), 'ru');
});

void test('inferEditorLocaleFromSystem: unknown tags fall back to ru', () => {
  assert.equal(inferEditorLocaleFromSystem(['de-DE', 'fr']), 'ru');
});

void test('inferEditorLocaleFromSystem: empty list → ru', () => {
  assert.equal(inferEditorLocaleFromSystem([]), 'ru');
});

void test('normalizeEditorLocale: trims stored en/ru', () => {
  assert.equal(normalizeEditorLocale(' EN '), 'en');
  assert.equal(normalizeEditorLocale('ru '), 'ru');
});

void test('normalizeEditorLocale: blank or invalid defers to system infer', () => {
  const inferred = inferEditorLocaleFromSystem();
  assert.equal(normalizeEditorLocale(''), inferred);
  assert.equal(normalizeEditorLocale('xx'), inferred);
});

void test('EDITOR_MESSAGES: ru and en have the same keys', () => {
  const ruKeys = Object.keys(EDITOR_MESSAGES.ru).sort();
  const enKeys = Object.keys(EDITOR_MESSAGES.en).sort();
  assert.deepEqual(enKeys, ruKeys);
});

void test('EDITOR_MESSAGES: every help section has title and body in both locales', () => {
  for (const id of HELP_SECTION_IDS) {
    const title = helpSectionTitleKey(id);
    const body = helpSectionBodyKey(id);
    for (const locale of ['ru', 'en'] as const) {
      assert.ok(EDITOR_MESSAGES[locale][title], `missing ${locale} ${title}`);
      assert.ok(EDITOR_MESSAGES[locale][body], `missing ${locale} ${body}`);
      assert.notEqual(EDITOR_MESSAGES[locale][title]!.trim(), '');
      assert.notEqual(EDITOR_MESSAGES[locale][body]!.trim(), '');
    }
  }
});

void test('EDITOR_MESSAGES: materials.* keys exist in both locales', () => {
  const materialKeys = Object.keys(EDITOR_MESSAGES.ru).filter((k) => k.startsWith('materials.'));
  assert.ok(materialKeys.length >= 20, `expected materials.* keys, got ${String(materialKeys.length)}`);
  for (const key of materialKeys) {
    assert.ok(EDITOR_MESSAGES.en[key], `missing en ${key}`);
    assert.notEqual(EDITOR_MESSAGES.en[key]!.trim(), '');
  }
});

void test('EDITOR_MESSAGES: npcs.* keys exist in both locales', () => {
  const npcKeys = Object.keys(EDITOR_MESSAGES.ru).filter((k) => k.startsWith('npcs.'));
  assert.ok(npcKeys.length >= 20, `expected npcs.* keys, got ${String(npcKeys.length)}`);
  for (const key of npcKeys) {
    assert.ok(EDITOR_MESSAGES.en[key], `missing en ${key}`);
    assert.notEqual(EDITOR_MESSAGES.en[key]!.trim(), '');
  }
});
