import React, { createContext, useState, useCallback, useEffect, useMemo } from 'react';
import useMetronomeState from '../hooks/useMetronomeState';

// Create a global context
export const GlobalContext = createContext({});

export const GlobalProvider = ({ children }) => {
  // Add global state or functions here as needed

  const [trackVolumeObject, setTrackVolumeObject] = useState({
    bIsMediaFile: false,
    broadcast: false,
    clientID: "",
    instrumentID: "",
    master: false,
    monitor: false,
    mute: false,
    name: "",
    objectName: "",
    record: false,
    volL: 0,
    volR: 0,
    wigetID: ""
  });

  const [globalObject, setGlobalObject] = useState({
    JK: window.JK || {},
    //ExternalVideoActions: window.ExternalVideoActions || null,
    //RecordingActions: window.RecordingActions || null,
  });

  const [videoEnabled, setVideoEnabled] = useState(false);

  // Metronome state management
  const {
    metronomeState,
    updateMetronomeState,
    openMetronome,
    closeMetronome,
    resetMetronome
  } = useMetronomeState();

  // Metronome callback handler - called by backend via execute_script
  const handleMetronomeCallback2 = useCallback((args) => {
    console.log('Metronome callback received:', args);
    // Backend sends: { bpm, cricket, meter, playback, sound }
    updateMetronomeState({
      ...args,
      isOpen: true // Backend callback means metronome is open
    });
  }, [updateMetronomeState]);

  // Register the callback globally when component mounts
  useEffect(() => {
    if (!globalObject.JK) {
      setGlobalObject(prev => ({
        ...prev,
        JK: {}
      }));
    }

    // Ensure JK object exists on window
    if (!window.JK) {
      window.JK = {};
    }

    // Register the callback
    window.JK.HandleMetronomeCallback2 = handleMetronomeCallback2;

    // Also register on globalObject for consistency
    setGlobalObject(prev => ({
      ...prev,
      JK: {
        ...prev.JK,
        HandleMetronomeCallback2: handleMetronomeCallback2
      }
    }));
  }, [handleMetronomeCallback2]);

  // Memoize context value to prevent unnecessary re-renders
  // useState setters (setTrackVolumeObject, setGlobalObject) are stable and don't need to be dependencies
  const value = useMemo(() => ({
    trackVolumeObject,
    setTrackVolumeObject,
    globalObject,
    setGlobalObject,
    // Metronome state and functions
    metronomeState,
    updateMetronomeState,
    openMetronome,
    closeMetronome,
    resetMetronome,
  }), [
    trackVolumeObject,
    globalObject,
    metronomeState,
    updateMetronomeState,
    openMetronome,
    closeMetronome,
    resetMetronome
  ]);

  return (
    <GlobalContext.Provider value={value}>
      {children}
    </GlobalContext.Provider>
  );
};

export const useGlobalContext = () => React.useContext(GlobalContext);
