// @vitest-environment jsdom
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { render, screen } from '@testing-library/react'

vi.mock('@/actions/user-settings', () => ({
  updateUserSettingsAction: vi.fn().mockResolvedValue({ success: true, settings: {} }),
}))

import { useProductWorkspaceStore } from '@/stores/product-workspace/store'
import { BacklogSplitPane } from '@/components/backlog/backlog-split-pane'

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

const PANES = [
  <div key="a">PBI pane</div>,
  <div key="b">Stories pane</div>,
  <div key="c">Tasks pane</div>,
]

function renderPane() {
  return render(
    <BacklogSplitPane
      panes={PANES}
      defaultSplit={[33, 33, 34]}
      cookieKey="test-backlog"
      tabLabels={["PBI's", 'Stories', 'Taken']}
    />
  )
}

beforeEach(() => {
  setSelection(null, null)
  // Force mobile viewport
  Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 600 })
  window.dispatchEvent(new Event('resize'))
})

describe('BacklogSplitPane auto-switch', () => {
  it('starts on tab 0 with no selection', () => {
    renderPane()
    expect(screen.getByText('PBI pane')).toBeTruthy()
    expect(screen.queryByText('Stories pane')).toBeNull()
  })

  it('auto-switches to tab 1 when PBI is selected', () => {
    const { rerender } = renderPane()
    setSelection('pbi-1', null)
    rerender(
      <BacklogSplitPane
        panes={PANES}
        defaultSplit={[33, 33, 34]}
        cookieKey="test-backlog"
        tabLabels={["PBI's", 'Stories', 'Taken']}
      />
    )
    expect(screen.getByText('Stories pane')).toBeTruthy()
    expect(screen.queryByText('PBI pane')).toBeNull()
  })

  it('auto-switches to tab 2 when story is selected', () => {
    const { rerender } = renderPane()
    setSelection('pbi-1', 'story-1')
    rerender(
      <BacklogSplitPane
        panes={PANES}
        defaultSplit={[33, 33, 34]}
        cookieKey="test-backlog"
        tabLabels={["PBI's", 'Stories', 'Taken']}
      />
    )
    expect(screen.getByText('Tasks pane')).toBeTruthy()
    expect(screen.queryByText('PBI pane')).toBeNull()
  })

  it('switches to tab 1 on cascade-reset (story cleared when new PBI selected)', () => {
    // Start with story selected (tab 2)
    setSelection('pbi-1', 'story-1')
    const { rerender } = renderPane()

    // Cascade-reset: new PBI → story clears
    setSelection('pbi-2', null)
    rerender(
      <BacklogSplitPane
        panes={PANES}
        defaultSplit={[33, 33, 34]}
        cookieKey="test-backlog"
        tabLabels={["PBI's", 'Stories', 'Taken']}
      />
    )
    expect(screen.getByText('Stories pane')).toBeTruthy()
  })
})
