/**
 * Beaver Builder Content Bridge
 *
 * Extracts live content from the Beaver Builder editor for SEO analysis.
 * BB uses a responsive iframe UI: parent window has the builder chrome,
 * child iframe renders the actual page content.
 *
 * Detection: ?fl_builder URL parameter + body class fl-builder-edit.
 */

/**
 * Get the Beaver Builder content iframe.
 */
const getBBIframe = () =>
  document.querySelector('.fl-builder-iframe-content') ||
  document.querySelector('iframe.fl-builder-ui-iframe') ||
  document.getElementById('fl-builder-iframe');

/**
 * Check if we're inside an *active* Beaver Builder session.
 *
 * Requires either the editor body class or the FLBuilder global
 * paired with an active iframe — prevents hijacking normal post.php.
 */
export const isBeaverBuilderEditor = () => {
  // Body class set only while the editor is running
  if (document.body?.classList?.contains('fl-builder-edit')) return true;

  // FLBuilder global + iframe confirms active session
  if (window.FLBuilder && getBBIframe()) return true;

  // FLBuilderConfig with postId is a strong signal
  if (window.FLBuilderConfig?.postId) return true;

  return false;
};

/**
 * Extract rendered HTML from Beaver Builder's content iframe.
 */
export const getBeaverBuilderContent = () => {
  try {
    // Try iframe content first (responsive iframe UI mode)
    const iframe = getBBIframe();
    if (iframe?.contentDocument) {
      const contentEl =
        iframe.contentDocument.querySelector('.fl-builder-content') ||
        iframe.contentDocument.querySelector('.fl-row');
      if (contentEl) return contentEl.innerHTML;
    }

    // Fallback: BB renders directly in page (iframe UI disabled)
    const directContent = document.querySelector('.fl-builder-content');
    if (directContent) return directContent.innerHTML;

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

/**
 * Get the post title from Beaver Builder's config or the page.
 */
export const getBeaverBuilderTitle = () => {
  try {
    // FLBuilderConfig may have the title
    if (window.FLBuilderConfig?.postTitle) {
      return window.FLBuilderConfig.postTitle;
    }

    // wp.data store if available
    const editor = window.wp?.data?.select?.('core/editor');
    if (editor?.getEditedPostAttribute) {
      const title = editor.getEditedPostAttribute('title');
      if (title) return title;
    }

    // DOM fallback — page <title> or h1
    const h1 = document.querySelector('h1.entry-title, h1.page-title, h1');
    if (h1) return h1.textContent.trim();

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

/**
 * Get the live permalink from Beaver Builder's context.
 * The VB URL is the page URL + ?fl_builder — strip it.
 */
export const getBeaverBuilderPermalink = () => {
  try {
    const url = new URL(window.location.href);
    if (url.searchParams.has('fl_builder')) {
      url.searchParams.delete('fl_builder');
      url.searchParams.delete('fl_builder_ui');
      url.searchParams.delete('fl_builder_ui_iframe');
      const clean = url.toString();
      return clean.replace(/\?$/, '');
    }

    // Fallback via wp.data
    const postId = window.FLBuilderConfig?.postId;
    if (postId) {
      const editor = window.wp?.data?.select?.('core/editor');
      if (editor?.getPermalink) return editor.getPermalink() || '';
      if (editor?.getCurrentPost?.()?.link) return editor.getCurrentPost().link;
    }

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

/**
 * Subscribe to Beaver Builder content changes.
 * Returns an unsubscribe function.
 */
export const subscribeToBeaverBuilderChanges = (callback) => {
  const cleanups = [];
  const $ = window.jQuery;

  if ($) {
    // Layout rendered / re-rendered (content changed)
    try {
      $(document).on('fl-builder.layout-rendered.prorankSeo', callback);
      cleanups.push(() => $(document).off('fl-builder.layout-rendered.prorankSeo'));
    } catch { /* ignore */ }

    // Preview rendered (live settings change)
    try {
      $(document).on('fl-builder.preview-rendered.prorankSeo', callback);
      cleanups.push(() => $(document).off('fl-builder.preview-rendered.prorankSeo'));
    } catch { /* ignore */ }

    // Node settings saved
    try {
      $(document).on('fl-builder.didSaveNodeSettings.prorankSeo', callback);
      cleanups.push(() => $(document).off('fl-builder.didSaveNodeSettings.prorankSeo'));
    } catch { /* ignore */ }

    // Also listen on the content element if available
    try {
      const $content = $('.fl-builder-content');
      if ($content.length) {
        $content.on('fl-builder.layout-rendered.prorankSeo', callback);
        cleanups.push(() => $content.off('fl-builder.layout-rendered.prorankSeo'));
      }
    } catch { /* ignore */ }
  }

  // Iframe load event
  try {
    const iframe = getBBIframe();
    if (iframe) {
      const onLoad = () => callback();
      iframe.addEventListener('load', onLoad);
      cleanups.push(() => iframe.removeEventListener('load', onLoad));
    }
  } catch { /* ignore */ }

  // Polling fallback
  const intervalId = window.setInterval(callback, 2000);
  cleanups.push(() => window.clearInterval(intervalId));

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