/**
 * Elementor Magic Button Integration
 * Adds Envato Elements button to Elementor "Add Section" areas
 */

(function() {
  'use strict';

  if (typeof jQuery === 'undefined') {
    return;
  }

  jQuery(function($) {
    
    function openEnvatoModal(event) {
      let insertPosition = 0;
      
      // Calculate insert position if we're in Elementor
      if (elementorCommon) {
        const $parent = $(event.target).parents('.elementor-section-wrap');
        if ($parent.length > 0) {
          insertPosition = $(this).parents('.elementor-add-section').index();
        } else {
          insertPosition = -1;
        }
      }

      // Remove any existing inline add sections
      if (insertPosition >= 0) {
        $(event.target).parents('.elementor-add-section-inline').remove();
      }

      // Create or get the modal holder div
      let modalHolder = document.getElementById('envato-elements-magic-button-holder');
      if (!modalHolder) {
        modalHolder = document.createElement('div');
        modalHolder.id = 'envato-elements-magic-button-holder';
        document.body.appendChild(modalHolder);
      }

      // Set up the magic button configuration
      const magicButtonConfig = {
        mode: 'elementorMagicButton',
        closeCallback: function() {
          window.envatoElements.closeMagicButton(modalHolder);
        },
        insertCallback: function(templateData) {
          console.log('insertCallback received:', templateData);
          
          if (typeof elementor === 'undefined') {
            console.error('Elementor is not available');
            return;
          }

          // The templateData from import has imported_template_id, we need to load that template
          if (templateData.imported_template_id) {
            console.log('Inserting template ID:', templateData.imported_template_id);
            
            // Get the template data from Elementor and insert it
            if (typeof $e !== 'undefined' && elementor.templates) {
              // Fetch the template from Elementor's library using 'local' source (our imported templates)
              elementor.templates.requestTemplateContent(
                'local',
                templateData.imported_template_id,
                {
                  data: {
                    edit_mode: 'builder',
                    display: true,
                    with_page_settings: false
                  },
                  success: function(data) {
                    console.log('Template content received:', data);
                    
                    if (data && data.content && Array.isArray(data.content)) {
                      const historyId = $e.internal('document/history/start-log', {
                        type: 'add',
                        title: 'Add Envato Elements Template'
                      });

                      for (let i = 0; i < data.content.length; i++) {
                        $e.run('document/elements/create', {
                          container: elementor.getPreviewContainer(),
                          model: data.content[i],
                          options: insertPosition >= 0 ? { at: insertPosition++ } : {}
                        });
                      }

                      $e.internal('document/history/end-log', { id: historyId });
                    }
                    
                    // Close the modal
                    window.envatoElements.closeMagicButton(modalHolder);
                  },
                  error: function(err) {
                    console.error('Failed to get template content:', err);
                    alert('Failed to insert template. Please try again.');
                  }
                }
              );
            } else if (elementor.templates) {
              // Legacy fallback
              elementor.templates.importTemplate({
                template_id: templateData.imported_template_id
              });
              window.envatoElements.closeMagicButton(modalHolder);
            }
            
            return;
          }

          // Fallback: if we have content array, insert it directly
          if (!templateData.content || !Array.isArray(templateData.content)) {
            console.error('No content to insert', templateData);
            return;
          }

          // Use modern Elementor API if available
          if (typeof $e !== 'undefined') {
            const historyId = $e.internal('document/history/start-log', {
              type: 'add',
              title: 'Add Envato Elements Content'
            });

            for (let i = 0; i < templateData.content.length; i++) {
              $e.run('document/elements/create', {
                container: elementor.getPreviewContainer(),
                model: templateData.content[i],
                options: insertPosition >= 0 ? { at: insertPosition++ } : {}
              });
            }

            $e.internal('document/history/end-log', { id: historyId });
          } else {
            // Fallback to legacy Elementor API
            const model = new Backbone.Model({
              getTitle: () => 'Envato Elements Template'
            });

            elementor.channels.data.trigger('template:before:insert', model);

            for (let i = 0; i < templateData.content.length; i++) {
              elementor.getPreviewView().addChildElement(
                templateData.content[i],
                insertPosition >= 0 ? { at: insertPosition++ } : null
              );
            }

            elementor.channels.data.trigger('template:after:insert', {});
          }

          // Close the modal after insertion
          window.envatoElements.closeMagicButton(modalHolder);
        }
      };

      // Open the magic button modal
      window.envatoElements.initMagicButton(modalHolder, magicButtonConfig);
    }

    // Modify the Elementor "Add Section" template to include our button
    const addSectionTemplate = $('#tmpl-elementor-add-section');
    if (addSectionTemplate.length > 0) {
      let templateContent = addSectionTemplate.text();
      
      // Inject our Envato button before the drag title
      templateContent = templateContent.replace(
        '<div class="elementor-add-section-drag-title',
        '<div class="elementor-add-section-area-button elementor-add-envato-button" title="Envato Elements"> ' +
        '<i class="dashicons dashicons-download"></i> ' +
        '</div>' +
        '<div class="elementor-add-section-drag-title'
      );
      
      addSectionTemplate.text(templateContent);

      // Attach click handler when Elementor preview is loaded
      elementor.on('preview:loaded', function() {
        $(elementor.$previewContents[0].body).on('click', '.elementor-add-envato-button', openEnvatoModal);
      });
    }

  });

})();

