import React, { createContext, useContext, useMemo, useState } from "react";
import initialLibrary from "../data/library";

const LibraryContext = createContext(null);

export function LibraryProvider({ children }) {
  const [albums, setAlbums] = useState(initialLibrary);

  const toggleLike = (albumId, trackId) => {
    setAlbums((prev) =>
      prev.map((album) =>
        album.id !== albumId
          ? album
          : {
              ...album,
              tracks: album.tracks.map((t) =>
                t.id === trackId ? { ...t, liked: !t.liked } : t
              ),
            }
      )
    );
  };

  const likedTracks = useMemo(
    () =>
      albums.flatMap((album) =>
        album.tracks
          .filter((track) => track.liked)
          .map((track) => ({
            ...track,
            albumId: album.id,
            albumTitle: album.title,
            artist: album.artist,
            cover: album.cover,
          }))
      ),
    [albums]
  );

  return (
    <LibraryContext.Provider value={{ albums, likedTracks, toggleLike }}>
      {children}
    </LibraryContext.Provider>
  );
}

export function useLibrary() {
  const ctx = useContext(LibraryContext);
  if (!ctx) throw new Error("useLibrary must be used inside LibraryProvider");
  return ctx;
}