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

const globalStubs = {
  BreadcrumbBar: true,
  SearchBar: true,
  SortControls: true,
  DropZone: true,
  UploadProgress: true,
  TopicBadge: true,
  AppIcon: { template: '<span class="app-icon-stub" />' },
  EmptyState: true,
}

const FOLDERS = [{ id: 'f1', name: 'Archive', created_at: '2025-01-01T00:00:00Z' }]
const FILES = [{ id: 'd1', original_name: 'report.pdf', size_bytes: 1024, created_at: '2025-01-01T00:00:00Z', topics: [] }]

// Full cloud-unsupported capabilities
const CAPS_NONE = {
  share: false,
  move: false,
  delete: false,
  rename_folder: false,
  delete_folder: false,
  create_folder: false,
  drag_move: false,
}

// Temporarily unavailable
const CAPS_TEMP = {
  share: 'temporarily_unavailable',
  move: 'temporarily_unavailable',
  delete: 'temporarily_unavailable',
  rename_folder: false,
  delete_folder: false,
  create_folder: false,
  drag_move: false,
}

beforeEach(() => {
  setActivePinia(createPinia())
})

describe('StorageBrowser capability rendering', () => {

  // ── Local defaults — all pre-Phase-12 local actions preserved ─────────────
  it('local mode: folders have rename and delete buttons in supported state', async () => {
    const w = mount(StorageBrowser, {
      props: { mode: 'local', folders: FOLDERS, files: [], rootFolders: [] },
      global: { stubs: globalStubs },
    })
    const folderActions = w.find('[data-test="folder-row-actions"]')
    const buttons = folderActions.findAll('button')
    expect(buttons.length).toBeGreaterThanOrEqual(2)
    // No aria-disabled on local
    buttons.forEach(btn => {
      expect(btn.attributes('aria-disabled')).toBeUndefined()
    })
  })

  it('local mode: file rows have share, move, delete buttons in supported state', async () => {
    const w = mount(StorageBrowser, {
      props: { mode: 'local', folders: [], files: FILES, rootFolders: [] },
      global: { stubs: globalStubs },
    })
    const fileActions = w.find('[data-test="file-row-actions"]')
    const buttons = fileActions.findAll('button')
    expect(buttons.length).toBeGreaterThanOrEqual(3)
    buttons.forEach(btn => {
      expect(btn.attributes('aria-disabled')).toBeUndefined()
    })
  })

  it('local mode: supported file-delete button emits file-delete on click', async () => {
    const w = mount(StorageBrowser, {
      props: { mode: 'local', folders: [], files: FILES, rootFolders: [] },
      global: { stubs: globalStubs },
    })
    const fileActions = w.find('[data-test="file-row-actions"]')
    const deleteBtn = fileActions.findAll('button').find(b => b.attributes('title') === 'Delete')
    await deleteBtn.trigger('click')
    expect(w.emitted('file-delete')).toBeTruthy()
    expect(w.emitted('file-delete')[0][0]).toBe('d1')
  })

  // ── Unsupported actions — aria-disabled, gray, action suppressed ─────────
  it('cloud unsupported: file actions have aria-disabled="true"', async () => {
    const w = mount(StorageBrowser, {
      props: { mode: 'cloud', folders: [], files: FILES, rootFolders: [], capabilities: CAPS_NONE },
      global: { stubs: globalStubs },
    })
    const fileActions = w.find('[data-test="file-row-actions"]')
    const buttons = fileActions.findAll('button')
    buttons.forEach(btn => {
      expect(btn.attributes('aria-disabled')).toBe('true')
    })
  })

  it('cloud unsupported: clicking aria-disabled action does NOT emit the action', async () => {
    const w = mount(StorageBrowser, {
      props: { mode: 'cloud', folders: [], files: FILES, rootFolders: [], capabilities: CAPS_NONE },
      global: { stubs: globalStubs },
    })
    const fileActions = w.find('[data-test="file-row-actions"]')
    const deleteBtn = fileActions.findAll('button').find(b => b.attributes('aria-label') === 'Delete')
    await deleteBtn.trigger('click')
    expect(w.emitted('file-delete')).toBeFalsy()
  })

  it('cloud unsupported: keyboard Enter on disabled action does NOT emit action', async () => {
    const w = mount(StorageBrowser, {
      props: { mode: 'cloud', folders: [], files: FILES, rootFolders: [], capabilities: CAPS_NONE },
      global: { stubs: globalStubs },
    })
    const fileActions = w.find('[data-test="file-row-actions"]')
    const shareBtn = fileActions.findAll('button').find(b => b.attributes('aria-label') === 'Share')
    await shareBtn.trigger('keydown', { key: 'Enter' })
    expect(w.emitted('file-share')).toBeFalsy()
  })

  it('cloud unsupported: keyboard Space on disabled action does NOT emit action', async () => {
    const w = mount(StorageBrowser, {
      props: { mode: 'cloud', folders: [], files: FILES, rootFolders: [], capabilities: CAPS_NONE },
      global: { stubs: globalStubs },
    })
    const fileActions = w.find('[data-test="file-row-actions"]')
    const shareBtn = fileActions.findAll('button').find(b => b.attributes('aria-label') === 'Share')
    await shareBtn.trigger('keydown', { key: ' ' })
    expect(w.emitted('file-share')).toBeFalsy()
  })

  it('cloud unsupported: clicking disabled action shows capability-notice', async () => {
    const w = mount(StorageBrowser, {
      props: { mode: 'cloud', folders: [], files: FILES, rootFolders: [], capabilities: CAPS_NONE },
      global: { stubs: globalStubs },
    })
    const fileActions = w.find('[data-test="file-row-actions"]')
    const deleteBtn = fileActions.findAll('button').find(b => b.attributes('aria-label') === 'Delete')
    await deleteBtn.trigger('click')
    await nextTick()
    expect(w.find('[data-test="capability-notice"]').exists()).toBe(true)
  })

  it('cloud unsupported: also emits capability-explain event', async () => {
    const w = mount(StorageBrowser, {
      props: { mode: 'cloud', folders: [], files: FILES, rootFolders: [], capabilities: CAPS_NONE },
      global: { stubs: globalStubs },
    })
    const fileActions = w.find('[data-test="file-row-actions"]')
    const deleteBtn = fileActions.findAll('button').find(b => b.attributes('aria-label') === 'Delete')
    await deleteBtn.trigger('click')
    expect(w.emitted('capability-explain')).toBeTruthy()
  })

  // ── Temporarily unavailable — amber state ─────────────────────────────────
  it('temporarily_unavailable: action buttons have data-cap="temporarily_unavailable"', async () => {
    const w = mount(StorageBrowser, {
      props: { mode: 'cloud', folders: [], files: FILES, rootFolders: [], capabilities: CAPS_TEMP },
      global: { stubs: globalStubs },
    })
    const fileActions = w.find('[data-test="file-row-actions"]')
    const tempBtns = fileActions.findAll('button').filter(b => b.attributes('data-cap') === 'temporarily_unavailable')
    expect(tempBtns.length).toBeGreaterThan(0)
  })

  it('temporarily_unavailable: clicking does NOT emit action', async () => {
    const w = mount(StorageBrowser, {
      props: { mode: 'cloud', folders: [], files: FILES, rootFolders: [], capabilities: CAPS_TEMP },
      global: { stubs: globalStubs },
    })
    const fileActions = w.find('[data-test="file-row-actions"]')
    const shareBtn = fileActions.findAll('button').find(b => b.attributes('aria-label') === 'Share')
    await shareBtn.trigger('click')
    expect(w.emitted('file-share')).toBeFalsy()
  })

  // ── No native disabled attr ────────────────────────────────────────────────
  it('no button uses native disabled attribute (all use aria-disabled)', async () => {
    const w = mount(StorageBrowser, {
      props: { mode: 'cloud', folders: FOLDERS, files: FILES, rootFolders: [], capabilities: CAPS_NONE },
      global: { stubs: globalStubs },
    })
    const allButtons = w.findAll('button')
    allButtons.forEach(btn => {
      expect(btn.attributes('disabled')).toBeUndefined()
    })
  })

  // ── Cached byte marker ────────────────────────────────────────────────────
  it('shows cached-byte marker when byteAvailability is "cached"', async () => {
    const w = mount(StorageBrowser, {
      props: {
        mode: 'cloud', folders: [], files: FILES, rootFolders: [],
        capabilities: CAPS_NONE, byteAvailability: 'cached',
        lastRefreshedAt: '2026-01-01T00:00:00Z',
      },
      global: { stubs: globalStubs },
    })
    expect(w.find('[data-test="cached-byte-marker"]').exists()).toBe(true)
  })

  it('does NOT show cached-byte marker when byteAvailability is "cloud_only"', async () => {
    const w = mount(StorageBrowser, {
      props: {
        mode: 'cloud', folders: [], files: FILES, rootFolders: [],
        capabilities: CAPS_NONE, byteAvailability: 'cloud_only',
      },
      global: { stubs: globalStubs },
    })
    expect(w.find('[data-test="cached-byte-marker"]').exists()).toBe(false)
  })

  it('does NOT show cached-byte marker in local mode', async () => {
    const w = mount(StorageBrowser, {
      props: { mode: 'local', folders: [], files: FILES, rootFolders: [] },
      global: { stubs: globalStubs },
    })
    expect(w.find('[data-test="cached-byte-marker"]').exists()).toBe(false)
  })

  // ── Touch target min size ─────────────────────────────────────────────────
  it('action buttons have min-w-[36px] min-h-[36px] touch target classes', async () => {
    const w = mount(StorageBrowser, {
      props: { mode: 'cloud', folders: [], files: FILES, rootFolders: [], capabilities: CAPS_NONE },
      global: { stubs: globalStubs },
    })
    const fileActions = w.find('[data-test="file-row-actions"]')
    const buttons = fileActions.findAll('button')
    buttons.forEach(btn => {
      const cls = btn.attributes('class') || ''
      expect(cls).toContain('min-w-[36px]')
      expect(cls).toContain('min-h-[36px]')
    })
  })

  // ── Drag/drop preserved for local ────────────────────────────────────────
  it('local mode: file rows have draggable="true"', async () => {
    const w = mount(StorageBrowser, {
      props: { mode: 'local', folders: FOLDERS, files: FILES, rootFolders: [] },
      global: { stubs: globalStubs },
    })
    const fileRow = w.find('[draggable="true"]')
    expect(fileRow.exists()).toBe(true)
  })

  it('cloud mode with drag_move=false: file rows are NOT draggable', async () => {
    const w = mount(StorageBrowser, {
      props: { mode: 'cloud', folders: FOLDERS, files: FILES, rootFolders: [], capabilities: CAPS_NONE },
      global: { stubs: globalStubs },
    })
    const fileRows = w.findAll('[draggable="true"]')
    expect(fileRows.length).toBe(0)
  })
})
