import { createContext, useContext, useEffect, useState } from 'react';

const STORAGE_KEY = 'bookibra_saved_books';
const SavedBooksContext = createContext();

export function SavedBooksProvider({ children }) {
  const [savedBooks, setSavedBooks] = useState(() => {
    if (typeof window === 'undefined') return [];
    try {
      const raw = window.localStorage.getItem(STORAGE_KEY);
      return raw ? JSON.parse(raw) : [];
    } catch (error) {
      console.warn('Saved books parse error', error);
      return [];
    }
  });

  useEffect(() => {
    if (typeof window !== 'undefined') {
      window.localStorage.setItem(STORAGE_KEY, JSON.stringify(savedBooks));
    }
  }, [savedBooks]);

  const addBook = (book) => {
    setSavedBooks((prev) => {
      if (prev.find((item) => item.title === book.title && item.authorName === book.authorName)) {
        return prev;
      }
      return [...prev, book];
    });
  };

  const removeBook = (title) => {
    setSavedBooks((prev) => prev.filter((book) => book.title !== title));
  };

  return (
    <SavedBooksContext.Provider value={{ savedBooks, addBook, removeBook }}>
      {children}
    </SavedBooksContext.Provider>
  );
}

export const useSavedBooks = () => useContext(SavedBooksContext);
