/* global wp */
/**
 * WordPress URL Helpers
 *
 * Provides WordPress-compatible URL functions for React components
 * Uses localized data from wp_localize_script
 */

// Get the localized data
const proRankData = window.proRankSEO ?? {};

/**
 * Get WordPress admin URL
 *
 * @param {string} path - Optional path to append to admin URL
 * @return {string} Admin URL
 */
export function adminUrl(path = '') {
  const baseUrl = proRankData.adminUrl ?? '/wp-admin/';

  // Ensure path doesn't start with /
  if (path.length > 0 && path.startsWith('/')) {
    path = path.substring(1);
  }

  // Ensure baseUrl ends with /
  const url = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`;

  return url + path;
}

/**
 * Get WordPress admin page URL
 *
 * @param {string} page   - Admin page slug
 * @param {Object} params - Query parameters
 * @return {string} Admin page URL
 */
export function adminPageUrl(page, params = {}) {
  let url = adminUrl(`admin.php?page=${page}`);

  // Add additional parameters
  Object.keys(params).forEach((key) => {
    url += `&${key}=${encodeURIComponent(params[key])}`;
  });

  return url;
}

/**
 * Get ProRank SEO admin page URL
 *
 * @param {string} subpage - ProRank subpage
 * @param {Object} params  - Query parameters
 * @return {string} ProRank admin page URL
 */
export function proRankAdminUrl(subpage = '', params = {}) {
  const page = subpage ? `prorank-seo-${subpage}` : 'prorank-seo';
  return adminPageUrl(page, params);
}

/**
 * Make admin_url available globally for backward compatibility
 * This ensures any code expecting a global admin_url function will work
 */
if (typeof window.admin_url === 'undefined') {
  window.admin_url = adminUrl;
}

// Export all WordPress URL helpers
export const wpUrls = {
  admin: adminUrl,
  adminPage: adminPageUrl,
  proRankAdmin: proRankAdminUrl,
  apiUrl: proRankData.apiUrl,
  supportUrl: proRankData.urls?.support,
  pricingUrl: proRankData.urls?.pricing,
};

export default wpUrls;
