/* global wp */
/**
 * Setup apiFetch middleware
 *
 * Configures WordPress apiFetch with proper nonce and root URL
 * This should be called once when the app initializes
 */
import apiFetch from '@wordpress/api-fetch';

let isConfigured = false;

export function setupApiFetch() {
  // Only configure once
  if (isConfigured) {
    return;
  }

  // Get nonce and REST URL from localized data
  // Check both possible variable names
  const data =
    window.prorankSeo ||
    window.prorankSeoAdmin ||
    window.proRankSEO ||
    window.proRankSeoAdmin ||
    {};
  const nonce = data.nonce || data.restNonce || window.wpApiSettings?.nonce;
  const restUrl = data.restUrl || window.wpApiSettings?.root;

  if (nonce && restUrl) {
    // Set up nonce middleware for authentication
    apiFetch.use(apiFetch.createNonceMiddleware(nonce));

    // Set up root URL middleware
    // restUrl should be the base WordPress REST URL (e.g., /wp-json/)
    apiFetch.use(apiFetch.createRootURLMiddleware(restUrl));

    isConfigured = true;
  } else {
  }
}

export default setupApiFetch;
