import { useState, useCallback } from 'react'

const STORAGE_KEY = 'cameleer:starred'

function readStarred(): Set<string> {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    if (raw) {
      const arr = JSON.parse(raw)
      if (Array.isArray(arr)) return new Set(arr)
    }
  } catch {
    // localStorage unavailable (private browsing, quota exceeded) — fall back to empty
  }
  return new Set()
}

function writeStarred(ids: Set<string>): void {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify([...ids]))
  } catch {
    // Silently fail if localStorage unavailable
  }
}

export function useStarred() {
  const [starredIds, setStarredIds] = useState<Set<string>>(readStarred)

  const isStarred = useCallback((id: string) => starredIds.has(id), [starredIds])

  const toggleStar = useCallback((id: string) => {
    setStarredIds((prev) => {
      const next = new Set(prev)
      if (next.has(id)) {
        next.delete(id)
      } else {
        next.add(id)
      }
      writeStarred(next)
      return next
    })
  }, [])

  return { starredIds, isStarred, toggleStar }
}
