'use client'

import { Suspense } from 'react'
import { Header } from './header'
import { useSearchParams, useRouter } from 'next/navigation'
import { useLabels } from '@/context/LabelContext'

interface HeaderWrapperProps {
  onColorFilterChange?: (color: string | null) => void
  user?: any
}

function HeaderContent({ onColorFilterChange, user }: HeaderWrapperProps) {
  const searchParams = useSearchParams()
  const router = useRouter()
  const { labels } = useLabels()
  
  const selectedLabels = searchParams.get('labels')?.split(',').filter(Boolean) || []
  const selectedColor = searchParams.get('color') || null

  const handleLabelFilterChange = (labels: string[]) => {
    const params = new URLSearchParams(searchParams.toString())
    
    if (labels.length > 0) {
      params.set('labels', labels.join(','))
    } else {
      params.delete('labels')
    }

    router.push(`/?${params.toString()}`)
  }

  const handleColorFilterChange = (color: string | null) => {
    const params = new URLSearchParams(searchParams.toString())
    
    if (color) {
      params.set('color', color)
    } else {
      params.delete('color')
    }

    router.push(`/?${params.toString()}`)
    onColorFilterChange?.(color)
  }

  return (
    <Header
      selectedLabels={selectedLabels}
      selectedColor={selectedColor}
      onLabelFilterChange={handleLabelFilterChange}
      onColorFilterChange={handleColorFilterChange}
      user={user}
    />
  )
}

export function HeaderWrapper(props: HeaderWrapperProps) {
  return (
    <Suspense fallback={<div className="h-16 border-b bg-background/95" />}>
      <HeaderContent {...props} />
    </Suspense>
  )
}
