/**
 * Editor Sidebar Entry Point
 *
 * Registers the ProRank SEO sidebar plugin for the Block Editor.
 * Uses window.wp.* directly to avoid ES module timing issues.
 *
 * @package
 */

// Import styles (no dependencies)
import './styles.css';

const resolvePluginUrl = () => {
  const candidates = [
    window?.proRankSidebar?.pluginUrl,
    window?.prorankSeo?.pluginUrl,
    window?.prorankSeoAdmin?.pluginUrl,
    window?.prorankSeoEditor?.pluginUrl,
    window?.proRankSEO?.pluginUrl,
    window?.proRankSeoAdmin?.pluginUrl,
  ];

  for (const candidate of candidates) {
    if (typeof candidate === 'string' && candidate.length > 0) {
      return candidate;
    }
  }

  if (typeof document === 'undefined') {
    return '';
  }

  const scripts = document.getElementsByTagName('script');
  for (let index = 0; index < scripts.length; index += 1) {
    const src = scripts[index]?.src || '';
    if (!src) {
      continue;
    }
    if (src.includes('/wp-content/plugins/') && src.includes('/build/') && src.includes('/prorank')) {
      return src.replace(/\?.*$/, '').replace(/\/build\/[^/]+$/, '/');
    }
  }

  return '';
};

const pluginUrl = resolvePluginUrl();
const proRankLogoUrl = pluginUrl ? `${pluginUrl.replace(/\/+$/, '')}/assets/images/favicon.png` : '';

// Prevent duplicate registration
let sidebarRegistered = false;

/**
 * Wait for WordPress to be fully initialized
 */
const waitForWordPress = (callback, maxAttempts = 50) => {
  let attempts = 0;

  const check = () => {
    attempts++;

    const hasPlugins = window.wp?.plugins?.registerPlugin;
    const hasLegacySidebar = !window.wp?.editor && window.wp?.editPost?.PluginSidebar;
    const hasEditor = window.wp?.editor?.PluginSidebar || hasLegacySidebar;
    const hasI18n = window.wp?.i18n?.__;
    const hasElement = window.wp?.element?.createElement;

    if (hasPlugins && hasEditor && hasI18n && hasElement) {
      callback();
      return;
    }

    if (attempts < maxAttempts) {
      setTimeout(check, 100);
    } else {
      console.warn('[ProRank SEO] WordPress sidebar dependencies not available after timeout');
    }
  };

  check();
};

/**
 * Initialize the sidebar
 */
const initSidebar = () => {
  // Prevent duplicate registration
  if (sidebarRegistered) {
    return;
  }

  const { createElement, lazy, Suspense, Fragment } = window.wp.element;
  const { registerPlugin, getPlugin } = window.wp.plugins;
  const { __ = (text) => text } = window.wp?.i18n || {};
  const { Spinner } = window.wp.components;

  // Check if already registered
  if (getPlugin && getPlugin('prorank-seo-sidebar')) {
    sidebarRegistered = true;
    return;
  }

  // Prefer wp.editor slotfills on modern WordPress and only touch wp.editPost on older installs.
  const editor = window.wp.editor || {};
  const legacyEditPost = !window.wp.editor ? (window.wp.editPost || {}) : {};
  const PluginSidebar = editor.PluginSidebar || legacyEditPost.PluginSidebar;
  const PluginSidebarMoreMenuItem =
    editor.PluginSidebarMoreMenuItem || legacyEditPost.PluginSidebarMoreMenuItem;

  if (!PluginSidebar) {
    console.warn('[ProRank SEO] PluginSidebar components not available');
    return;
  }

  // ProRank SEO Icon - prefer the real plugin SVG file when available.
  const ProRankIcon = ({ size = 24 }) => {
    if (proRankLogoUrl) {
      return createElement('img', {
        src: proRankLogoUrl,
        width: size,
        height: size,
        alt: 'ProRank SEO',
        style: { display: 'block' },
      });
    }

    return createElement(
      'svg',
      {
        width: size,
        height: size,
        viewBox: '0 0 24 24',
        fill: 'none',
        xmlns: 'http://www.w3.org/2000/svg',
      },
      // Outer hexagon shape
      createElement('path', {
        d: 'M12 2L4 6.5V17.5L12 22L20 17.5V6.5L12 2Z',
        fill: 'currentColor',
        fillOpacity: '0.15',
        stroke: 'currentColor',
        strokeWidth: '1.5',
        strokeLinecap: 'round',
        strokeLinejoin: 'round',
      }),
      // Inner rising bar chart representing SEO growth
      createElement('path', {
        d: 'M8 15V13',
        stroke: 'currentColor',
        strokeWidth: '2',
        strokeLinecap: 'round',
      }),
      createElement('path', {
        d: 'M12 15V10',
        stroke: 'currentColor',
        strokeWidth: '2',
        strokeLinecap: 'round',
      }),
      createElement('path', {
        d: 'M16 15V7',
        stroke: 'currentColor',
        strokeWidth: '2',
        strokeLinecap: 'round',
      })
    );
  };

  // Lazy load the EditorSidebar component
  const EditorSidebar = lazy(() =>
    import(/* webpackMode: "eager" */ './EditorSidebar').catch((err) => {
      console.error('[ProRank SEO] Failed to load EditorSidebar:', err);
      return {
        default: () =>
          createElement(
            'div',
            { style: { padding: '16px', color: '#856404', background: '#fff3cd' } },
            __('Failed to load sidebar. Please refresh.', 'prorank-seo')
          ),
      };
    })
  );

  // Loading fallback
  const LoadingFallback = createElement(
    'div',
    {
      style: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '20px',
        gap: '10px',
      },
    },
    Spinner && createElement(Spinner, null),
    createElement('span', null, __('Loading...', 'prorank-seo'))
  );

  // Register the plugin
  registerPlugin('prorank-seo-sidebar', {
    icon: createElement(ProRankIcon, { size: 20 }),
    render: () =>
      createElement(
        Fragment,
        null,
        PluginSidebarMoreMenuItem
          ? createElement(
              PluginSidebarMoreMenuItem,
              { target: 'prorank-seo-sidebar', icon: createElement(ProRankIcon, { size: 20 }) },
              __('ProRank SEO', 'prorank-seo')
            )
          : null,
        createElement(
          PluginSidebar,
          {
            name: 'prorank-seo-sidebar',
            title: __('ProRank SEO', 'prorank-seo'),
            icon: createElement(ProRankIcon, { size: 20 }),
            className: 'prorank-plugin-sidebar',
            isPinnable: true,
          },
          createElement(Suspense, { fallback: LoadingFallback }, createElement(EditorSidebar, null))
        )
      ),
  });

  sidebarRegistered = true;
};

// Start initialization when DOM is ready
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', () => {
    waitForWordPress(initSidebar);
  });
} else {
  waitForWordPress(initSidebar);
}
