'use client'

import { useEffect, useRef } from 'react'
import { useBacklogRealtime } from '@/lib/realtime/use-backlog-realtime'
import { useWorkspaceResync } from '@/lib/realtime/use-workspace-resync'
import { useProductWorkspaceStore } from '@/stores/product-workspace/store'
import type {
  BacklogPbi,
  BacklogStory,
  BacklogTask,
  ProductBacklogSnapshot,
} from '@/stores/product-workspace/types'

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

interface BacklogHydrationWrapperProps {
  initialData: InitialData
  productId: string
  productName?: 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}`
}

// PBI-74 / Story 8: workspace-store is nu enige bron — dual-dispatch weg.
function toWorkspaceSnapshot(
  data: InitialData,
  productId: string,
  productName: string | undefined,
): ProductBacklogSnapshot {
  return {
    product: { id: productId, name: productName ?? '' },
    pbis: data.pbis,
    storiesByPbi: data.storiesByPbi,
    tasksByStory: data.tasksByStory,
  }
}

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

  useEffect(() => {
    const fp = fingerprint(initialData)
    if (fp !== lastFingerprint.current) {
      lastFingerprint.current = fp
      useProductWorkspaceStore
        .getState()
        .hydrateSnapshot(toWorkspaceSnapshot(initialData, productId, productName))
    }
  }, [initialData, productId, productName])

  useBacklogRealtime(productId)
  useWorkspaceResync()

  return <>{children}</>
}
