import { loadRecord, saveRecord } from './browser-storage'
import { useEffect, useState } from 'react'

/** Client-side mirror of collector config `projectColors` until Settings (U4) writes via POST. */
const STORAGE_KEY = 'overdeck-project-colors'

export type ProjectColorOverrides = Record<string, string>

export function loadProjectColorOverrides(): ProjectColorOverrides {
  return loadRecord(STORAGE_KEY, (value): value is string => typeof value === 'string')
}

export function saveProjectColorOverrides(overrides: ProjectColorOverrides): void {
  saveRecord(STORAGE_KEY, overrides)
}

export function useProjectColorOverrides(): [ProjectColorOverrides, (overrides: ProjectColorOverrides) => void] {
  const [overrides, setOverrides] = useState(() => loadProjectColorOverrides())
  useEffect(() => {
    const onStorage = (event: StorageEvent) => {
      if (event.key === STORAGE_KEY) setOverrides(loadProjectColorOverrides())
    }
    window.addEventListener('storage', onStorage)
    return () => window.removeEventListener('storage', onStorage)
  }, [])
  return [overrides, setOverrides]
}
