// assets/wpai-embed.js
// Use jQuery if available (WordPress includes it)
(function($) {
  'use strict';
  
  console.log('[wpai-embed] Script file loaded!');
  window.WPAI_EMBED_LOADED = true;

  if (!window.WPAI_CLIENT) {
    console.warn('[wpai-embed] WPAI_CLIENT not found. Available:', Object.keys(window).filter(k => k.includes('WPAI')));
    return;
  }
  const { server, token, site_url } = window.WPAI_CLIENT;
  if (!server || !token) {
    console.warn('[wpai-embed] Missing server or token');
    return;
  }
  console.log('[wpai-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: 'WPAI_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 = 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._wpaiWired) return;
    iframe.dataset._wpaiWired = '1';
    iframe.addEventListener('load', () => {
      setTimeout(() => startTokenLoop(iframe), 120);
    });
  };

  console.log('[wpai-embed] Setting up message listener');
  // Test: Send a test message to verify script is loaded
  console.log('[wpai-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 || {};
    if (data.type === 'WPAI_ACK') {
      document.querySelectorAll('iframe.wpai-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; } }
        }
      });
    } else if (data.type === 'WPAI_READY') {
      // Embed page is ready, send token immediately
      document.querySelectorAll('iframe.wpai-iframe').forEach((ifr) => {
        if (ifr.contentWindow === ev.source) {
          sendTokenOnce(ifr);
          startTokenLoop(ifr);
        }
      });
    } else if (data.type === 'WPAI_RESIZE' && typeof data.height === 'number') {
      document.querySelectorAll('iframe.wpai-iframe').forEach((ifr) => {
        if (ifr.contentWindow === ev.source) {
          const container = ifr.closest('.wpai-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 === 'WPAI_CLOSE') {
      // Hide the sidebar when close button is clicked
      console.log('[wpai-embed] Received WPAI_CLOSE message');
      const sidebar = document.querySelector('.wpai-fixed-sidebar');
      console.log('[wpai-embed] Sidebar element:', sidebar);
      if (sidebar) {
        console.log('[wpai-embed] Current sidebar classes:', sidebar.className);
        console.log('[wpai-embed] Hiding sidebar');
        sidebar.classList.add('wpai-hidden');
        document.body.classList.add('wpai-sidebar-hidden');
        console.log('[wpai-embed] Sidebar classes after hiding:', sidebar.className);
        console.log('[wpai-embed] Body classes:', document.body.className);
        try { localStorage.setItem('wpai_sidebar_visible', '0'); } catch {}
      } else {
        console.warn('[wpai-embed] Sidebar not found. Available elements:', document.querySelectorAll('aside, .wpai-fixed-sidebar'));
      }
    } else if (data.type === 'WPAI_FULLSCREEN') {
      // Toggle fullscreen mode
      console.log('[wpai-embed] Received WPAI_FULLSCREEN message');
      const sidebar = document.querySelector('.wpai-fixed-sidebar');
      console.log('[wpai-embed] Sidebar element:', sidebar);
      if (sidebar) {
        const isFullscreen = sidebar.classList.contains('wpai-fullscreen');
        console.log('[wpai-embed] Current fullscreen state:', isFullscreen);
        console.log('[wpai-embed] Current sidebar classes:', sidebar.className);
        if (isFullscreen) {
          sidebar.classList.remove('wpai-fullscreen');
          document.body.classList.remove('wpai-fullscreen');
          try { localStorage.setItem('wpai_sidebar_fullscreen', '0'); } catch {}
          console.log('[wpai-embed] Exited fullscreen mode. Sidebar classes:', sidebar.className);
          console.log('[wpai-embed] Body classes:', document.body.className);
          // Notify iframe about fullscreen state
          const iframe = sidebar.querySelector('iframe.wpai-iframe');
          if (iframe && iframe.contentWindow) {
            try {
              iframe.contentWindow.postMessage({ type: 'WPAI_FULLSCREEN_STATE', fullscreen: false }, ORIGIN);
            } catch (e) {}
          }
        } else {
          sidebar.classList.add('wpai-fullscreen');
          document.body.classList.add('wpai-fullscreen');
          try { localStorage.setItem('wpai_sidebar_fullscreen', '1'); } catch {}
          console.log('[wpai-embed] Entered fullscreen mode. Sidebar classes:', sidebar.className);
          console.log('[wpai-embed] Body classes:', document.body.className);
          // Notify iframe about fullscreen state
          const iframe = sidebar.querySelector('iframe.wpai-iframe');
          if (iframe && iframe.contentWindow) {
            try {
              console.log('[wpai-embed] Sending fullscreen=true to iframe (from message handler)');
              iframe.contentWindow.postMessage({ type: 'WPAI_FULLSCREEN_STATE', fullscreen: true }, ORIGIN);
              // Also send after a short delay to ensure iframe is ready
              setTimeout(() => {
                try {
                  iframe.contentWindow.postMessage({ type: 'WPAI_FULLSCREEN_STATE', fullscreen: true }, ORIGIN);
                } catch (e) {}
              }, 100);
            } catch (e) {
              console.error('[wpai-embed] Failed to send fullscreen message:', e);
            }
          } else {
            console.warn('[wpai-embed] Iframe not found for fullscreen notification');
          }
        }
      } else {
        console.warn('[wpai-embed] Sidebar not found. Available elements:', document.querySelectorAll('aside, .wpai-fixed-sidebar'));
      }
    }
  });

  // Handle resize functionality - using jQuery
  const initResize = () => {
    console.log('[wpai-embed] Initializing resize functionality...');
    const $sidebar = $('.wpai-fixed-sidebar');
    const $resizeHandle = $('.wpai-resize-handle');
    
    if ($sidebar.length === 0 || $resizeHandle.length === 0) {
      console.warn('[wpai-embed] Sidebar or resize handle not found');
      return;
    }

    let isResizing = false;
    let startX = 0;
    let startWidth = 0;
    const minWidth = 380;
    const maxWidth = Math.min(window.innerWidth * 0.5, 800);

    // 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();
      console.log('[wpai-embed] Resize started, width:', startWidth);
    });

    $(document).off('mousemove.wpai-resize').on('mousemove.wpai-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('wpai_sidebar_width', String(newWidth)); } catch {}
    });

    $(document).off('mouseup.wpai-resize').on('mouseup.wpai-resize', function() {
      if (isResizing) {
        isResizing = false;
        $('body').css({
          'cursor': '',
          'user-select': ''
        });
        console.log('[wpai-embed] Resize ended');
      }
    });
    
    console.log('[wpai-embed] Resize handlers attached');
  };

  // Handle header button clicks (close and maximize) - works with or without jQuery
  const initHeaderButtons = () => {
    console.log('[wpai-embed] Initializing header buttons...');
    
    const sidebar = document.querySelector('.wpai-fixed-sidebar');
    console.log('[wpai-embed] Sidebar found:', !!sidebar);
    
    if (!sidebar) {
      console.warn('[wpai-embed] Sidebar not found');
      return;
    }

    // Close button - try jQuery first, fallback to vanilla JS
    const closeBtn = sidebar.querySelector('.wpai-close-btn');
    console.log('[wpai-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();
        console.log('[wpai-embed] Close button clicked!');
        const sidebar = document.querySelector('.wpai-fixed-sidebar');
        if (sidebar) {
          sidebar.classList.add('wpai-hidden');
          document.body.classList.add('wpai-sidebar-hidden');
          try { localStorage.setItem('wpai_sidebar_visible', '0'); } catch {}
          console.log('[wpai-embed] Sidebar hidden successfully');
        }
      });
      console.log('[wpai-embed] Close button handler attached');
    } else {
      console.warn('[wpai-embed] Close button not found!');
    }

    // Maximize button - try jQuery first, fallback to vanilla JS
    const maximizeBtn = sidebar.querySelector('.wpai-maximize-btn');
    console.log('[wpai-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();
        console.log('[wpai-embed] Maximize button clicked!');
        const sidebar = document.querySelector('.wpai-fixed-sidebar');
        if (sidebar) {
          const isFullscreen = sidebar.classList.contains('wpai-fullscreen');
        if (isFullscreen) {
          sidebar.classList.remove('wpai-fullscreen');
          document.body.classList.remove('wpai-fullscreen');
          try { localStorage.setItem('wpai_sidebar_fullscreen', '0'); } catch {}
          console.log('[wpai-embed] Exited fullscreen mode');
          // Notify iframe about fullscreen state
          const iframe = sidebar.querySelector('iframe.wpai-iframe');
          if (iframe && iframe.contentWindow) {
            try {
              iframe.contentWindow.postMessage({ type: 'WPAI_FULLSCREEN_STATE', fullscreen: false }, ORIGIN);
            } catch (e) {}
          }
          } else {
            sidebar.classList.add('wpai-fullscreen');
            document.body.classList.add('wpai-fullscreen');
            try { localStorage.setItem('wpai_sidebar_fullscreen', '1'); } catch {}
            console.log('[wpai-embed] Entered fullscreen mode');
            // Notify iframe about fullscreen state
            const iframe = sidebar.querySelector('iframe.wpai-iframe');
            if (iframe && iframe.contentWindow) {
              try {
                console.log('[wpai-embed] Sending fullscreen=true to iframe');
                iframe.contentWindow.postMessage({ type: 'WPAI_FULLSCREEN_STATE', fullscreen: true }, ORIGIN);
                // Also send after a short delay to ensure iframe is ready
                setTimeout(() => {
                  try {
                    iframe.contentWindow.postMessage({ type: 'WPAI_FULLSCREEN_STATE', fullscreen: true }, ORIGIN);
                  } catch (e) {}
                }, 100);
              } catch (e) {
                console.error('[wpai-embed] Failed to send fullscreen message:', e);
              }
            } else {
              console.warn('[wpai-embed] Iframe not found for fullscreen notification');
            }
          }
        }
      });
      console.log('[wpai-embed] Maximize button handler attached');
    } else {
      console.warn('[wpai-embed] Maximize button not found!');
    }
  };

  // Handle admin bar icon click - works with or without jQuery
  const initAdminBarToggle = () => {
    console.log('[wpai-embed] Initializing admin bar toggle...');
    const chatIcon = document.querySelector('#wp-admin-bar-peligent-chat a');
    console.log('[wpai-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('.wpai-fixed-sidebar');
        if (sidebar) {
          const isHidden = sidebar.classList.contains('wpai-hidden');
          if (isHidden) {
            sidebar.classList.remove('wpai-hidden');
            document.body.classList.remove('wpai-sidebar-hidden');
            try { localStorage.setItem('wpai_sidebar_visible', '1'); } catch {}
            console.log('[wpai-embed] Sidebar shown');
          } else {
            sidebar.classList.add('wpai-hidden');
            document.body.classList.add('wpai-sidebar-hidden');
            try { localStorage.setItem('wpai_sidebar_visible', '0'); } catch {}
            console.log('[wpai-embed] Sidebar hidden');
          }
        }
      });
      console.log('[wpai-embed] Admin bar toggle handler attached');
    } else {
      console.warn('[wpai-embed] Admin bar chat icon not found');
    }
  };

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

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

      const fullscreen = localStorage.getItem('wpai_sidebar_fullscreen');
      if (fullscreen === '1') {
        sidebar.classList.add('wpai-fullscreen');
        document.body.classList.add('wpai-fullscreen');
      }

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

      const width = localStorage.getItem('wpai_sidebar_width');
      if (width) {
        const widthNum = parseInt(width, 10);
        if (!isNaN(widthNum) && widthNum >= 380) {
          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
    }
  };

  const onReady = () => {
    document.querySelectorAll('iframe.wpai-iframe').forEach(wireIframe);
    initResize();
    initHeaderButtons();
    initAdminBarToggle();
    restoreSidebarState();
  };

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

  if (typeof jQuery !== 'undefined' && typeof $ !== 'undefined') {
    jQuery(document).ready(function($) {
      console.log('[wpai-embed] jQuery ready, initializing...');
      initScript();
    });
  } else {
    console.log('[wpai-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


