/**
 * ProRank SEO – Webpack runtime public path fixer.
 *
 * Ensures code-split chunks load from this plugin's `build/` directory.
 *
 * In some WordPress admin environments, webpack's `publicPath: 'auto'` can
 * incorrectly resolve to `/wp-includes/js/dist/`, causing ChunkLoadError when
 * loading lazy chunks.
 */

/* global __webpack_public_path__ */

try {
  let buildBase = '';

  // Preferred: PHP-localized plugin URL (most reliable when present).
  if (
    typeof window !== 'undefined' &&
    window.prorankSeoAdmin &&
    typeof window.prorankSeoAdmin.pluginUrl === 'string' &&
    window.prorankSeoAdmin.pluginUrl.length > 0
  ) {
    buildBase = window.prorankSeoAdmin.pluginUrl.replace(/\/+$/, '') + '/build/';
  }

  // Fallback: derive from the currently executing script tag.
  if (!buildBase && typeof document !== 'undefined') {
    let src = '';

    if (document.currentScript && typeof document.currentScript.src === 'string') {
      src = document.currentScript.src;
    }

    if (!src) {
      const scriptEl = document.getElementById('prorank-seo-admin-js');
      if (scriptEl && typeof scriptEl.getAttribute === 'function') {
        src = scriptEl.getAttribute('src') || '';
      }
    }

    if (!src) {
      const scripts = document.getElementsByTagName('script');
      for (let index = 0; index < scripts.length; index++) {
        const script = scripts[index];
        if (
          script &&
          typeof script.src === 'string' &&
          script.src.includes('/wp-content/plugins/') &&
          script.src.includes('/build/')
        ) {
          src = script.src;
          break;
        }
      }
    }

    if (src) {
      buildBase = src.replace(/\?.*$/, '').replace(/\/[^/]+$/, '/');
    }
  }

  if (buildBase) {
    __webpack_public_path__ = buildBase;
  }
} catch (e) {
  // Ignore - fallback to webpack runtime auto detection.
}
