import { describe, it, expect, vi, afterEach } from 'vitest';
import { registerAcmsElements } from './register';

const TAG_NAMES = [
  'acms-tag-select',
  'acms-category-select',
  'acms-sub-category-select',
  'acms-related-entry-editor',
  'acms-unit-editor',
  'acms-unit-inplace-editor',
  'acms-unit-config-editor',
  'acms-block-editor',
  'acms-block-editor-menu-type-select',
];

describe('registerAcmsElements', () => {
  afterEach(() => {
    vi.restoreAllMocks();
  });

  it('9つのカスタム要素を登録する', () => {
    registerAcmsElements();

    TAG_NAMES.forEach((tagName) => {
      expect(customElements.get(tagName)).toBeDefined();
    });
  });

  it('複数回呼び出しても例外にならない（冪等）', () => {
    registerAcmsElements();
    expect(() => registerAcmsElements()).not.toThrow();
  });

  it('既に登録済みのタグ名は define し直さない', () => {
    registerAcmsElements();
    const defineSpy = vi.spyOn(customElements, 'define');

    registerAcmsElements();

    expect(defineSpy).not.toHaveBeenCalled();
  });

  it('9つのタグすべてに display: contents を当てる style を head へ注入する', () => {
    registerAcmsElements();

    const style = document.getElementById('acms-elements-host-display-contents');
    expect(style).toBeInstanceOf(HTMLStyleElement);
    TAG_NAMES.forEach((tagName) => {
      expect(style?.textContent).toContain(tagName);
    });
    expect(style?.textContent).toContain('display: contents');
  });

  it('複数回呼び出しても style タグを重複注入しない', () => {
    registerAcmsElements();
    registerAcmsElements();

    const styles = document.querySelectorAll('#acms-elements-host-display-contents');
    expect(styles.length).toBe(1);
  });
});
