import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import { nextTick } from 'vue'
import DocumentCard from '../../documents/DocumentCard.vue'

// ── Stubs ──────────────────────────────────────────────────────────────────────

const DocumentCardStubs = {
  TopicBadge: true,
  ShareModal: true,
}

// ── Fixtures ───────────────────────────────────────────────────────────────────

const SAMPLE_DOC = {
  id: 'doc-1',
  original_name: 'report.pdf',
  size_bytes: 1024,
  created_at: '2025-01-01T00:00:00Z',
  status: 'ready',
  topics: [],
  is_shared: false,
}

describe('UX-13: Teleport + getBoundingClientRect dropdown pattern across components', () => {
  beforeEach(() => {
    setActivePinia(createPinia())
    // Mock getBoundingClientRect to return predictable values
    vi.spyOn(Element.prototype, 'getBoundingClientRect').mockReturnValue({
      top: 100,
      bottom: 140,
      left: 50,
      right: 250,
      width: 200,
      height: 40,
      x: 50,
      y: 100,
    })
    // Mock window dimensions
    Object.defineProperty(window, 'innerHeight', { value: 800, writable: true })
    Object.defineProperty(window, 'innerWidth', { value: 1200, writable: true })
  })

  afterEach(() => {
    vi.restoreAllMocks()
  })

  it('DocumentCard folder picker uses Teleport to body', async () => {
    const wrapper = mount(DocumentCard, {
      props: { doc: SAMPLE_DOC },
      global: {
        stubs: DocumentCardStubs,
        // attachTo is required for Teleport to render to document.body
      },
      attachTo: document.body,
    })

    // Hover is not needed, just click the move button directly
    const moveBtn = wrapper.find('[aria-label="Move to folder"]')
    expect(moveBtn.exists()).toBe(true)
    await moveBtn.trigger('click')
    await nextTick()

    // The folder picker should be teleported to body
    const picker = document.body.querySelector('[data-test="folder-picker"]')
    expect(picker).not.toBeNull()

    wrapper.unmount()
  })

  it('DocumentCard folder picker position matches trigger getBoundingClientRect', async () => {
    const wrapper = mount(DocumentCard, {
      props: { doc: SAMPLE_DOC },
      global: { stubs: DocumentCardStubs },
      attachTo: document.body,
    })

    const moveBtn = wrapper.find('[aria-label="Move to folder"]')
    await moveBtn.trigger('click')
    await nextTick()

    const picker = document.body.querySelector('[data-test="folder-picker"]')
    expect(picker).not.toBeNull()
    // Should have fixed positioning with top matching rect.bottom + offset
    const style = picker.style
    expect(style.top || style.bottom).toBeTruthy()
    expect(style.left).toBeTruthy()

    wrapper.unmount()
  })
})
