'use client'

import { useState } from 'react'
import { useSelectionStore } from '@/stores/selection-store'
import { SplitPane, type SplitPaneProps } from '@/components/split-pane/split-pane'

type Props = Omit<SplitPaneProps, 'activeTab' | 'onActiveTabChange'>

export function BacklogSplitPane(props: Props) {
  const { selectedPbiId, selectedStoryId } = useSelectionStore()
  const [activeTab, setActiveTab] = useState(0)

  // React-recommended "derived state from props" pattern: update state during render
  // instead of useEffect to avoid cascading renders.
  const [prevPbiId, setPrevPbiId] = useState(selectedPbiId)
  const [prevStoryId, setPrevStoryId] = useState(selectedStoryId)

  if (selectedStoryId !== prevStoryId) {
    setPrevStoryId(selectedStoryId)
    if (selectedStoryId) setActiveTab(2)
  }
  if (selectedPbiId !== prevPbiId) {
    setPrevPbiId(selectedPbiId)
    if (selectedPbiId && !selectedStoryId) setActiveTab(1)
  }

  return (
    <SplitPane
      {...props}
      activeTab={activeTab}
      onActiveTabChange={setActiveTab}
    />
  )
}
