import { useState, useEffect, useCallback } from 'react'
import * as SecureStore from 'expo-secure-store'
import { toggleKBBookmark } from '../services/api'

const KEY = 'kb_bookmarks'

export function useKBBookmark() {
  const [ids, setIds] = useState<number[]>([])

  useEffect(() => {
    SecureStore.getItemAsync(KEY).then(raw => {
      try { if (raw) setIds(JSON.parse(raw)) } catch {}
    })
  }, [])

  const persist = useCallback(async (next: number[]) => {
    setIds(next)
    await SecureStore.setItemAsync(KEY, JSON.stringify(next)).catch(() => {})
  }, [])

  const isBookmarked = useCallback((id: number) => ids.includes(id), [ids])

  const toggle = useCallback(async (id: number) => {
    const next = ids.includes(id) ? ids.filter(x => x !== id) : [...ids, id]
    await persist(next)
    toggleKBBookmark(id).catch(() => {})
  }, [ids, persist])

  return { ids, isBookmarked, toggle }
}
