import { mount } from '@vue/test-utils';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { nextTick, ref } from 'vue';

const floatingItemIsDisplayed = ref(false);
const showFloatingItem = vi.fn(() => (floatingItemIsDisplayed.value = true));
const hideFloatingItem = vi.fn(() => (floatingItemIsDisplayed.value = false));
const onTriggerKeydown = vi.fn();
const onListboxKeydown = vi.fn();

vi.mock('../sidebar/use-floating-item.composable', () => {
  return {
    useFloatingItem: () => ({
      floatingItemIsDisplayed,
      showFloatingItem,
      hideFloatingItem,
      onTriggerKeydown,
      onListboxKeydown,
    }),
  };
});

import MSidebarShortcuts from './MSidebarShortcuts.vue';
import { EXPANDED_SIDEBAR_KEY } from '../sidebar/MSidebar.const';

beforeEach(() => {
  vi.clearAllMocks();
});

describe('MSidebarShortcuts', () => {
  it('renders expanded view when expanded is true', () => {
    const wrapper = mount(MSidebarShortcuts, {
      props: { menuLabel: 'Shortcuts' },
      global: {
        provide: { [EXPANDED_SIDEBAR_KEY as symbol]: true },
        components: { ViewGridX424: { template: '<svg />' } },
      },
    });

    expect(wrapper.find('section').exists()).toBe(true);
    expect(wrapper.find('.mc-sidebar__trigger').exists()).toBe(false);
  });

  it('renders trigger when collapsed and responds to interactions', async () => {
    const wrapper = mount(MSidebarShortcuts, {
      props: { menuLabel: 'Shortcuts' },
      attachTo: document.body,
      global: {
        provide: { [EXPANDED_SIDEBAR_KEY as symbol]: false },
        components: { ViewGridX424: { template: '<svg />' } },
        stubs: {
          Teleport: true,
        },
      },
    });

    const trigger = wrapper.find('.mc-sidebar__trigger');
    expect(trigger.exists()).toBe(true);

    await trigger.trigger('mouseenter');
    expect(showFloatingItem).toHaveBeenCalled();
    await nextTick();
    expect(trigger.attributes('aria-expanded')).toBe('true');

    await trigger.trigger('mouseleave');
    expect(hideFloatingItem).toHaveBeenCalled();
    await nextTick();
    expect(trigger.attributes('aria-expanded')).toBe('false');

    await trigger.trigger('focus');
    expect(showFloatingItem).toHaveBeenCalled();

    await trigger.trigger('blur');
    expect(hideFloatingItem).toHaveBeenCalled();

    await trigger.trigger('keydown', { key: 'ArrowDown' });
    expect(onTriggerKeydown).toHaveBeenCalled();

    const floating = wrapper.find('.mc-sidebar__floating-item');
    expect(floating.exists()).toBe(true);
    await floating.trigger('keydown', { key: 'Escape' });
    expect(onListboxKeydown).toHaveBeenCalled();

    await floating.trigger('mouseleave');
    expect(hideFloatingItem).toHaveBeenCalled();
  });
});
