'use client'

import { useEffect } from 'react'
import { AnalyzePanel } from '@/components/analyze/AnalyzePanel'
import { ANALYZE_PREFS_KEY, useAnalyzePanelStore } from '@/lib/analyze-store'

type StoredPrefs = {
  fastMode?: boolean
  sectionVisibility?: Record<string, boolean>
}

export function AnalyzePanelProvider({ children }: { children: React.ReactNode }) {
  const { fastMode, sectionVisibility, setFastMode, setSectionVisibility } = useAnalyzePanelStore()

  // Hydrate from localStorage once
  useEffect(() => {
    try {
      const raw = localStorage.getItem(ANALYZE_PREFS_KEY)
      if (!raw) return
      const parsed = JSON.parse(raw) as StoredPrefs
      if (typeof parsed.fastMode === 'boolean') setFastMode(parsed.fastMode)
      if (parsed.sectionVisibility && typeof parsed.sectionVisibility === 'object') {
        setSectionVisibility({ ...sectionVisibility, ...parsed.sectionVisibility })
      }
    } catch {
      // ignore corrupted prefs
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  // Persist prefs
  useEffect(() => {
    try {
      const payload: StoredPrefs = { fastMode, sectionVisibility }
      localStorage.setItem(ANALYZE_PREFS_KEY, JSON.stringify(payload))
    } catch {
      // ignore
    }
  }, [fastMode, sectionVisibility])

  return (
    <>
      {children}
      <AnalyzePanel />
    </>
  )
}

