import { beforeEach, describe, expect, it, vi } from 'vitest'

import { mount } from '@vue/test-utils'
import { ref } from 'vue'
import { createMemoryHistory, createRouter } from 'vue-router'

const mockHotkeys = vi.fn()
mockHotkeys.unbind = vi.fn()

vi.mock('hotkeys-js', () => ({
  default: mockHotkeys,
}))

vi.mock('@/stores/links', () => ({
  useLinksStore: () => ({
    links: ref([]),
    recentLinks: ref([]),
    isLoading: ref(false),
    isReady: ref(true),
    ensureLoaded: vi.fn(),
    addLink: vi.fn(),
    updateLink: vi.fn(),
    removeLink: vi.fn(),
    recordVisit: vi.fn(),
    importLinks: vi.fn(),
    exportLinks: vi.fn().mockResolvedValue({ links: [] }),
  }),
}))

vi.mock('@/stores/settings', () => ({
  useSettingsStore: () => ({
    state: ref({
      searchShortcut: 'Ctrl+K',
      theme: 'light',
      defaultView: 'card',
    }),
    searchShortcut: ref('Ctrl+K'),
    ensureLoaded: vi.fn(),
    updateSettings: vi.fn(),
  }),
}))

const stubs = {
  'el-button': { template: '<button><slot /></button>' },
  'el-dialog': { template: '<div><slot /></div>' },
  'el-input': { template: '<input />' },
  'el-select': { template: '<select><slot /></select>' },
  'el-option': { template: '<option><slot /></option>' },
  'el-form': { template: '<form><slot /></form>' },
  'el-form-item': { template: '<div><slot /></div>' },
  'el-empty': { template: '<div class="empty"><slot /></div>' },
  'el-upload': { template: '<div><slot /></div>' },
  'el-divider': { template: '<hr />' },
  'el-skeleton': { template: '<div class="skeleton"></div>' },
  'el-drawer': { template: '<div class="drawer"><slot /></div>' },
  'el-message': true,
  'el-message-box': true,
  transition: false,
  teleport: true,
}

describe('App', () => {
  beforeEach(() => {
    vi.clearAllMocks()
  })

  it('renders the hero headline', async () => {
    const [{ default: App }, { default: HomeView }] = await Promise.all([
      import('../App.vue'),
      import('../views/HomeView.vue'),
    ])

    const router = createRouter({
      history: createMemoryHistory(),
      routes: [
        {
          path: '/',
          component: HomeView,
        },
      ],
    })

    router.push('/')
    await router.isReady()

    const wrapper = mount(App, {
      global: {
        stubs,
        plugins: [router],
      },
    })

    expect(wrapper.text()).toContain('掌控你的网页书签')
  })
})
