(function(factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['jquery'], factory);
  } else if (typeof module === 'object' && module.exports) {
    // Node/CommonJS
    module.exports = factory(require('jquery'));
  } else {
    // Browser globals
    factory(window.jQuery);
  }
}(function($) {
  // Config keys to check
  var AI_KEYS = ['AI_OPENAI', 'AI_CLAUDE', 'AI_GEMINI', 'AI_MISTRAL', 'AI_DEEPSEEK'];

  // Utility: get first available API key and its type
  function getFirstAIKey(config) {
    for (var i = 0; i < AI_KEYS.length; i++) {
      var key = AI_KEYS[i];
      if (config[key] && config[key] !== '') {
        return { type: key, value: config[key] };
      }
    }
    return null;
  }

  // Utility: get endpoint for a given type
  function getEndpoint(type) {
    // All are OpenAI compatible for this plugin
    return 'https://api.openai.com/v1/chat/completions';
  }

  var AI_SUFFIX = ' Only return the improved text. Do not include any HTML, code blocks, or formatting. Do not wrap your answer in any tags.';

  // AI functions for textareas
  var AI_FUNCTIONS = [
    { name: 'Summarize', prompt: 'Summarize the following text:' + AI_SUFFIX },
    { name: 'Improve Writing', prompt: 'Improve the clarity and style of this text:' + AI_SUFFIX },
    { name: 'Fix Grammar', prompt: 'Correct the grammar and spelling in this text:' + AI_SUFFIX },
    { name: 'Continue Writing', prompt: 'Continue writing from where this text ends:' + AI_SUFFIX },
    { name: 'Shorten', prompt: 'Shorten this text while keeping the main ideas:' + AI_SUFFIX },
    { name: 'Expand', prompt: 'Expand on the ideas in this text:' + AI_SUFFIX },
    { name: 'Change Tone to Professional', prompt: 'Change the tone of this text to be more professional:' + AI_SUFFIX }
  ];

  // Add the plugin using the original registration method for maximum compatibility
  $.summernote = $.summernote || {};
  $.summernote.plugins = $.summernote.plugins || {};
  $.summernote.plugins['SummernoteMagic'] = function(context) {
    var ui = $.summernote.ui;
    var options = context.options;
    var $editor = context.layoutInfo.editor;
    var $editable = context.layoutInfo.editable;
    var $editingArea = context.layoutInfo.editingArea;

    var config = options.magicAIConfig || window.magicAIConfig || {};
    var aiKeyObj = getFirstAIKey(config);

    // This variable will hold our dropdown, scoped to the plugin instance
    var $dropdown = null;

    // This function will be called to close and clean up the dropdown
    var closeDropdown = function() {
      if ($dropdown) {
        $dropdown.remove();
        $dropdown = null;
      }
      // Unbind document events to prevent memory leaks
      $(document).off('mousedown.summernote-magic keydown.summernote-magic');
    };

    // This function runs the AI task
    var runAIFunction = function(prompt) {
      // --- CORE FIX #1: Use context.invoke to get editor content ---
      var range = context.invoke('editor.createRange');
      var selectedText = range.toString();
      var textToSend = selectedText || context.invoke('editor.getText');

      if (!textToSend || typeof textToSend !== 'string' || textToSend.trim() === '') {
        alert('Please select text or add content to the editor before using AI Magic.');
        return;
      }
      
      // --- FIX #2: Improved loading spinner ---
      // It now correctly overlays the editing area.
      var $spinner = $('<div class="magic-spinner" style="position:absolute; top:0; left:0; width:100%; height:100%; background:rgba(255,255,255,0.8); display:flex; align-items:center; justify-content:center; z-index:10;"><span style="font-style:italic;color:#333;">AI is thinking...</span></div>');
      $editingArea.append($spinner);

      // Prepare OpenAI-compatible API call
      var data = {
        model: 'gpt-3.5-turbo',
        messages: [
          { role: 'system', content: prompt },
          { role: 'user', content: textToSend }
        ],
        max_tokens: 2048,
        temperature: 0.7
      };

      $.ajax({
        url: getEndpoint(aiKeyObj.type),
        method: 'POST',
        headers: {
          'Authorization': 'Bearer ' + aiKeyObj.value,
          'Content-Type': 'application/json'
        },
        data: JSON.stringify(data),
        success: function(resp) {
          var aiText = '';
          if (resp.choices && resp.choices.length > 0 && resp.choices[0].message) {
            aiText = resp.choices[0].message.content.trim();
          }

          if (aiText) {
            // --- CORE FIX #3: Use context.invoke to insert content ---
            if (selectedText) {
              // If text was selected, just replace that text
              context.invoke('editor.insertText', aiText);
            } else {
              // If no text was selected, replace the entire editor content
              context.invoke('editor.code', aiText);
            }
          } else {
            alert('The AI did not return any text.');
          }
        },
        error: function(xhr) {
          var errorMsg = 'AI request failed.';
          if (xhr.responseJSON && xhr.responseJSON.error) {
            errorMsg += ' ' + xhr.responseJSON.error.message;
          } else {
            errorMsg += ' Status: ' + xhr.statusText;
          }
          alert(errorMsg);
        },
        complete: function() {
          // Always remove spinner and restore focus
          $spinner.remove();
          context.invoke('editor.focus');
        }
      });
    };

    // Only add the button if an API key is present
    if (!aiKeyObj) {
        return;
    }

    // Add the button to the toolbar
    context.memo('button.SummernoteMagic', function() {
      return ui.button({
        // --- FIX #4: Reverted to your original icon ---
        // This assumes you have Bootstrap Icons loaded. Change to 'fa fa-magic' for Font Awesome.
        contents: '<i class="bi bi-magic"></i>',
        tooltip: 'AI Magic',
        className: 'note-btn-magic',
        click: function(e) {
          e.stopPropagation();

          // If dropdown is already open, close it. Otherwise, open it.
          if ($dropdown) {
            closeDropdown();
            return;
          }

          // Create the dropdown menu
          $dropdown = $('<div class="dropdown-menu show" style="min-width:220px;"></div>');

          AI_FUNCTIONS.forEach(function(fn) {
            var $item = $('<a class="dropdown-item" href="#">' + fn.name + '</a>');
            $item.on('click', function(ev) {
              ev.preventDefault();
              runAIFunction(fn.prompt);
              closeDropdown();
            });
            $dropdown.append($item);
          });

          // Append dropdown to the button's parent (the button group)
          var $btn = $editor.find('.note-btn-magic');
          $btn.parent().append($dropdown);

          // Add event listeners to close the dropdown when clicking outside or pressing Escape
          setTimeout(function() {
            $(document).on('mousedown.summernote-magic', function(event) {
              // Check if the click is outside the button and the dropdown
              if (!$(event.target).closest('.note-btn-magic, .dropdown-menu').length) {
                closeDropdown();
              }
            });
            $(document).on('keydown.summernote-magic', function(event) {
              if (event.key === 'Escape') {
                closeDropdown();
              }
            });
          }, 0);
        }
      }).render();
    });
  };
}));