(function($) {
  'use strict';

  var state = {
    historyLoaded: false,
    cachedHistory: null
  };

  function getInitialHistory() {
    return window.mindwecoFrontend && window.mindwecoFrontend.initialHistory ?
      window.mindwecoFrontend.initialHistory :
      null;
  }

  function getTabSessionId() {
    if (window.MindwecoSessionState && typeof window.MindwecoSessionState.getTabSessionId === 'function') {
      return window.MindwecoSessionState.getTabSessionId();
    }

    try {
      return sessionStorage.getItem('mindweco_tab_session_id') || '';
    } catch (error) {
      return '';
    }
  }

  function restorePinnedMessages() {
    $('.mindweco-message').each(function() {
      var $message = $(this);
      var messageId = $message.attr('data-message-id');
      var isPinned = localStorage.getItem('pinned_' + messageId) === '1';
      if (isPinned) {
        $message.addClass('pinned');
        var $btn = $message.find('.pin-response');
        $btn.find('.pin-icon').hide();
        $btn.find('.unpin-icon').show();
      }
    });
  }

  var LITE_BANNER_TEXT = '⚡ <b>SmartMind Lite — Free Tier</b><br>You are using the free version of SmartMind AI. Responses are powered by a base model. <a href="https://smartmind.it" target="_blank" rel="noopener noreferrer">Upgrade to Premium</a> for advanced AI models and faster responses.';

  function showLiteBanner(scroll) {
    var isValid = window.MindwecoHelpers.isValidSubscription(
      mindwecoData.trialEndDate,
      mindwecoData.trial_status
    );

    $('.lite-banner').remove();

    if (!isValid) {
      var $msg = window.MindwecoMessages.add(LITE_BANNER_TEXT, 'bot', scroll || false, {});
      if ($msg) $msg.addClass('lite-banner');
    }
  }
  function displayHistory(data) {
    if (!Array.isArray(data) || data.length === 0) return;
    var $messages = $('#mindweco-messages');
    $messages.empty();
    if (window.MindwecoCitations && window.MindwecoCitations.clearPanel) {
      window.MindwecoCitations.clearPanel();
    }
    window.MindwecoMessages.showDefault();
    var isValid = window.MindwecoHelpers.isValidSubscription(
      mindwecoData.trialEndDate,
      mindwecoData.trial_status
    );

    var botBuffer = '';
    var botTimestamp = '';
    data.forEach(function(item, i) {
      var isLast = i === data.length - 1;
      var nextRole = !isLast ? data[i + 1].role : '';
      var nextStartsNewMessage = nextRole === 'user' || nextRole === 'operator';
      var summaryText = (mindwecoFrontend.summary || '').replace(/\s+/g, ' ').trim();

      function normalizeText(t) {
        return (t || '').replace(/\s+/g, ' ').trim();
      }

      if (item.role === 'user') {
        if (botBuffer) {
          var cleanedBuffer = window.MindwecoHelpers.cleanBotText(botBuffer);
          if (summaryText && normalizeText(cleanedBuffer) === summaryText) {
            window.MindwecoMessages.showDefault();
          } else {
            window.MindwecoMessages.add(cleanedBuffer, 'bot', false, {}, { updateSourcesPanel: false, timestamp: botTimestamp });
          }
          botBuffer = '';
          botTimestamp = '';
        }
        window.MindwecoMessages.add(item.message, 'user', false, {}, { timestamp: item.timestamp });
      } else if (item.role === 'operator') {
        if (botBuffer) {
          var operatorCleanedBuffer = window.MindwecoHelpers.cleanBotText(botBuffer);
          if (summaryText && normalizeText(operatorCleanedBuffer) === summaryText) {
            window.MindwecoMessages.showDefault();
          } else {
            window.MindwecoMessages.add(operatorCleanedBuffer, 'bot', false, {}, { updateSourcesPanel: false, timestamp: botTimestamp });
          }
          botBuffer = '';
          botTimestamp = '';
        }
        window.MindwecoMessages.add(item.message, 'bot', false, {}, {
          timestamp: item.timestamp,
          updateSourcesPanel: false,
          isOperator: true
        });
      } else if (item.role === 'bot') {
        botBuffer += item.message;
        botTimestamp = item.timestamp;
        if (isLast || nextStartsNewMessage) {
          var cleanedBuffer = window.MindwecoHelpers.cleanBotText(botBuffer);
          if (summaryText && normalizeText(cleanedBuffer) === summaryText) {
            window.MindwecoMessages.showDefault();
          } else {
            window.MindwecoMessages.add(cleanedBuffer, 'bot', false, {}, { updateSourcesPanel: false, timestamp: botTimestamp });
          }
          botBuffer = '';
          botTimestamp = '';
        }
      }
    });
    showLiteBanner(false);
    restorePinnedMessages();
    $messages.scrollTop($messages[0].scrollHeight);
  }

  function loadChatHistory() {
    var historyData = getInitialHistory();
    if (historyData && state.historyLoaded) {
      displayHistory(historyData);
      $('#mindweco-messages').scrollTop($('#mindweco-messages')[0].scrollHeight);
      restorePinnedMessages();
      return;
    }

    var $bar = $('#mindweco-history-bar');
    var currentPostId = mindwecoFrontend.post_id || 0;
    var conversationId = sessionStorage.getItem('mindweco_conversation_id') || '';

    $bar.show();

    $.get(mindwecoFrontend.ajax_url, {
        action: 'mindweco_get_history',
        post_id: currentPostId,
        conversation_id: conversationId,
        tab_session_id: getTabSessionId(),
        nonce: mindwecoFrontend.nonce
      })
      .done(function(data) {
        if (data.success && Array.isArray(data.data) && data.data.length > 0) {
          displayHistory(data.data);
          state.historyLoaded = true;
          state.cachedHistory = data.data;
        } else {
          state.historyLoaded = true;
          showLiteBanner(false);
        }
      })
      .fail(function(err) {
        MindwecoToast.error('Error loading history:');
        state.historyLoaded = true;
      })
      .always(function() {
        $bar.hide();
      })
  }

  function clearHistory() {
    if (!mindwecoFrontend || !mindwecoFrontend.nonce) {
      MindwecoToast.error('Nonce not found in mindwecoFrontend');
      return;
    }

    var $modal = $('#startNewChatModal');
    var $messages = $('#mindweco-messages');

    $.post(mindwecoFrontend.ajax_url, {
        action: 'mindweco_clear_history',
        tab_session_id: getTabSessionId(),
        nonce: mindwecoFrontend.nonce
      })
      .done(function(data) {
        if (data.success) {
          $messages.empty();
          state.historyLoaded = false;
          state.cachedHistory = null;

          try {
            sessionStorage.removeItem('mindweco_conversation_id');
          } catch (error) {}

          Object.keys(localStorage)
            .filter(function(k) {
              return k.startsWith('cit_') || k.startsWith('pinned_');
            })
            .forEach(function(k) {
              localStorage.removeItem(k);
            });

          try {
            localStorage.removeItem('mindweco_conversation_id');
          } catch (error) {}

          $modal.removeClass('show').css('display', 'none');
          window.MindwecoMessages.showDefault();
          setTimeout(function() {
            showLiteBanner(true);
          }, 50);
        } else {
          MindwecoToast.error(data.data && data.data.message ? data.data.message : 'Failed to clear history');
          $modal.removeClass('show').css('display', 'none');
        }
      })
      .fail(function(xhr, status, error) {
        MindwecoToast.error('Something went wrong. Please try again.');
        $modal.removeClass('show').css('display', 'none');
      });
  }

  function init() {
    var $modal = $('#startNewChatModal');

    $(document).off('click', '#clear-chat-history').on('click', '#clear-chat-history', function(e) {
      e.preventDefault();
      e.stopPropagation();
      $modal.addClass('show').css('display', 'flex');
    });

    $(document).on('click', '#startNewChatModal .btn-close', function(e) {
      e.preventDefault();
      e.stopPropagation();
      $modal.removeClass('show').css('display', 'none');
    });

    $(document).off('click', '#startNewChatModal').on('click', '#startNewChatModal', function(e) {
      if (e.target === this) $modal.removeClass('show').css('display', 'none');
    });

    $(document).off('click', '#startNewChatModal .modal-content').on('click', '#startNewChatModal .modal-content', function(e) {
      e.stopPropagation();
    });

    $(document).off('click', '#confirmNewChatBtn').on('click', '#confirmNewChatBtn', function(e) {
      e.preventDefault();
      e.stopPropagation();
      clearHistory();
    });

    var $checkbox = $('#mindweco-context-toggle');
    if ($checkbox.length) {
      var pageKeyBase = 'mindweco_ask_only_current_page';
      var pageIdentifier = 'global';

      if (mindwecoFrontend && mindwecoFrontend.post_id) {
        pageIdentifier = mindwecoFrontend.post_id;
      } else if (typeof mindwecoData !== 'undefined' && mindwecoData && mindwecoData.post_id) {
        pageIdentifier = mindwecoData.post_id;
      }

      var pageKey = pageKeyBase + '_' + pageIdentifier;
      var savedState = sessionStorage.getItem(pageKey);

      $checkbox.prop('checked', savedState === '1');

      $checkbox.on('change', function() {
        sessionStorage.setItem(pageKey, $(this).is(':checked') ? '1' : '0');
      });
    }
  }

  window.MindwecoHistory = {
    init: init,
    load: loadChatHistory,
    display: displayHistory,
    clear: clearHistory,
    restorePinnedMessages: restorePinnedMessages,
    showLiteBanner: showLiteBanner,
    getState: function() {
      return state;
    }
  };

})(jQuery);
