import { useCallback, useEffect, useState } from 'react'
import { useAuth } from 'src/state/AuthProvider'

/**
 * Account-scoped UI preference. Reads via `read(accountId)` on mount,
 * re-hydrates whenever the active account changes, and persists every update
 * through `write(accountId, value)`.
 *
 * `read` must handle the empty-accountId case (return a default) — every
 * existing per-account pref reader (`getHomeMastodonList`, `getListOrder`)
 * already does. The setter no-ops the write half when there is no active
 * account so the local state still updates during a sign-out window without
 * stranding a write under an empty key.
 */
export function useAccountScopedPref<T>(
  read: (accountId: string) => T,
  write: (accountId: string, value: T) => void
): readonly [T, (next: T) => void] {
  const { activeAccountId } = useAuth()
  const accountId = activeAccountId ?? ''
  const [value, setLocal] = useState<T>(() => read(accountId))
  useEffect(() => {
    setLocal(read(accountId))
  }, [accountId])
  const set = useCallback(
    (next: T) => {
      setLocal(next)
      if (accountId) write(accountId, next)
    },
    [accountId, write]
  )
  return [value, set] as const
}
