'use client'

import { useState } from 'react'
import { useProductWorkspaceStore } from '@/stores/product-workspace/store'
import { SplitPane, type SplitPaneProps } from '@/components/split-pane/split-pane'

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

// PBI-74 / T-848: leest active PBI/story-ids uit workspace-store. Primitives,
// dus geen useShallow nodig.
export function BacklogSplitPane(props: Props) {
  const selectedPbiId = useProductWorkspaceStore((s) => s.context.activePbiId)
  const selectedStoryId = useProductWorkspaceStore((s) => s.context.activeStoryId)
  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}
    />
  )
}
