/** @jest-environment jsdom */

import { resolveLocaleForElement } from './locale';

describe('resolveLocaleForElement', () => {
  const originalLang = document.documentElement.lang;
  const navigatorLanguageDescriptor = Object.getOwnPropertyDescriptor(window.navigator, 'language');

  afterEach(() => {
    document.documentElement.lang = originalLang;

    if (navigatorLanguageDescriptor) {
      Object.defineProperty(window.navigator, 'language', navigatorLanguageDescriptor);
    }
  });

  it('returns locale from element dataset first', () => {
    document.documentElement.lang = 'fr-FR';
    Object.defineProperty(window.navigator, 'language', {
      value: 'de-DE',
      configurable: true,
    });

    const element = document.createElement('div');
    element.dataset.crtodayLocale = 'uk-UA';

    expect(resolveLocaleForElement(element)).toBe('uk-UA');
  });

  it('falls back to document lang when dataset locale is empty', () => {
    document.documentElement.lang = 'pl-PL';
    Object.defineProperty(window.navigator, 'language', {
      value: 'de-DE',
      configurable: true,
    });

    const element = document.createElement('div');
    element.dataset.crtodayLocale = '  ';

    expect(resolveLocaleForElement(element)).toBe('pl-PL');
  });

  it('falls back to navigator language when no dataset and no document lang', () => {
    document.documentElement.lang = '';
    Object.defineProperty(window.navigator, 'language', {
      value: 'es-ES',
      configurable: true,
    });

    const element = document.createElement('div');

    expect(resolveLocaleForElement(element)).toBe('es-ES');
  });
});
