'use client'

import { useEffect, useRef } from 'react'
import { useBacklogStore, type BacklogPbi, type BacklogStory, type BacklogTask } from '@/stores/backlog-store'
import { useBacklogRealtime } from '@/lib/realtime/use-backlog-realtime'

interface InitialData {
  pbis: BacklogPbi[]
  storiesByPbi: Record<string, BacklogStory[]>
  tasksByStory: Record<string, BacklogTask[]>
}

interface BacklogHydrationWrapperProps {
  initialData: InitialData
  productId: string
  children: React.ReactNode
}

function fingerprint(data: InitialData): string {
  const pbiPart = data.pbis.map((p) => `${p.id}:${p.status}:${p.priority}`).join(',')
  const storyPart = Object.entries(data.storiesByPbi)
    .flatMap(([, list]) => list.map((s) => `${s.id}:${s.status}:${s.sprint_id ?? 'null'}`))
    .join(',')
  const taskPart = Object.entries(data.tasksByStory)
    .flatMap(([, list]) => list.map((t) => `${t.id}:${t.status}`))
    .join(',')
  return `${pbiPart}|${storyPart}|${taskPart}`
}

export function BacklogHydrationWrapper({ initialData, productId, children }: BacklogHydrationWrapperProps) {
  const setInitialData = useBacklogStore((s) => s.setInitialData)
  const lastFingerprint = useRef<string>('')

  useEffect(() => {
    const fp = fingerprint(initialData)
    if (fp !== lastFingerprint.current) {
      lastFingerprint.current = fp
      setInitialData(initialData)
    }
  }, [initialData, setInitialData])

  useBacklogRealtime(productId)

  return <>{children}</>
}
