import { describe, expect, it } from 'vitest';
import { canCheckWord, dictionaryLookupUrl, MAX_WORD_LEN, sanitizeCheckWord } from './checkword';

const EN = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');

describe('sanitizeCheckWord', () => {
  it('upper-cases and keeps only letters of the alphabet', () => {
    expect(sanitizeCheckWord('ca7t!', EN)).toBe('CAT');
    expect(sanitizeCheckWord('  Hi 9 ', EN)).toBe('HI');
  });

  it('drops characters outside the active alphabet', () => {
    expect(sanitizeCheckWord('cat', ['C', 'A'])).toBe('CA'); // T not in this alphabet
    const RU = 'КОТ'.split('');
    expect(sanitizeCheckWord('коt', RU)).toBe('КО'); // cyrillic kept, latin "t" dropped
  });

  it('caps the length at MAX_WORD_LEN', () => {
    expect(sanitizeCheckWord('A'.repeat(30), EN)).toHaveLength(MAX_WORD_LEN);
  });
});

describe('canCheckWord', () => {
  it('allows a fresh, in-range word', () => {
    expect(canCheckWord('CAT', false, false)).toBe(true);
  });

  it('rejects an out-of-range length', () => {
    expect(canCheckWord('A', false, false)).toBe(false); // too short
    expect(canCheckWord('A'.repeat(MAX_WORD_LEN + 1), false, false)).toBe(false); // too long
  });

  it('rejects an already-checked word or a cooling-down state', () => {
    expect(canCheckWord('CAT', true, false)).toBe(false);
    expect(canCheckWord('CAT', false, true)).toBe(false);
  });

  it('trims surrounding whitespace before measuring length', () => {
    expect(canCheckWord('  ok  ', false, false)).toBe(true);
    expect(canCheckWord('  a  ', false, false)).toBe(false);
  });
});

describe('dictionaryLookupUrl', () => {
  it('points the Russian variants at gramota.ru with a lower-cased, encoded query', () => {
    expect(dictionaryLookupUrl('КОТ', 'scrabble_ru')).toBe(
      'https://gramota.ru/poisk?query=' + encodeURIComponent('кот'),
    );
    expect(dictionaryLookupUrl('ЭРА', 'erudit_ru')).toBe(
      'https://gramota.ru/poisk?query=' + encodeURIComponent('эра'),
    );
  });

  it('points English at scrabblewordfinder.org with a lower-cased path', () => {
    expect(dictionaryLookupUrl('CAT', 'scrabble_en')).toBe('https://scrabblewordfinder.org/dictionary/cat');
  });
});
