// hooks/useWebVitals.ts
'use client'

import { useEffect, useState } from 'react'

interface WebVitalsMetrics {
    FCP: number | null
    LCP: number | null
    FID: number | null
    CLS: number | null
    TTFB: number | null
    INP: number | null
}

export function useWebVitals() {
    const [metrics, setMetrics] = useState<WebVitalsMetrics>({
        FCP: null,
        LCP: null,
        FID: null,
        CLS: null,
        TTFB: null,
        INP: null,
    })

    useEffect(() => {
        if (typeof window === 'undefined' || !('performance' in window)) return

        // Create a PerformanceObserver to capture metrics
        const observer = new PerformanceObserver((list) => {
            list.getEntries().forEach((entry) => {
                // First Contentful Paint
                if (entry.entryType === 'paint' && entry.name === 'first-contentful-paint') {
                    setMetrics(prev => ({ ...prev, FCP: entry.startTime }))
                }

                // Largest Contentful Paint
                if (entry.entryType === 'largest-contentful-paint') {
                    setMetrics(prev => ({ ...prev, LCP: entry.startTime }))
                }

                // First Input Delay
                if (entry.entryType === 'first-input') {
                    const fidEntry = entry as PerformanceEventTiming
                    setMetrics(prev => ({ ...prev, FID: fidEntry.processingStart - fidEntry.startTime }))
                }

                // Cumulative Layout Shift
                if (entry.entryType === 'layout-shift') {
                    const clsEntry = entry as any // LayoutShift
                    if (!clsEntry.hadRecentInput) {
                        setMetrics(prev => ({
                            ...prev,
                            CLS: (prev.CLS || 0) + clsEntry.value
                        }))
                    }
                }

                // Interaction to Next Paint
                if (entry.entryType === 'event' || entry.entryType === 'first-input') {
                    const inpEntry = entry as any // PerformanceEventTiming
                    if (inpEntry.interactionId) {
                        setMetrics(prev => ({
                            ...prev,
                            INP: Math.max(prev.INP || 0, inpEntry.duration)
                        }))
                    }
                }
            })
        })

        // TTFB can be obtained from navigation timing
        const navigationEntry = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming
        if (navigationEntry) {
            setMetrics(prev => ({
                ...prev,
                TTFB: navigationEntry.responseStart - navigationEntry.requestStart
            }))
        }

        // Observe different metric types
        observer.observe({
            entryTypes: ['paint', 'largest-contentful-paint', 'first-input', 'layout-shift', 'event']
        })

        return () => observer.disconnect()
    }, [])

    return metrics
}