// assets/peligent-ai-embed.js
// Use jQuery if available (WordPress includes it)
(function ($) {
  'use strict';
  const logDebug = window.PELIGENT_AI_DEBUG ? console.log.bind(console) : () => { };

  logDebug('[peligent-ai-embed] Script file loaded!');
  window.PELIGENT_AI_EMBED_LOADED = true;

  if (!window.PELIGENT_AI_CLIENT) {
    console.warn('[peligent-ai-embed] PELIGENT_AI_CLIENT not found. Available:', Object.keys(window).filter(k => k.includes('WPAI')));
    return;
  }
  const { server, token, site_url } = window.PELIGENT_AI_CLIENT;
  if (!server || !token) {
    console.warn('[peligent-ai-embed] Missing server or token');
    return;
  }
  logDebug('[peligent-ai-embed] Initialized with server:', server);

  const ORIGIN = server.replace(/\/+$/, '');
  const EMBED_URL = ORIGIN + '/embed';

  const MAX_RETRIES = 15;
  const RETRY_MS = 400;
  const sentMap = new WeakMap();

  const initBackend = async () => {
    try {
      await fetch(ORIGIN + '/client/init', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-Site-Token': token },
        body: JSON.stringify({ site_url })
      });
    } catch (e) {
      // swallow
    }
  };

  const sendTokenOnce = (iframe) => {
    if (!iframe || !iframe.contentWindow) return;
    try {
      iframe.contentWindow.postMessage({ type: 'PELIGENT_AI_TOKEN', token }, ORIGIN);
    } catch (e) {
      console.warn('Could not send token to iframe:', e);
    }
  };

  const startTokenLoop = (iframe) => {
    if (!iframe) return;
    if (!sentMap.has(iframe)) sentMap.set(iframe, { timer: null, tries: 0, ack: false });
    const s = sentMap.get(iframe);
    if (s.timer) clearInterval(s.timer);
    s.tries = 0; s.ack = false;
    if (!iframe.src || iframe.src === 'about:blank') iframe.src = iframe.dataset.src || EMBED_URL;
    sendTokenOnce(iframe);
    s.timer = setInterval(() => {
      if (s.ack) { clearInterval(s.timer); s.timer = null; return; }
      s.tries++;
      if (s.tries > MAX_RETRIES) { clearInterval(s.timer); s.timer = null; return; }
      sendTokenOnce(iframe);
    }, RETRY_MS);
  };

  const wireIframe = (iframe) => {
    if (!iframe || iframe.dataset._peligentAiWired) return;
    iframe.dataset._peligentAiWired = '1';
    iframe.addEventListener('load', () => {
      setTimeout(() => startTokenLoop(iframe), 120);
    });
  };

  logDebug('[peligent-ai-embed] Setting up message listener');
  // Test: Send a test message to verify script is loaded
  logDebug('[peligent-ai-embed] Script is running! Window location:', window.location.href);

  window.addEventListener('message', (ev) => {
    if (!ev) return;
    // Only accept messages from the expected embed origin or same origin
    if (ev.origin !== ORIGIN && ev.origin !== window.location.origin) return;
    const data = ev.data || {};
    logDebug('[peligent-ai-embed] Received message from:', ev.origin, 'type:', data.type);
    if (data.type === 'PELIGENT_AI_ACK') {
      document.querySelectorAll('iframe.peligent-ai-iframe').forEach((ifr) => {
        if (ifr.contentWindow === ev.source) {
          const s = sentMap.get(ifr);
          if (s) { s.ack = true; if (s.timer) { clearInterval(s.timer); s.timer = null; } }
          // Feature 7: Send page context after ACK
          if (window.PELIGENT_PAGE_CONTEXT) {
            try { ifr.contentWindow.postMessage({ type: 'PELIGENT_AI_PAGE_CONTEXT', context: window.PELIGENT_PAGE_CONTEXT }, ORIGIN); } catch (e) {}
          }
          // Feature 9: Send pending prompt if queued
          if (window._peligentPendingPrompt) {
            try { ifr.contentWindow.postMessage({ type: 'PELIGENT_AI_PROMPT', prompt: window._peligentPendingPrompt }, ORIGIN); } catch (e) {}
            window._peligentPendingPrompt = null;
          }
          // Send pending generate content request if queued
          if (pendingGenerateContent) {
            setTimeout(() => {
              try { ifr.contentWindow.postMessage(pendingGenerateContent, ORIGIN); } catch (e) {}
              console.log('[Peligent] Sent queued generate content message after ACK');
              pendingGenerateContent = null;
            }, 500);
          }
        }
      });
    } else if (data.type === 'PELIGENT_AI_READY') {
      // Embed page is ready, send token immediately
      document.querySelectorAll('iframe.peligent-ai-iframe').forEach((ifr) => {
        if (ifr.contentWindow === ev.source) {
          sendTokenOnce(ifr);
          startTokenLoop(ifr);
        }
      });
    } else if (data.type === 'PELIGENT_AI_RESIZE' && typeof data.height === 'number') {
      document.querySelectorAll('iframe.peligent-ai-iframe').forEach((ifr) => {
        if (ifr.contentWindow === ev.source) {
          const container = ifr.closest('.peligent-ai-iframe-container');
          if (container) {
            const minHeight = 400;
            const newHeight = Math.max(minHeight, data.height);
            container.style.minHeight = newHeight + 'px';
          } else {
            // Fallback for old structure
            ifr.style.height = Math.max(320, data.height) + 'px';
          }
        }
      });
    } else if (data.type === 'PELIGENT_AI_CLOSE') {
      // Hide the sidebar and unload iframe to stop requests
      logDebug('[peligent-ai-embed] Received PELIGENT_AI_CLOSE message');
      const sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
      if (sidebar) {
        // Exit fullscreen if active before closing
        sidebar.classList.remove('peligent-ai-fullscreen');
        document.body.classList.remove('peligent-ai-fullscreen');
        sidebar.classList.add('peligent-ai-hidden');
        document.body.classList.add('peligent-ai-sidebar-hidden');
        try { localStorage.setItem('peligent_ai_sidebar_visible', '0'); } catch { }
        // Keep iframe alive (dont unload) so in-progress streams continue
        const closeIframe = sidebar.querySelector('iframe.peligent-ai-iframe');
        if (false && closeIframe) { // Disabled: keep iframe alive when sidebar closes
          closeIframe.src = 'about:blank';
        }
        logDebug('[peligent-ai-embed] Sidebar hidden and iframe unloaded');
      }
    } else if (data.type === 'PELIGENT_AI_TOKEN_REQUEST') {
      // Iframe is requesting a fresh token (e.g. after auth failure)
      logDebug('[peligent-ai-embed] Received PELIGENT_AI_TOKEN_REQUEST - re-sending token');
      document.querySelectorAll('iframe.peligent-ai-iframe').forEach((ifr) => {
        if (ifr.contentWindow === ev.source) {
          sendTokenOnce(ifr);
        }
      });
    } else if (data.type === 'PELIGENT_AI_FULLSCREEN') {
      // Toggle fullscreen mode
      logDebug('[peligent-ai-embed] Received PELIGENT_AI_FULLSCREEN message');
      const sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
      logDebug('[peligent-ai-embed] Sidebar element:', sidebar);
      if (sidebar) {
        const isFullscreen = sidebar.classList.contains('peligent-ai-fullscreen');
        const iframe = sidebar.querySelector('iframe.peligent-ai-iframe');
        logDebug('[peligent-ai-embed] Current fullscreen state:', isFullscreen);
        logDebug('[peligent-ai-embed] Current sidebar classes:', sidebar.className);

        if (isFullscreen) {
          // Exit fullscreen mode
          sidebar.classList.remove('peligent-ai-fullscreen');
          document.body.classList.remove('peligent-ai-fullscreen');
          logDebug('[peligent-ai-embed] Exited fullscreen mode. Sidebar classes:', sidebar.className);
          logDebug('[peligent-ai-embed] Body classes:', document.body.className);

          // Notify iframe about fullscreen state (no URL change needed)
          if (iframe && iframe.contentWindow) {
            try {
              iframe.contentWindow.postMessage({ type: 'WPAI_FULLSCREEN_STATE', fullscreen: false }, ORIGIN);
            } catch (e) { }
          }
        } else {
          // Enter fullscreen mode
          sidebar.classList.add('peligent-ai-fullscreen');
          document.body.classList.add('peligent-ai-fullscreen');
          logDebug('[peligent-ai-embed] Entered fullscreen mode. Sidebar classes:', sidebar.className);
          logDebug('[peligent-ai-embed] Body classes:', document.body.className);

          // Notify iframe about fullscreen state (no URL change needed)
          if (iframe && iframe.contentWindow) {
            try {
              logDebug('[peligent-ai-embed] Sending fullscreen=true to iframe (from message handler)');
              iframe.contentWindow.postMessage({ type: 'WPAI_FULLSCREEN_STATE', fullscreen: true }, ORIGIN);
            } catch (e) {
              console.error('[peligent-ai-embed] Failed to send fullscreen message:', e);
            }
          } else {
            console.warn('[peligent-ai-embed] Iframe not found for fullscreen notification');
          }
        }
      } else {
        console.warn('[peligent-ai-embed] Sidebar not found. Available elements:', document.querySelectorAll('aside, .peligent-ai-fixed-sidebar'));
      }
    }
  });

  // Handle resize functionality - using jQuery
  const initResize = () => {
    logDebug('[peligent-ai-embed] Initializing resize functionality...');
    const $sidebar = $('.peligent-ai-fixed-sidebar');
    const $resizeHandle = $('.peligent-ai-resize-handle');

    if ($sidebar.length === 0 || $resizeHandle.length === 0) {
      console.warn('[peligent-ai-embed] Sidebar or resize handle not found');
      return;
    }

    let isResizing = false;
    let startX = 0;
    let startWidth = 0;
    const minWidth = 480;
    const maxWidth = Math.min(window.innerWidth * 0.45, 960);

    // Use jQuery for event handlers
    $resizeHandle.off('mousedown').on('mousedown', function (e) {
      isResizing = true;
      startX = e.clientX;
      startWidth = $sidebar[0].offsetWidth;
      $('body').css({
        'cursor': 'col-resize',
        'user-select': 'none'
      });
      e.preventDefault();
      logDebug('[peligent-ai-embed] Resize started, width:', startWidth);
    });

    $(document).off('mousemove.peligent-ai-resize').on('mousemove.peligent-ai-resize', function (e) {
      if (!isResizing) return;

      // Check if RTL
      const isRTL = document.documentElement.dir === 'rtl' ||
        document.body.classList.contains('rtl') ||
        getComputedStyle(document.body).direction === 'rtl';

      let diff;
      if (isRTL) {
        // In RTL, sidebar is on the left, so dragging right increases width
        diff = e.clientX - startX;
      } else {
        // In LTR, sidebar is on the right, so dragging left increases width
        diff = startX - e.clientX;
      }

      let newWidth = startWidth + diff;
      if (newWidth < minWidth) newWidth = minWidth;
      if (newWidth > maxWidth) newWidth = maxWidth;

      $sidebar.css('width', newWidth + 'px');

      // Update margin based on RTL/LTR
      if (isRTL) {
        $('#wpcontent, #wpbody-content').css('margin-left', newWidth + 'px');
      } else {
        $('#wpcontent, #wpbody-content').css('margin-right', newWidth + 'px');
      }

      try { localStorage.setItem('peligent_ai_sidebar_width', String(newWidth)); } catch { }
    });

    $(document).off('mouseup.peligent-ai-resize').on('mouseup.peligent-ai-resize', function () {
      if (isResizing) {
        isResizing = false;
        $('body').css({
          'cursor': '',
          'user-select': ''
        });
        logDebug('[peligent-ai-embed] Resize ended');
      }
    });

    logDebug('[peligent-ai-embed] Resize handlers attached');
  };

  // Handle header button clicks (close and maximize) - works with or without jQuery
  const initHeaderButtons = () => {
    logDebug('[peligent-ai-embed] Initializing header buttons...');

    const sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
    logDebug('[peligent-ai-embed] Sidebar found:', !!sidebar);

    if (!sidebar) {
      console.warn('[peligent-ai-embed] Sidebar not found');
      return;
    }

    // Close button - try jQuery first, fallback to vanilla JS
    const closeBtn = sidebar.querySelector('.peligent-ai-close-btn');
    logDebug('[peligent-ai-embed] Close button found:', !!closeBtn);

    if (closeBtn) {
      // Remove any existing handlers
      const newCloseBtn = closeBtn.cloneNode(true);
      closeBtn.parentNode.replaceChild(newCloseBtn, closeBtn);

      // Add click handler
      newCloseBtn.addEventListener('click', function (e) {
        e.preventDefault();
        e.stopPropagation();
        logDebug('[peligent-ai-embed] Close button clicked!');
        const sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
        if (sidebar) {
          sidebar.classList.add('peligent-ai-hidden');
          document.body.classList.add('peligent-ai-sidebar-hidden');
          try { localStorage.setItem('peligent_ai_sidebar_visible', '0'); } catch { }
          // Unload iframe to stop requests
          const iframe = sidebar.querySelector('iframe.peligent-ai-iframe');
          // Keep iframe alive when sidebar closes (preserves in-progress streams)
          // if (iframe && iframe.src !== 'about:blank') { iframe.src = 'about:blank'; }
          logDebug('[peligent-ai-embed] Sidebar hidden and iframe unloaded');
        }
      });
      logDebug('[peligent-ai-embed] Close button handler attached');
    } else {
      console.warn('[peligent-ai-embed] Close button not found!');
    }

    // Maximize button - try jQuery first, fallback to vanilla JS
    const maximizeBtn = sidebar.querySelector('.peligent-ai-maximize-btn');
    logDebug('[peligent-ai-embed] Maximize button found:', !!maximizeBtn);

    if (maximizeBtn) {
      // Remove any existing handlers
      const newMaximizeBtn = maximizeBtn.cloneNode(true);
      maximizeBtn.parentNode.replaceChild(newMaximizeBtn, maximizeBtn);

      // Add click handler
      newMaximizeBtn.addEventListener('click', function (e) {
        e.preventDefault();
        e.stopPropagation();
        logDebug('[peligent-ai-embed] Maximize button clicked!');
        const sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
        if (sidebar) {
          const isFullscreen = sidebar.classList.contains('peligent-ai-fullscreen');
          const iframe = sidebar.querySelector('iframe.peligent-ai-iframe');

          if (isFullscreen) {
            // Exit fullscreen mode
            sidebar.classList.remove('peligent-ai-fullscreen');
            document.body.classList.remove('peligent-ai-fullscreen');
            logDebug('[peligent-ai-embed] Exited fullscreen mode');

            // Notify iframe about fullscreen state (no URL change needed)
            if (iframe && iframe.contentWindow) {
              try {
                iframe.contentWindow.postMessage({ type: 'WPAI_FULLSCREEN_STATE', fullscreen: false }, ORIGIN);
              } catch (e) { }
            }
          } else {
            // Enter fullscreen mode
            sidebar.classList.add('peligent-ai-fullscreen');
            document.body.classList.add('peligent-ai-fullscreen');
            logDebug('[peligent-ai-embed] Entered fullscreen mode');

            // Notify iframe about fullscreen state (no URL change needed)
            if (iframe && iframe.contentWindow) {
              try {
                logDebug('[peligent-ai-embed] Sending fullscreen=true to iframe');
                iframe.contentWindow.postMessage({ type: 'WPAI_FULLSCREEN_STATE', fullscreen: true }, ORIGIN);
              } catch (e) {
                console.error('[peligent-ai-embed] Failed to send fullscreen message:', e);
              }
            } else {
              console.warn('[peligent-ai-embed] Iframe not found for fullscreen notification');
            }
          }
        }
      });
      logDebug('[peligent-ai-embed] Maximize button handler attached');
    } else {
      console.warn('[peligent-ai-embed] Maximize button not found!');
    }
  };

  // Handle admin bar icon click - works with or without jQuery
  const initAdminBarToggle = () => {
    logDebug('[peligent-ai-embed] Initializing admin bar toggle...');
    const chatIcon = document.querySelector('#wp-admin-bar-peligent-chat a');
    logDebug('[peligent-ai-embed] Admin bar chat icon found:', !!chatIcon);

    if (chatIcon) {
      // Remove existing handler by cloning
      const newChatIcon = chatIcon.cloneNode(true);
      chatIcon.parentNode.replaceChild(newChatIcon, chatIcon);

      newChatIcon.addEventListener('click', function (e) {
        e.preventDefault();
        const sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
        if (sidebar) {
          const isHidden = sidebar.classList.contains('peligent-ai-hidden');
          const iframe = sidebar.querySelector('iframe.peligent-ai-iframe');
          if (isHidden) {
            sidebar.classList.remove('peligent-ai-hidden');
            document.body.classList.remove('peligent-ai-sidebar-hidden');
            // Lazy-load iframe
            if (iframe && iframe.dataset.src && iframe.src !== iframe.dataset.src) {
              iframe.src = iframe.dataset.src;
            }
            try { localStorage.setItem('peligent_ai_sidebar_visible', '1'); } catch { }
            logDebug('[peligent-ai-embed] Sidebar shown, iframe loaded');
          } else {
            // Exit fullscreen if active before closing
            sidebar.classList.remove('peligent-ai-fullscreen');
            document.body.classList.remove('peligent-ai-fullscreen');
            sidebar.classList.add('peligent-ai-hidden');
            document.body.classList.add('peligent-ai-sidebar-hidden');
            // Unload iframe
            // Keep iframe alive when sidebar closes
            // if (iframe && iframe.src !== 'about:blank') { iframe.src = 'about:blank'; }
            try { localStorage.setItem('peligent_ai_sidebar_visible', '0'); } catch { }
            logDebug('[peligent-ai-embed] Sidebar hidden, iframe unloaded');
          }
        }
      });
      logDebug('[peligent-ai-embed] Admin bar toggle handler attached');
    } else {
      console.warn('[peligent-ai-embed] Admin bar chat icon not found');
    }
  };

  // Restore sidebar state from localStorage
  const restoreSidebarState = () => {
    const sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
    if (!sidebar) return;

    try {
      const visible = localStorage.getItem('peligent_ai_sidebar_visible');
      if (visible === '0') {
        sidebar.classList.add('peligent-ai-hidden');
        document.body.classList.add('peligent-ai-sidebar-hidden');
      }

      // Fullscreen is not persisted — resets on each page load for safety

      // Check if RTL
      const isRTL = document.documentElement.dir === 'rtl' ||
        document.body.classList.contains('rtl') ||
        getComputedStyle(document.body).direction === 'rtl';

      const width = localStorage.getItem('peligent_ai_sidebar_width');
      if (width) {
        const widthNum = parseInt(width, 10);
        if (!isNaN(widthNum) && widthNum >= 480) {
          sidebar.style.width = widthNum + 'px';
          const wpcontent = document.querySelector('#wpcontent');
          const wpbodyContent = document.querySelector('#wpbody-content');
          // Update margin based on RTL/LTR
          if (isRTL) {
            if (wpcontent) wpcontent.style.marginLeft = widthNum + 'px';
            if (wpbodyContent) wpbodyContent.style.marginLeft = widthNum + 'px';
          } else {
            if (wpcontent) wpcontent.style.marginRight = widthNum + 'px';
            if (wpbodyContent) wpbodyContent.style.marginRight = widthNum + 'px';
          }
        }
      }
    } catch (e) {
      // Ignore localStorage errors
    }
  };

  // Exit fullscreen helper — used by Escape key and floating exit buttons
  const exitFullscreen = () => {
    const sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
    if (!sidebar || !sidebar.classList.contains('peligent-ai-fullscreen')) return;
    sidebar.classList.remove('peligent-ai-fullscreen');
    document.body.classList.remove('peligent-ai-fullscreen');
    const iframe = sidebar.querySelector('iframe.peligent-ai-iframe');
    if (iframe && iframe.contentWindow) {
      try { iframe.contentWindow.postMessage({ type: 'WPAI_FULLSCREEN_STATE', fullscreen: false }, ORIGIN); } catch {}
    }
    logDebug('[peligent-ai-embed] Exited fullscreen');
  };

  const closeSidebar = () => {
    const sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
    if (!sidebar) return;
    if (sidebar.classList.contains('peligent-ai-fullscreen')) {
      sidebar.classList.remove('peligent-ai-fullscreen');
      document.body.classList.remove('peligent-ai-fullscreen');
    }
    sidebar.classList.add('peligent-ai-hidden');
    document.body.classList.add('peligent-ai-sidebar-hidden');
    try { localStorage.setItem('peligent_ai_sidebar_visible', '0'); } catch {}
    const iframe = sidebar.querySelector('iframe.peligent-ai-iframe');
    // Keep iframe alive when sidebar closes
    // if (iframe && iframe.src !== 'about:blank') iframe.src = 'about:blank';
  };

  // Escape key exits fullscreen
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') exitFullscreen();
  });

  // Wire floating fullscreen exit buttons
  const initFullscreenBar = () => {
    const minBtn = document.querySelector('.peligent-ai-fullscreen-minimize');
    const closeBtn = document.querySelector('.peligent-ai-fullscreen-close');
    if (minBtn) minBtn.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); exitFullscreen(); });
    if (closeBtn) closeBtn.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); closeSidebar(); });
  };


  // ====== Feature 8: Target Mode ======
  let targetOverlay = null;
  let targetHighlight = null;
  let targetActive = false;

  const activateTargetMode = () => {
    if (targetActive) { deactivateTargetMode(); return; }
    targetActive = true;
    const targetBtn = document.querySelector('.peligent-ai-target-btn');
    if (targetBtn) targetBtn.style.background = '#3b82f6';

    targetOverlay = document.createElement('div');
    targetOverlay.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,0.03);z-index:99998;cursor:crosshair;';
    // Exclude sidebar area from overlay
    const sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
    if (sidebar && !sidebar.classList.contains('peligent-ai-hidden')) {
      const sidebarW = sidebar.offsetWidth || 480;
      const isRTL = document.documentElement.dir === 'rtl' || getComputedStyle(document.body).direction === 'rtl';
      if (isRTL) { targetOverlay.style.left = sidebarW + 'px'; targetOverlay.style.right = '0'; }
      else { targetOverlay.style.right = sidebarW + 'px'; targetOverlay.style.left = '0'; }
    }
    document.body.appendChild(targetOverlay);

    targetHighlight = document.createElement('div');
    targetHighlight.style.cssText = 'position:fixed;border:2px solid #3b82f6;background:rgba(59,130,246,0.08);border-radius:4px;z-index:99999;pointer-events:none;transition:all 0.1s ease;display:none;';
    document.body.appendChild(targetHighlight);

    targetOverlay.addEventListener('mousemove', handleTargetHover, true);
    targetOverlay.addEventListener('click', handleTargetClick, true);
    document.addEventListener('keydown', handleTargetEscape);
  };

  const deactivateTargetMode = () => {
    targetActive = false;
    const targetBtn = document.querySelector('.peligent-ai-target-btn');
    if (targetBtn) targetBtn.style.background = 'transparent';
    if (targetOverlay) { targetOverlay.remove(); targetOverlay = null; }
    if (targetHighlight) { targetHighlight.remove(); targetHighlight = null; }
    document.removeEventListener('keydown', handleTargetEscape);
  };

  const handleTargetEscape = (e) => { if (e.key === 'Escape') deactivateTargetMode(); };

  const findTargetable = (el) => {
    if (!el) return null;
    // Skip non-content elements
    if (el.closest('.peligent-ai-fixed-sidebar, #wpadminbar, #adminmenuwrap')) return null;
    // Priority: specific selectors first
    const selectors = [
      'tr[id^="post-"]',
      '.wc-orders-list-table tbody tr',
      'table.wc-orders tbody tr',
      '#post-body',
      '.woocommerce-layout__primary',
      '.form-table tr',
      '.wp-list-table tbody tr',
      '.postbox',
      '.woocommerce-card',
      '.wrap > form',
      'table tbody tr'
    ];
    for (const sel of selectors) {
      const match = el.closest(sel);
      if (match) return match;
    }
    // Fallback: any reasonable content block
    const block = el.closest('div[id], section, article, .card, .widget, li');
    if (block && block.offsetHeight < 600 && block.offsetHeight > 20) return block;
    return null;
  };

  const handleTargetHover = (e) => {
    // Temporarily hide overlay pointer-events to find element underneath
    targetOverlay.style.pointerEvents = 'none';
    const actualEl = document.elementFromPoint(e.clientX, e.clientY);
    targetOverlay.style.pointerEvents = '';
    if (!actualEl) { targetHighlight.style.display = 'none'; return; }
    const target = findTargetable(actualEl);
    if (target) {
      const rect = target.getBoundingClientRect();
      targetHighlight.style.left = rect.left + 'px';
      targetHighlight.style.top = rect.top + 'px';
      targetHighlight.style.width = rect.width + 'px';
      targetHighlight.style.height = rect.height + 'px';
      targetHighlight.style.display = 'block';
    } else {
      targetHighlight.style.display = 'none';
    }
  };

  const extractTargetContext = (el) => {
    if (!el) return null;
    // Product/post row
    if (el.matches('tr[id^="post-"]')) {
      const id = el.id.replace('post-', '');
      const name = (el.querySelector('.row-title, .column-name a') || {}).textContent?.trim();
      const postType = document.querySelector('input[name="post_type"]');
      const type = postType ? postType.value : 'product';
      return { type, id, name: name || '#' + id };
    }
    // HPOS order row
    if (el.matches('.wc-orders-list-table tbody tr, table.wc-orders tbody tr')) {
      const link = el.querySelector('a[href*="id="]') || el.querySelector('.order-view, .column-order_number a');
      const idMatch = (link?.href || link?.textContent || '').match(/#?(\d+)/);
      const id = idMatch ? idMatch[1] : null;
      return { type: 'order', id, name: 'Order #' + (id || '?') };
    }
    // Edit screen
    if (el.matches('#post-body')) {
      const id = document.querySelector('#post_ID')?.value;
      const name = document.querySelector('#title')?.value;
      const postType = document.querySelector('input[name="post_type"]')?.value || 'product';
      return { type: postType, id, name: name || '#' + (id || '') };
    }
    // WC block editor
    if (el.matches('.woocommerce-layout__primary')) {
      const urlMatch = window.location.href.match(/[?&](?:post|id|path=\/product\/)=(\d+)/);
      const id = urlMatch ? urlMatch[1] : null;
      const name = document.querySelector('.woocommerce-product-header__title input, h2.woocommerce-product-header__title');
      return { type: 'product', id, name: name?.value || name?.textContent || '#' + (id || '') };
    }
    // Settings row
    if (el.matches('.form-table tr')) {
      const label = (el.querySelector('th label, th') || {}).textContent?.trim();
      const val = (el.querySelector('td input, td select, td textarea') || {}).value;
      return { type: 'setting', id: null, name: label || 'Setting', value: val };
    }
    // Generic list row
    if (el.matches('.wp-list-table tbody tr, table tbody tr')) {
      const firstLink = el.querySelector('a');
      return { type: 'item', id: null, name: firstLink?.textContent?.trim() || 'Row' };
    }
    // Generic block fallback
    if (el) {
      const heading = el.querySelector('h1, h2, h3, h4, .hndle, .postbox-header');
      const link = el.querySelector('a');
      const name = heading?.textContent?.trim() || link?.textContent?.trim() || el.id || 'Selected element';
      return { type: 'element', id: el.id || null, name: name.slice(0, 80) };
    }
    return null;
  };

  const handleTargetClick = (e) => {
    e.preventDefault();
    e.stopPropagation();
    // Find element underneath overlay
    targetOverlay.style.pointerEvents = 'none';
    const actualEl = document.elementFromPoint(e.clientX, e.clientY);
    targetOverlay.style.pointerEvents = '';
    const target = findTargetable(actualEl);
    const ctx = target ? extractTargetContext(target) : null;
    if (ctx) {
      const iframe = document.querySelector('iframe.peligent-ai-iframe');
      if (iframe && iframe.contentWindow) {
        try { iframe.contentWindow.postMessage({ type: 'PELIGENT_AI_TARGET', target: ctx }, ORIGIN); } catch (e) {}
      }
    } else if (targetHighlight) {
      // Brief red flash feedback when nothing targetable is found
      targetHighlight.style.display = 'block';
      targetHighlight.style.border = '2px solid #ef4444';
      targetHighlight.style.background = 'rgba(239,68,68,0.08)';
      targetHighlight.style.inset = '0';
      targetHighlight.style.width = 'auto';
      targetHighlight.style.height = 'auto';
      setTimeout(() => deactivateTargetMode(), 300);
      return;
    }
    deactivateTargetMode();
  };


  const initTargetButton = () => {
    const targetBtn = document.querySelector('.peligent-ai-target-btn');
    if (targetBtn) {
      const newBtn = targetBtn.cloneNode(true);
      targetBtn.parentNode.replaceChild(newBtn, targetBtn);
      newBtn.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); dismissTargetHint(); activateTargetMode(); });

      // First-time discovery hint
      showTargetHint(newBtn);
    }
  };

  const showTargetHint = (btn) => {
    try { if (localStorage.getItem('peligent_target_hint_seen')) return; } catch {}

    // Make button container relative for positioning
    btn.style.position = 'relative';

    // Pulsing dot
    const dot = document.createElement('span');
    dot.className = 'peligent-target-hint-dot';
    dot.style.cssText = 'position:absolute;top:-2px;right:-2px;width:8px;height:8px;background:#f59e0b;border-radius:50%;pointer-events:none;z-index:10;animation:peligent-pulse 1.5s ease-in-out infinite;';
    btn.appendChild(dot);

    // Tooltip
    const tip = document.createElement('div');
    tip.className = 'peligent-target-hint-tip';
    tip.innerHTML = '<strong>Target Picker</strong><br><span style="opacity:0.85;">Click here to select any product, order, or element on the page — it will be attached to your next message.</span>';
    tip.style.cssText = 'position:absolute;top:calc(100% + 10px);right:0;width:220px;padding:10px 12px;background:#1e293b;color:#fff;font-size:12px;line-height:1.45;border-radius:8px;box-shadow:0 8px 24px rgba(0,0,0,0.25);z-index:100;pointer-events:auto;opacity:0;transform:translateY(-4px);transition:opacity 0.25s,transform 0.25s;';
    btn.appendChild(tip);

    // Arrow
    const arrow = document.createElement('div');
    arrow.style.cssText = 'position:absolute;top:-5px;right:12px;width:10px;height:10px;background:#1e293b;transform:rotate(45deg);border-radius:2px;';
    tip.appendChild(arrow);

    // Pulse keyframe
    if (!document.getElementById('peligent-pulse-keyframes')) {
      const style = document.createElement('style');
      style.id = 'peligent-pulse-keyframes';
      style.textContent = '@keyframes peligent-pulse{0%,100%{opacity:1;transform:scale(1)}50%{opacity:0.5;transform:scale(1.4)}}';
      document.head.appendChild(style);
    }

    // Animate in after a short delay
    setTimeout(() => { tip.style.opacity = '1'; tip.style.transform = 'translateY(0)'; }, 600);

    // Dismiss on click anywhere
    const dismiss = (e) => {
      if (e && btn.contains(e.target)) return; // let the button click handler dismiss
      dismissTargetHint();
    };
    setTimeout(() => document.addEventListener('click', dismiss, { once: true }), 700);

    // Store dismiss function for the button click handler
    window._peligentDismissTargetHint = dismiss;
  };

  const dismissTargetHint = () => {
    try { localStorage.setItem('peligent_target_hint_seen', '1'); } catch {}
    const dot = document.querySelector('.peligent-target-hint-dot');
    const tip = document.querySelector('.peligent-target-hint-tip');
    if (tip) { tip.style.opacity = '0'; tip.style.transform = 'translateY(-4px)'; setTimeout(() => tip.remove(), 250); }
    if (dot) dot.remove();
    if (window._peligentDismissTargetHint) { document.removeEventListener('click', window._peligentDismissTargetHint); delete window._peligentDismissTargetHint; }
  };


  // ====== Feature: Blog Editor Quick Action Chips ======
  const blogQuickActions = [
    { label: 'Write SEO-optimized intro', prompt: 'Write an SEO-optimized introduction for this blog post.' },
    { label: 'Suggest headlines for this post', prompt: 'Suggest several compelling headline options for this blog post.' },
    { label: 'Check readability & SEO', prompt: 'Check the readability and SEO of this blog post and suggest improvements.' },
    { label: 'Add meta description', prompt: 'Write an optimized meta description for this blog post.' }
  ];

  const initBlogQuickActions = () => {
    const ctx = window.PELIGENT_PAGE_CONTEXT;
    if (!ctx || ctx.page_type !== 'blog_editor') return;

    const sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
    if (!sidebar) return;

    // Don't add if already present
    if (sidebar.querySelector('.peligent-blog-quick-actions')) return;

    const container = document.createElement('div');
    container.className = 'peligent-blog-quick-actions';
    container.style.cssText = 'display:flex;flex-wrap:wrap;gap:6px;padding:8px 12px;border-bottom:1px solid rgba(255,255,255,0.08);';

    blogQuickActions.forEach(action => {
      const chip = document.createElement('button');
      chip.type = 'button';
      chip.textContent = action.label;
      chip.style.cssText = 'background:rgba(59,130,246,0.12);color:#93c5fd;border:1px solid rgba(59,130,246,0.25);border-radius:16px;padding:4px 12px;font-size:12px;cursor:pointer;white-space:nowrap;transition:background 0.15s,border-color 0.15s;line-height:1.4;';
      chip.addEventListener('mouseenter', () => { chip.style.background = 'rgba(59,130,246,0.25)'; chip.style.borderColor = 'rgba(59,130,246,0.5)'; });
      chip.addEventListener('mouseleave', () => { chip.style.background = 'rgba(59,130,246,0.12)'; chip.style.borderColor = 'rgba(59,130,246,0.25)'; });
      chip.addEventListener('click', (e) => {
        e.preventDefault();
        e.stopPropagation();
        const iframe = sidebar.querySelector('iframe.peligent-ai-iframe');
        if (iframe && iframe.contentWindow) {
          // Ensure sidebar is visible
          if (sidebar.classList.contains('peligent-ai-hidden')) {
            sidebar.classList.remove('peligent-ai-hidden');
            document.body.classList.remove('peligent-ai-sidebar-hidden');
            try { localStorage.setItem('peligent_ai_sidebar_visible', '1'); } catch {}
          }
          try {
            iframe.contentWindow.postMessage({ type: 'PELIGENT_AI_PROMPT', prompt: action.prompt }, ORIGIN);
          } catch (err) {
            // Queue the prompt if iframe isn't ready yet
            window._peligentPendingPrompt = action.prompt;
          }
        }
      });
      container.appendChild(chip);
    });

    // Insert after the header div
    const header = sidebar.querySelector('.peligent-ai-header');
    if (header && header.parentNode) {
      header.parentNode.insertBefore(container, header.nextSibling);
    } else {
      // Fallback: prepend inside sidebar before iframe container
      const iframeContainer = sidebar.querySelector('.peligent-ai-iframe-container');
      if (iframeContainer) {
        sidebar.insertBefore(container, iframeContainer);
      }
    }

    logDebug('[peligent-ai-embed] Blog quick action chips rendered');
  };
  let pendingGenerateContent = null;

  const onReady = () => {
    document.querySelectorAll('iframe.peligent-ai-iframe').forEach(wireIframe);
    initResize();
    initHeaderButtons();
    initAdminBarToggle();
    initFullscreenBar();
    initTargetButton();
    initBlogQuickActions();
    restoreSidebarState();
  };

  // Use jQuery ready if available, otherwise fallback to vanilla JS
  const initScript = function () {
    logDebug('[peligent-ai-embed] Initializing script...');
    logDebug('[peligent-ai-embed] jQuery available:', typeof $ !== 'undefined');
    logDebug('[peligent-ai-embed] Sidebar exists:', document.querySelector('.peligent-ai-fixed-sidebar') !== null);
    logDebug('[peligent-ai-embed] Close button exists:', document.querySelector('.peligent-ai-close-btn') !== null);
    logDebug('[peligent-ai-embed] Maximize button exists:', document.querySelector('.peligent-ai-maximize-btn') !== null);
    initBackend().finally(onReady);
  };

  if (typeof jQuery !== 'undefined' && typeof $ !== 'undefined') {
    jQuery(document).ready(function ($) {

      logDebug('[peligent-ai-embed] jQuery ready, initializing...');
      initScript();
    });
  } else {
    logDebug('[peligent-ai-embed] jQuery not available, using vanilla JS');
    if (document.readyState === 'complete' || document.readyState === 'interactive') {
      initScript();
    } else {
      document.addEventListener('DOMContentLoaded', initScript);
    }
  }
})(typeof jQuery !== 'undefined' ? jQuery : undefined); // Pass jQuery if available
