import { useState, useCallback } from 'react'

const KEY = 'fb_starred_repos'

function read(): string[] {
  try {
    return JSON.parse(localStorage.getItem(KEY) ?? '[]')
  } catch {
    return []
  }
}

function repoKey(ownerName: string, name: string) {
  return `${ownerName}/${name}`
}

export function useStarredRepos() {
  const [starred, setStarred] = useState<string[]>(read)

  const toggle = useCallback((ownerName: string, name: string) => {
    const key = repoKey(ownerName, name)
    setStarred(prev => {
      const next = prev.includes(key) ? prev.filter(k => k !== key) : [...prev, key]
      localStorage.setItem(KEY, JSON.stringify(next))
      return next
    })
  }, [])

  const isStarred = useCallback((ownerName: string, name: string) => {
    return starred.includes(repoKey(ownerName, name))
  }, [starred])

  return { starred, toggle, isStarred }
}
