import { useEffect } from 'react'
import { useMMKVBoolean, useMMKVString } from 'react-native-mmkv'
import { type FaviconStatus, faviconKey, probeFavicon } from 'src/lib/favicon'
import { appStorage, uiKeys } from 'src/state/storage'

export interface UseFaviconResult {
  /** 'available' | 'unavailable' | 'unknown' — collapses the MMKV string into
   *  the favicon module's discriminated union. */
  status: FaviconStatus
  /** Global preference; consumers should still call this rather than hard-
   *  coding gates so a single Settings toggle controls every surface. */
  enabled: boolean
}

const SHOW_LINK_FAVICONS_DEFAULT = true

/**
 * Reactive favicon status for `host`. Subscribes to the host-keyed MMKV entry
 * so a probe that lands while the cell is mounted re-renders it. Fires a
 * background probe when the entry is missing and the global pref is on; the
 * probe writes through MMKV so the cell re-renders naturally on completion.
 */
export function useFavicon(host: string | null | undefined): UseFaviconResult {
  const safeHost = host ?? ''
  const [stored] = useMMKVString(faviconKey(safeHost), appStorage)
  const [enabledStored] = useMMKVBoolean(uiKeys.showLinkFavicons, appStorage)
  const enabled = enabledStored ?? SHOW_LINK_FAVICONS_DEFAULT

  useEffect(() => {
    if (!safeHost || !enabled) return
    if (stored === undefined) {
      probeFavicon(safeHost).catch(() => {})
    }
  }, [safeHost, stored, enabled])

  let status: FaviconStatus = 'unknown'
  if (stored === 'available') status = 'available'
  else if (stored === 'unavailable') status = 'unavailable'
  return { status, enabled }
}
