import { describe, test, expect, beforeEach, vi } from 'vitest';
import setupGoogleMapsPicker from '@ablogcms/lib/google-maps-picker';
import dispatchGoogleMapsPicker from './dispatch-google-maps-picker';

vi.mock('@ablogcms/lib/google-maps-picker', () => ({
  default: vi.fn(),
}));

describe('dispatchGoogleMapsPicker', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    document.body.innerHTML = '';
    const win = window as unknown as { ACMS: { Config?: Record<string, unknown> } };
    win.ACMS.Config = {
      ...(win.ACMS.Config ?? {}),
      fieldgroupSortableItemTemplateMark: '.item-template',
    };
  });

  test('対象要素が無い場合は何もしない', async () => {
    await dispatchGoogleMapsPicker();

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

  test('すべての .js-map-editable 要素を初期化する', async () => {
    document.body.innerHTML = `
      <div class="js-map-editable" id="map-1"></div>
      <div class="js-map-editable" id="map-2"></div>
    `;

    await dispatchGoogleMapsPicker();

    expect(setupGoogleMapsPicker).toHaveBeenCalledTimes(2);
    expect(setupGoogleMapsPicker).toHaveBeenCalledWith(document.getElementById('map-1'));
    expect(setupGoogleMapsPicker).toHaveBeenCalledWith(document.getElementById('map-2'));
  });

  test('フィールドグループのテンプレート内の要素は初期化しない', async () => {
    document.body.innerHTML = `
      <div class="item-template">
        <div class="js-map-editable" id="map-in-template"></div>
      </div>
      <div class="js-map-editable" id="map-outside"></div>
    `;

    await dispatchGoogleMapsPicker();

    expect(setupGoogleMapsPicker).toHaveBeenCalledTimes(1);
    expect(setupGoogleMapsPicker).toHaveBeenCalledWith(document.getElementById('map-outside'));
  });

  test('context を指定した場合はその要素内だけを初期化する', async () => {
    document.body.innerHTML = `
      <div id="scope">
        <div class="js-map-editable" id="map-in-scope"></div>
      </div>
      <div class="js-map-editable" id="map-out-of-scope"></div>
    `;

    await dispatchGoogleMapsPicker(document.getElementById('scope')!);

    expect(setupGoogleMapsPicker).toHaveBeenCalledTimes(1);
    expect(setupGoogleMapsPicker).toHaveBeenCalledWith(document.getElementById('map-in-scope'));
  });
});
