import { useState, useEffect } from "react";

export default function useBasket() {
  const [basket, setBasket] = useState([]);

  useEffect(() => {
    fetch('http://localhost:5000/basket')
      .then(res => res.json())
      .then(setBasket);
  }, []);

  const addToBasket = async (item) => {
    const res = await fetch('http://localhost:5000/basket', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(item)
    });
    const newItem = await res.json();
    setBasket([...basket, newItem]);
  };

  const removeFromBasket = async (id) => {
    await fetch(`http://localhost:5000/basket/${id}`, { method: 'DELETE' });
    setBasket(basket.filter(item => item.id !== id));
  };

  const clearBasket = async () => {
    for (let item of basket) {
      await fetch(`http://localhost:5000/basket/${item.id}`, { method: 'DELETE' });
    }
    setBasket([]);
  };

  return { basket, addToBasket, removeFromBasket, clearBasket };
}
