/**
 * Elementor Content Bridge
 *
 * Extracts live content from the Elementor editor preview iframe
 * for SEO analysis (focus keyword checks, readability, density, etc.).
 */

/**
 * Check if we're inside the Elementor post editor.
 */
export const isElementorEditor = () =>
  Boolean(window.elementor) &&
  Boolean(document.getElementById('elementor-preview-iframe'));

/**
 * Extract rendered HTML from Elementor's preview iframe.
 */
export const getElementorContent = () => {
  try {
    const iframe = document.getElementById('elementor-preview-iframe');
    if (!iframe?.contentDocument) return '';

    const doc = iframe.contentDocument;

    // Prefer the post/page content wrapper (excludes header/footer templates)
    const postContent =
      doc.querySelector('.elementor[data-elementor-type="wp-post"]') ||
      doc.querySelector('.elementor[data-elementor-type="wp-page"]') ||
      doc.querySelector('.elementor-inner') ||
      doc.querySelector('.elementor');

    if (!postContent) return '';

    return postContent.innerHTML;
  } catch {
    return '';
  }
};

/**
 * Get the post title from Elementor's page settings model.
 */
export const getElementorTitle = () => {
  try {
    // Live value from the page settings Backbone model
    const liveTitle = window.elementor?.settings?.page?.model?.get?.('post_title');
    if (liveTitle) return liveTitle;

    // Fallback: initial config snapshot
    return window.elementor?.config?.initial_document?.settings?.settings?.post_title || '';
  } catch {
    return '';
  }
};

/**
 * Get the live permalink/URL from Elementor's page settings.
 * Synthesises from the live slug when the full permalink isn't available.
 */
export const getElementorPermalink = () => {
  try {
    // Elementor exposes the permalink in the config
    const permalink = window.elementor?.config?.initial_document?.urls?.permalink;

    // Live slug from page-settings model (updates when user edits slug)
    const liveSlug = window.elementor?.settings?.page?.model?.get?.('post_name');
    const initialSlug =
      window.elementor?.config?.initial_document?.settings?.settings?.post_name || '';

    if (liveSlug && permalink) {
      // Replace the last path segment with the live slug
      const base = permalink.replace(/\/[^/]*\/?$/, '/');
      return `${base}${liveSlug}/`;
    }

    if (permalink) return permalink;

    // Last resort: build from origin + slug
    if (liveSlug || initialSlug) {
      return `${window.location.origin}/${liveSlug || initialSlug}/`;
    }

    return '';
  } catch {
    return '';
  }
};

/**
 * Subscribe to Elementor content changes.
 * Returns an unsubscribe function.
 */
export const subscribeToElementorChanges = (callback) => {
  if (!window.elementor) return () => {};

  const cleanups = [];

  // Widget / section content edits
  try {
    const channel = window.elementor.channels?.editor;
    if (channel) {
      channel.on('change', callback);
      cleanups.push(() => channel.off('change', callback));
    }
  } catch { /* ignore */ }

  // Page-settings changes (title, slug, etc.)
  try {
    const pageModel = window.elementor?.settings?.page?.model;
    if (pageModel) {
      pageModel.on('change', callback);
      cleanups.push(() => pageModel.off('change', callback));
    }
  } catch { /* ignore */ }

  // Document lifecycle (initial load / template switch)
  try {
    window.elementor.on('document:loaded', callback);
    cleanups.push(() => window.elementor.off('document:loaded', callback));
  } catch { /* ignore */ }

  // Preview iframe load (catches late renders)
  try {
    const iframe = document.getElementById('elementor-preview-iframe');
    if (iframe) {
      const onLoad = () => callback();
      iframe.addEventListener('load', onLoad);
      cleanups.push(() => iframe.removeEventListener('load', onLoad));
    }
  } catch { /* ignore */ }

  // Polling fallback — iframe re-renders not covered by events
  const intervalId = window.setInterval(callback, 2000);
  cleanups.push(() => window.clearInterval(intervalId));

  return () => cleanups.forEach((fn) => fn());
};
