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

/**
 * Context for tracking band iteration state
 * Used to provide current data item to elements inside bands
 */
const BandContext = createContext();

export function BandProvider({ children, bandDataMap = {} }) {
  // Map of bandId -> current data item
  // Can be provided externally or managed internally
  const [internalBandData, setInternalBandData] = useState({});

  // Use external bandDataMap if provided, otherwise use internal state
  const currentBandData = Object.keys(bandDataMap).length > 0 ? bandDataMap : internalBandData;

  const setBandData = (bandId, data) => {
    setInternalBandData(prev => ({
      ...prev,
      [bandId]: data
    }));
  };

  const clearBandData = () => {
    setInternalBandData({});
  };

  const removeBandData = (bandId) => {
    setInternalBandData(prev => {
      const newData = { ...prev };
      delete newData[bandId];
      return newData;
    });
  };

  return (
    <BandContext.Provider value={{ currentBandData, setBandData, clearBandData, removeBandData }}>
      {children}
    </BandContext.Provider>
  );
}

export function useBandContext() {
  const context = useContext(BandContext);
  if (!context) {
    throw new Error('useBandContext must be used within a BandProvider');
  }
  return context;
}
