// @vitest-environment jsdom
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { useProductWorkspaceStore } from '@/stores/product-workspace/store'
import type {
  BacklogStory,
  BacklogTask,
} from '@/stores/product-workspace/types'

// Mock next/navigation
const mockPush = vi.fn()
vi.mock('next/navigation', () => ({ useRouter: () => ({ push: mockPush }) }))

// localStorage mock for StoryPanel sort mode persistence
const localStorageMock = (() => {
  let store: Record<string, string> = {}
  return {
    getItem: (k: string) => store[k] ?? null,
    setItem: (k: string, v: string) => { store[k] = v },
    removeItem: (k: string) => { delete store[k] },
    clear: () => { store = {} },
  }
})()
Object.defineProperty(globalThis, 'localStorage', { value: localStorageMock, writable: true })

// Mock server actions
vi.mock('@/actions/stories', () => ({
  reorderPbisAction: vi.fn().mockResolvedValue({ success: true }),
  updatePbiPriorityAction: vi.fn().mockResolvedValue({ success: true }),
}))
vi.mock('@/actions/pbis', () => ({ deletePbiAction: vi.fn().mockResolvedValue({ success: true }) }))
vi.mock('@/actions/user-settings', () => ({
  updateUserSettingsAction: vi.fn().mockResolvedValue({ success: true, settings: {} }),
}))
vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } }))

// Mock dnd-kit (still needed for PBI panel which supports drag-and-drop)
vi.mock('@dnd-kit/core', () => ({
  DndContext: ({ children }: { children: React.ReactNode }) => <>{children}</>,
  PointerSensor: class {},
  KeyboardSensor: class {},
  useSensor: vi.fn(),
  useSensors: vi.fn(() => []),
  closestCenter: vi.fn(),
  DragOverlay: () => null,
}))
vi.mock('@dnd-kit/sortable', () => ({
  SortableContext: ({ children }: { children: React.ReactNode }) => <>{children}</>,
  useSortable: () => ({
    attributes: {}, listeners: {}, setNodeRef: vi.fn(),
    transform: null, transition: undefined, isDragging: false,
  }),
  verticalListSortingStrategy: {},
  rectSortingStrategy: {},
  sortableKeyboardCoordinates: {},
  arrayMove: (arr: unknown[]) => arr,
}))
vi.mock('@dnd-kit/utilities', () => ({ CSS: { Transform: { toString: () => '' } } }))

import { StoryPanel } from '@/components/backlog/story-panel'
import { TaskPanel } from '@/components/backlog/task-panel'

const PRODUCT_ID = 'prod-1'
const PBI_ID = 'pbi-1'
const ALT_PBI_ID = 'pbi-2'
const STORY_ID = 'story-1'

const STORIES: BacklogStory[] = [
  { id: STORY_ID, code: 'ST-1', title: 'Eerste story', description: null, acceptance_criteria: null, priority: 2, sort_order: 1, status: 'OPEN', pbi_id: PBI_ID, sprint_id: null, created_at: new Date() },
]
const TASKS: BacklogTask[] = [
  { id: 'task-1', code: null, title: 'Eerste taak', description: null, priority: 2, status: 'TO_DO', sort_order: 1, story_id: STORY_ID, created_at: new Date() },
]

function resetStores() {
  useProductWorkspaceStore.setState((s) => {
    s.context.activeProduct = null
    s.context.activePbiId = null
    s.context.activeStoryId = null
    s.context.activeTaskId = null
    s.entities.pbisById = {}
    s.entities.storiesById = Object.fromEntries(STORIES.map((st) => [st.id, st]))
    s.entities.tasksById = Object.fromEntries(TASKS.map((t) => [t.id, t]))
    s.relations.pbiIds = []
    s.relations.storyIdsByPbi = { [PBI_ID]: STORIES.map((st) => st.id) }
    s.relations.taskIdsByStory = { [STORY_ID]: TASKS.map((t) => t.id) }
  })
}

function selectPbi(pbiId: string | null) {
  useProductWorkspaceStore.setState((s) => {
    s.context.activePbiId = pbiId
    s.context.activeStoryId = null
    s.context.activeTaskId = null
  })
}

function selectStory(pbiId: string | null, storyId: string | null) {
  useProductWorkspaceStore.setState((s) => {
    s.context.activePbiId = pbiId
    s.context.activeStoryId = storyId
  })
}

describe('Backlog 3-pane integration', () => {
  beforeEach(() => {
    mockPush.mockClear()
    resetStores()
  })

  it('StoryPanel shows empty state when no PBI selected', () => {
    render(<StoryPanel productId={PRODUCT_ID} isDemo={false} />)
    expect(screen.getByText('Selecteer een PBI om de stories te bekijken.')).toBeTruthy()
  })

  it('StoryPanel shows stories when PBI is selected', () => {
    selectPbi(PBI_ID)
    render(<StoryPanel productId={PRODUCT_ID} isDemo={false} />)
    expect(screen.getByText('Eerste story')).toBeTruthy()
  })

  it('clicking a story dispatches setActiveStory to the workspace-store', () => {
    selectPbi(PBI_ID)
    render(<StoryPanel productId={PRODUCT_ID} isDemo={false} />)
    fireEvent.click(screen.getByText('Eerste story'))
    expect(useProductWorkspaceStore.getState().context.activeStoryId).toBe(STORY_ID)
  })

  it('cascade-reset: selecting different PBI clears activeStoryId', () => {
    selectStory(PBI_ID, STORY_ID)
    useProductWorkspaceStore.getState().setActivePbi(ALT_PBI_ID)
    expect(useProductWorkspaceStore.getState().context.activeStoryId).toBeNull()
  })

  it('TaskPanel shows tasks after story is selected', () => {
    selectStory(PBI_ID, STORY_ID)
    render(<TaskPanel productId={PRODUCT_ID} isDemo={false} closePath={`/products/${PRODUCT_ID}`} />)
    expect(screen.getByText('Eerste taak')).toBeTruthy()
  })

  it('TaskPanel shows empty state after cascade-reset', () => {
    selectStory(PBI_ID, STORY_ID)
    render(<TaskPanel productId={PRODUCT_ID} isDemo={false} closePath={`/products/${PRODUCT_ID}`} />)
    useProductWorkspaceStore.getState().setActivePbi(ALT_PBI_ID)
    render(<TaskPanel productId={PRODUCT_ID} isDemo={false} closePath={`/products/${PRODUCT_ID}`} />)
    expect(screen.getAllByText('Selecteer een story om de taken te bekijken.').length).toBeGreaterThan(0)
  })

  it('selected story card has isSelected highlight class applied', () => {
    selectStory(PBI_ID, STORY_ID)
    const { container } = render(<StoryPanel productId={PRODUCT_ID} isDemo={false} />)
    // bg-primary-container is applied when isSelected
    const selected = container.querySelector('.bg-primary-container')
    expect(selected).toBeTruthy()
  })
})
