export interface LibraryNovel {
  id: string
  title: string
  author: string
  cover: string
  addedAt: string
}

export interface ReadingHistoryEntry {
  novelId: string
  novelTitle: string
  chapterId: string
  chapterTitle: string
  cover: string
  readAt: string
}

export const useReaderStorage = () => {
  /**
   * Library Management (localStorage)
   * TODO: Migrate to PostgreSQL in a future update
   */
  const addToLibrary = (novel: { id: string, title: string, author: string, cover: string }) => {
    const library = JSON.parse(localStorage.getItem('user_library') || '[]') as LibraryNovel[]
    const exists = library.some(n => n.id === novel.id)

    if (!exists) {
      library.push({
        ...novel,
        addedAt: new Date().toISOString()
      })
      localStorage.setItem('user_library', JSON.stringify(library))
      return true
    }
    return false
  }

  const removeFromLibrary = (novelId: string) => {
    const library = JSON.parse(localStorage.getItem('user_library') || '[]') as LibraryNovel[]
    const filtered = library.filter(n => n.id !== novelId)
    localStorage.setItem('user_library', JSON.stringify(filtered))
  }

  const isInLibrary = (novelId: string): boolean => {
    const library = JSON.parse(localStorage.getItem('user_library') || '[]') as LibraryNovel[]
    return library.some(n => n.id === novelId)
  }

  const getLibrary = (): LibraryNovel[] => {
    return JSON.parse(localStorage.getItem('user_library') || '[]')
  }

  /**
   * Reading History Management (localStorage)
   * TODO: Migrate to PostgreSQL in a future update
   */
  const addToHistory = (entry: Omit<ReadingHistoryEntry, 'readAt'>) => {
    const history = JSON.parse(localStorage.getItem('reading_history') || '[]') as ReadingHistoryEntry[]

    history.push({
      ...entry,
      readAt: new Date().toISOString()
    })

    // Keep only last 100 entries
    if (history.length > 100) {
      history.shift()
    }

    localStorage.setItem('reading_history', JSON.stringify(history))
  }

  const getHistory = (): ReadingHistoryEntry[] => {
    const history = JSON.parse(localStorage.getItem('reading_history') || '[]') as ReadingHistoryEntry[]
    return history.sort((a, b) => new Date(b.readAt).getTime() - new Date(a.readAt).getTime())
  }

  const clearHistory = () => {
    localStorage.removeItem('reading_history')
  }

  return {
    // Library methods
    addToLibrary,
    removeFromLibrary,
    isInLibrary,
    getLibrary,

    // History methods
    addToHistory,
    getHistory,
    clearHistory
  }
}
