/**
 * Helper function to make API calls to WordPress REST API
 * @param {string} endpoint - The API endpoint name
 * @param {string} method - HTTP method (GET, POST, etc.)
 * @param {object} data - Data to send with the request
 * @returns {Promise} - Promise that resolves with the API response
 */
export const apiCall = async (endpoint, method = 'POST', data = {}) => {
  // Use the full API URL from PHP to support WordPress installations in subdirectories
  const apiUrl = window.envatoElements?.api_url || `/wp-json/${window.envatoElements?.api_namespace || 'envato-elements/v2'}/`;
  const url = `${apiUrl}${endpoint}`;
  
  const options = {
    method,
    credentials: 'same-origin',
    headers: {
      'X-WP-Nonce': window.envatoElements?.nonce || ''
    }
  };

  if (method === 'POST' && !(data instanceof FormData)) {
    options.headers['Content-Type'] = 'application/json';
    options.body = JSON.stringify(data);
  } else if (data instanceof FormData) {
    options.body = data;
  }

  const response = await fetch(url, options);
  const result = await response.json();

  if (!response.ok || result.error) {
    const error = result.error || {};
    throw new Error(error.message || 'API call failed');
  }

  return result;
};


