// chat.js

document.addEventListener('DOMContentLoaded', () => {
  // Create widget container with Word.Chat brand styling
  const chatBox = document.createElement('div');
  chatBox.id = 'wordchat-widget';

  // Get customization settings
  const primaryColor = WordChatVars.primary_color || '#1A73E8';
  const position = WordChatVars.position || 'right';
  const startOpen = WordChatVars.start_open !== undefined ? WordChatVars.start_open : true;
  const placeholder = WordChatVars.placeholder || 'Ask a question...';
  const buttonText = WordChatVars.button_text || 'Send';

  // Calculate darker shade for hover (15% darker)
  function darkenColor(hex, percent) {
    const num = parseInt(hex.replace('#', ''), 16);
    const r = Math.max(0, Math.floor((num >> 16) * (1 - percent / 100)));
    const g = Math.max(0, Math.floor(((num >> 8) & 0x00FF) * (1 - percent / 100)));
    const b = Math.max(0, Math.floor((num & 0x0000FF) * (1 - percent / 100)));
    return `#${(r << 16 | g << 8 | b).toString(16).padStart(6, '0')}`;
  }

  const primaryColorDark = darkenColor(primaryColor, 15);
  const positionStyle = position === 'left' ? 'left: 20px;' : 'right: 20px;';

  chatBox.innerHTML = `
    <style>
      @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');

      #wordchat-widget {
        font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
        --wordchat-primary: ${primaryColor};
        --wordchat-primary-dark: ${primaryColorDark};
      }
      #wordchat-container {
        position: fixed;
        bottom: 20px;
        ${positionStyle}
        width: 400px;
        max-width: calc(100vw - 40px);
        background: white;
        border: 1px solid #E5E7EB;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.05);
        overflow: hidden;
        z-index: 9999;
        transition: box-shadow 200ms ease;
      }
      #wordchat-container:hover {
        box-shadow: 0 6px 16px rgba(0,0,0,0.08);
      }
      #wordchat-header {
        background: var(--wordchat-primary);
        color: white;
        padding: 16px 20px;
        font-weight: 600;
        font-size: 16px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid rgba(255,255,255,0.1);
      }
      #wordchat-header-buttons {
        display: flex;
        gap: 4px;
        align-items: center;
      }
      .wordchat-header-btn {
        background: none;
        border: none;
        color: white;
        font-size: 18px;
        cursor: pointer;
        padding: 4px;
        width: 28px;
        height: 28px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 4px;
        transition: background 150ms ease;
      }
      .wordchat-header-btn:hover {
        background: rgba(255,255,255,0.15);
      }
      .wordchat-header-btn[title]:hover::after {
        content: attr(title);
        position: absolute;
        bottom: -32px;
        right: 0;
        background: #1F2937;
        color: white;
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;
        font-weight: 400;
        white-space: nowrap;
        z-index: 10000;
        pointer-events: none;
        animation: wordchat-tooltip-fadein 150ms ease;
      }
      @keyframes wordchat-tooltip-fadein {
        from { opacity: 0; transform: translateY(-4px); }
        to { opacity: 1; transform: translateY(0); }
      }
      #wordchat-header-buttons {
        position: relative;
      }
      #wordchat-minimize {
        font-size: 20px;
      }
      #wordchat-body {
        padding: 20px;
        background: #F9FAFB;
        max-height: 400px;
        overflow-y: auto;
        scroll-behavior: smooth;
      }
      #wordchat-messages {
        min-height: 120px;
        margin-bottom: 16px;
      }
      #wordchat-input-area {
        background: white;
        border-top: 1px solid #E5E7EB;
        padding: 12px 16px;
        display: flex;
        gap: 8px;
        align-items: center;
      }
      #wordchat-input {
        flex: 1;
        padding: 10px 12px;
        border: 1px solid #E5E7EB;
        border-radius: 6px;
        font-size: 15px;
        font-family: inherit;
        color: #111827;
        background: white;
        box-sizing: border-box;
        transition: border-color 200ms ease, box-shadow 200ms ease;
      }
      #wordchat-input::placeholder {
        color: #9CA3AF;
      }
      #wordchat-input:focus {
        outline: none;
        border-color: var(--wordchat-primary);
        box-shadow: 0 0 0 3px color-mix(in srgb, var(--wordchat-primary) 10%, transparent);
      }
      #wordchat-send {
        padding: 10px 20px;
        background: var(--wordchat-primary);
        color: white;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 600;
        font-family: inherit;
        cursor: pointer;
        transition: background 200ms ease, transform 150ms ease;
        white-space: nowrap;
      }
      #wordchat-send:hover:not(:disabled) {
        background: var(--wordchat-primary-dark);
      }
      #wordchat-send:active:not(:disabled) {
        transform: scale(0.98);
      }
      #wordchat-send:disabled {
        background: #E5E7EB;
        color: #9CA3AF;
        cursor: not-allowed;
      }
      .wordchat-message {
        margin-bottom: 8px;
        padding: 12px;
        border-radius: 10px;
        font-size: 15px;
        line-height: 1.5;
        color: #111827;
        animation: wordchat-fadein 200ms ease;
      }
      .wordchat-message.user {
        background: var(--wordchat-primary);
        color: white;
        border-radius: 10px 10px 0 10px;
        margin-left: 20px;
      }
      .wordchat-message.ai {
        background: #F3F4F6;
        color: #111827;
        border-radius: 10px 10px 10px 0;
        margin-right: 20px;
      }
      .wordchat-message.error {
        background: #FEE2E2;
        color: #EF4444;
        border-radius: 8px;
        border-left: 3px solid #EF4444;
      }
      .wordchat-message.loading {
        background: #F3F4F6;
        color: #6B7280;
        border-radius: 10px 10px 10px 0;
        margin-right: 20px;
      }
      @keyframes wordchat-fadein {
        from { opacity: 0; transform: translateY(8px); }
        to { opacity: 1; transform: translateY(0); }
      }
      .wordchat-spinner {
        display: inline-flex;
        gap: 4px;
        align-items: center;
      }
      .wordchat-spinner span {
        width: 6px;
        height: 6px;
        background: #9CA3AF;
        border-radius: 50%;
        animation: wordchat-pulse 1.4s ease-in-out infinite;
      }
      .wordchat-spinner span:nth-child(2) {
        animation-delay: 0.2s;
      }
      .wordchat-spinner span:nth-child(3) {
        animation-delay: 0.4s;
      }
      @keyframes wordchat-pulse {
        0%, 80%, 100% { opacity: 0.3; }
        40% { opacity: 1; }
      }
      #wordchat-minimized {
        position: fixed;
        bottom: 20px;
        ${positionStyle}
        width: 60px;
        height: 60px;
        background: var(--wordchat-primary);
        border-radius: 50%;
        box-shadow: 0 4px 12px color-mix(in srgb, var(--wordchat-primary) 30%, transparent);
        display: none;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        z-index: 9999;
        transition: transform 200ms ease, box-shadow 200ms ease;
      }
      #wordchat-minimized:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 16px color-mix(in srgb, var(--wordchat-primary) 40%, transparent);
      }
      #wordchat-minimized svg {
        width: 28px;
        height: 28px;
        fill: white;
      }
      #wordchat-branding {
        padding: 8px 20px;
        text-align: center;
        font-size: 12px;
        color: #9CA3AF;
        border-top: 1px solid #E5E7EB;
        background: white;
      }
      #wordchat-branding a {
        color: var(--wordchat-primary);
        text-decoration: none;
        transition: color 150ms ease;
      }
      #wordchat-branding a:hover {
        color: var(--wordchat-primary-dark);
      }
      @media (max-width: 480px) {
        #wordchat-container {
          width: calc(100vw - 32px);
          bottom: 16px;
          right: 16px;
        }
        #wordchat-body {
          padding: 16px;
        }
      }
    </style>
    <div id="wordchat-minimized" title="Open Chat">
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
        <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>
      </svg>
    </div>
    <div id="wordchat-container">
      <div id="wordchat-header">
        <span id="wordchat-header-text">Ask us anything</span>
        <div id="wordchat-header-buttons">
          <button id="wordchat-clear" class="wordchat-header-btn" title="Clear chat history" aria-label="Clear chat">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M3 6h18M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"/>
            </svg>
          </button>
          <button id="wordchat-minimize" class="wordchat-header-btn" title="Minimize" aria-label="Minimize chat">−</button>
        </div>
      </div>
      <div id="wordchat-body">
        <div id="wordchat-messages"></div>
      </div>
      <div id="wordchat-input-area">
        <input type="text" id="wordchat-input" placeholder="${placeholder}" aria-label="Message input" />
        <button id="wordchat-send" aria-label="Send message">${buttonText}</button>
      </div>
      <div id="wordchat-branding">Powered by <a href="https://word.chat" target="_blank" rel="noopener">Word.Chat</a></div>
    </div>
  `;
  document.body.appendChild(chatBox);

  // Get DOM elements
  const container = document.getElementById('wordchat-container');
  const minimizedBtn = document.getElementById('wordchat-minimized');
  const minimizeBtn = document.getElementById('wordchat-minimize');
  const clearBtn = document.getElementById('wordchat-clear');
  const input = document.getElementById('wordchat-input');
  const button = document.getElementById('wordchat-send');
  const messagesContainer = document.getElementById('wordchat-messages');
  const bodyContainer = document.getElementById('wordchat-body'); // The actual scrollable element
  const headerTextEl = document.getElementById('wordchat-header-text');

  // Apply start state (open/closed)
  if (!startOpen) {
    container.style.display = 'none';
    minimizedBtn.style.display = 'flex';
  }

  // Load chat history from localStorage
  const chatHistory = loadChatHistory();

  // Apply custom settings
  if (WordChatVars.header_text) {
    headerTextEl.textContent = WordChatVars.header_text;
  }

  // Restore chat history or show intro message
  if (chatHistory.length > 0) {
    chatHistory.forEach(msg => {
      addMessage(msg.text, msg.type, false); // false = don't save to history
    });
    // Force scroll to bottom after history is loaded
    setTimeout(() => {
      scrollToBottom();
    }, 100);
  } else if (WordChatVars.intro_message) {
    addMessage(WordChatVars.intro_message, 'ai');
  }

  // Minimize/maximize handlers
  minimizeBtn.addEventListener('click', () => {
    container.style.display = 'none';
    minimizedBtn.style.display = 'flex';
  });

  minimizedBtn.addEventListener('click', () => {
    minimizedBtn.style.display = 'none';
    container.style.display = 'block';
    input.focus();
  });

  // Clear chat handler
  clearBtn.addEventListener('click', () => {
    if (confirm('Clear chat history? This cannot be undone.')) {
      clearChatHistory();
    }
  });

  // Load chat history from localStorage
  function loadChatHistory() {
    try {
      const saved = localStorage.getItem('wordchat_history');
      return saved ? JSON.parse(saved) : [];
    } catch (e) {
      console.error('WordChat: Failed to load chat history', e);
      return [];
    }
  }

  // Save chat history to localStorage
  function saveChatHistory(text, type) {
    try {
      const history = loadChatHistory();
      history.push({ text, type, timestamp: Date.now() });

      // Keep only last 50 messages to avoid localStorage bloat
      const trimmedHistory = history.slice(-50);

      localStorage.setItem('wordchat_history', JSON.stringify(trimmedHistory));
    } catch (e) {
      console.error('WordChat: Failed to save chat history', e);
    }
  }

  // Clear chat history
  function clearChatHistory() {
    try {
      localStorage.removeItem('wordchat_history');
      messagesContainer.innerHTML = '';
      if (WordChatVars.intro_message) {
        addMessage(WordChatVars.intro_message, 'ai');
      }
    } catch (e) {
      console.error('WordChat: Failed to clear chat history', e);
    }
  }

  // Scroll to bottom helper with forced behavior
  function scrollToBottom(smooth = false) {
    // Scroll the body container, not the messages div
    const scrollTarget = bodyContainer;

    if (smooth) {
      scrollTarget.scrollTo({
        top: scrollTarget.scrollHeight,
        behavior: 'smooth'
      });
    } else {
      // Force immediate scroll without smooth behavior
      scrollTarget.style.scrollBehavior = 'auto';
      scrollTarget.scrollTop = scrollTarget.scrollHeight;

      // Use requestAnimationFrame to ensure it happens after render
      requestAnimationFrame(() => {
        scrollTarget.scrollTop = scrollTarget.scrollHeight;
        // Restore smooth scrolling
        scrollTarget.style.scrollBehavior = 'smooth';
      });
    }
  }

  // Log chat interaction to backend for analytics
  function logChatInteraction(question, answer, sources, navigatedToUrl) {
    // Don't block the UI - fire and forget
    const formData = new FormData();
    formData.append('action', 'wordchat_log_chat');
    formData.append('nonce', WordChatVars.nonce);
    formData.append('question', question);
    formData.append('answer', answer);
    formData.append('sources', JSON.stringify(sources || []));
    if (navigatedToUrl) {
      formData.append('navigated_to_url', navigatedToUrl);
    }

    fetch(WordChatVars.ajax_url, {
      method: 'POST',
      body: formData
    }).catch(() => {
      // Chat logging is non-critical, silently ignore failures
    });
  }

  // Add message to chat
  function addMessage(text, type, saveToHistory = true) {
    const messageDiv = document.createElement('div');
    messageDiv.className = `wordchat-message ${type}`;
    messageDiv.innerHTML = text;
    messagesContainer.appendChild(messageDiv);

    // Immediately scroll to bottom after adding message
    bodyContainer.scrollTop = bodyContainer.scrollHeight;

    // Use requestAnimationFrame to ensure DOM has updated
    requestAnimationFrame(() => {
      bodyContainer.scrollTop = bodyContainer.scrollHeight;

      // Double RAF for even better reliability
      requestAnimationFrame(() => {
        bodyContainer.scrollTop = bodyContainer.scrollHeight;
      });
    });

    // Fallback scroll after a short delay
    setTimeout(() => {
      bodyContainer.scrollTop = bodyContainer.scrollHeight;
    }, 50);

    // Save to localStorage (skip for loading, errors, and intro on restore)
    if (saveToHistory && type !== 'loading' && type !== 'error') {
      saveChatHistory(text, type);
    }

    return messageDiv;
  }

  // Send query function with streaming support via WordPress AJAX
  async function sendQuery() {
    const question = input.value.trim();

    if (!question) {
      addMessage('Please enter a question.', 'error');
      return;
    }

    // Debug: Check if AJAX config exists
    if (!WordChatVars.ajax_url || !WordChatVars.nonce) {
      console.error('WordChat: Missing AJAX configuration', {
        ajax_url: WordChatVars.ajax_url,
        nonce: WordChatVars.nonce ? 'present' : 'missing'
      });
      addMessage('Configuration error: AJAX not configured. Please contact the site administrator.', 'error');
      return;
    }

    // Capture conversation history BEFORE adding current question to localStorage
    const priorHistory = loadChatHistory();
    const conversationPairs = [];
    for (let i = 0; i < priorHistory.length; i++) {
      if (priorHistory[i].type === 'user') {
        conversationPairs.push({ role: 'user', content: priorHistory[i].text });
      } else if (priorHistory[i].type === 'ai') {
        conversationPairs.push({ role: 'assistant', content: priorHistory[i].text });
      }
    }

    // Add user message (saves to localStorage)
    addMessage(question, 'user');

    // Clear input
    const originalQuestion = question;
    input.value = '';

    // Disable input and button
    button.disabled = true;
    input.disabled = true;
    const originalButtonText = button.textContent;
    button.textContent = 'Sending...';

    // Show loading indicator
    const loadingMessage = addMessage(
      '<div class="wordchat-spinner"><span></span><span></span><span></span></div>',
      'loading'
    );

    // Prepare FormData for WordPress AJAX
    const formData = new FormData();
    formData.append('action', 'wordchat_query');
    formData.append('nonce', WordChatVars.nonce);
    formData.append('question', originalQuestion);

    // Send last 3 Q&A pairs as conversation history (captured before current question)
    formData.append('history', JSON.stringify(conversationPairs.slice(-6)));

    try {
      const res = await fetch(WordChatVars.ajax_url, {
        method: 'POST',
        body: formData
      });

      if (!res.ok) {
        const errorBody = await res.text();
        console.error('WordChat API error:', res.status, errorBody);
        throw new Error(`Server returned ${res.status}: ${errorBody}`);
      }

      // Remove loading indicator before streaming
      loadingMessage.remove();

      // Create AI message div that we'll update as tokens stream in
      const aiMessageDiv = document.createElement('div');
      aiMessageDiv.className = 'wordchat-message ai';
      aiMessageDiv.textContent = '';
      messagesContainer.appendChild(aiMessageDiv);

      let fullAnswer = '';
      let sources = [];

      // Read the stream using EventSource-like parsing
      const reader = res.body.getReader();
      const decoder = new TextDecoder();
      let buffer = '';

      while (true) {
        const { done, value } = await reader.read();

        if (done) break;

        // Decode the chunk and add to buffer
        buffer += decoder.decode(value, { stream: true });

        // Process complete SSE messages (data: ... \n\n)
        const messages = buffer.split('\n\n');
        buffer = messages.pop(); // Keep incomplete message in buffer

        for (const message of messages) {
          if (!message.trim() || !message.startsWith('data: ')) continue;

          const jsonStr = message.replace(/^data: /, '');
          try {
            const event = JSON.parse(jsonStr);

            if (event.type === 'sources') {
              sources = event.sources || [];
            } else if (event.type === 'token') {
              // Append token to answer
              fullAnswer += event.content;
              aiMessageDiv.textContent = fullAnswer;

              // Auto-scroll as content comes in
              bodyContainer.scrollTop = bodyContainer.scrollHeight;
            } else if (event.type === 'done') {
              // Stream complete
            } else if (event.type === 'error') {
              throw new Error(event.error || 'Stream error');
            }
          } catch (parseError) {
            console.warn('WordChat: Failed to parse SSE event:', jsonStr, parseError);
          }
        }
      }

      // Save final answer to history
      if (fullAnswer) {
        saveChatHistory(fullAnswer, 'ai');
      }

      // Navigate to the top source page if enabled and sources are available
      let navigatedToUrl = null;
      if (WordChatVars.navigate_to_response && sources.length > 0) {
        const topSource = sources[0];
        if (topSource && topSource.url) {
          navigatedToUrl = topSource.url;
          // Short delay to allow user to see the answer
          setTimeout(() => {
            window.location.href = topSource.url;
          }, 1500);
        }
      }

      // Log the chat interaction for analytics (don't await - fire and forget)
      logChatInteraction(originalQuestion, fullAnswer, sources, navigatedToUrl);

    } catch (error) {
      console.error('WordChat error:', error);

      // Remove loading message if it still exists
      if (loadingMessage && loadingMessage.parentNode) {
        loadingMessage.remove();
      }

      // Show user-friendly error message
      addMessage('Our AI is temporarily unavailable. Please try again in a moment.', 'error');
    } finally {
      // Re-enable input and button
      button.disabled = false;
      input.disabled = false;
      button.textContent = originalButtonText;
      input.focus();

      // Force scroll after everything is done
      setTimeout(() => scrollToBottom(), 100);
    }
  }

  // Event listeners
  button.addEventListener('click', sendQuery);

  input.addEventListener('keypress', (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendQuery();
    }
  });

  // Focus input on load and ensure scroll to bottom
  input.focus();

  // Final scroll to bottom after everything is loaded
  setTimeout(() => scrollToBottom(), 200);
  setTimeout(() => scrollToBottom(), 500);

  // Ensure scroll to bottom whenever widget becomes visible
  const observer = new MutationObserver(() => {
    if (container.style.display !== 'none') {
      scrollToBottom();
    }
  });
  observer.observe(container, { attributes: true, attributeFilter: ['style'] });
});
