/**
 * Enhanced drag-and-drop functionality for the workflow area
 * Allows blocks to be reordered by dragging and dropping
 */

// Enhanced block manager with improved drag-drop handling
function createBlockManager() {
  return {
      blocks: [],
      selectedBlockId: null,
      
      // Add a new block to the workflow
      addBlock: function(blockData) {
          const blockId = 'block-' + Date.now();
          const newBlock = {
              id: blockId,
              type: blockData.type,
              properties: blockData.properties || {}
          };
          
          this.blocks.push(newBlock);
          this.renderWorkflow();
          this.selectBlock(blockId);
          return blockId;
      },
      
      // Remove a block from the workflow
      removeBlock: function(blockId) {
          this.blocks = this.blocks.filter(block => block.id !== blockId);
          if (this.selectedBlockId === blockId) {
              this.selectedBlockId = null;
              this.updatePropertiesPanel();
          }
          this.renderWorkflow();
      },
      
      // Update a block's properties
      updateBlock: function(blockId, properties) {
          const blockIndex = this.blocks.findIndex(block => block.id === blockId);
          if (blockIndex !== -1) {
              this.blocks[blockIndex].properties = { 
                  ...this.blocks[blockIndex].properties,
                  ...properties
              };
              this.renderWorkflow();
              this.updateBlockSummary(blockId);
          }
      },
      
      // Select a block to edit its properties
      selectBlock: function(blockId) {
          this.selectedBlockId = blockId;
          
          // Highlight the selected block
          document.querySelectorAll('.workflow-block').forEach(blockEl => {
              blockEl.classList.remove('selected');
          });
          
          const blockEl = document.getElementById(blockId);
          if (blockEl) {
              blockEl.classList.add('selected');
          }
          
          this.updatePropertiesPanel();
      },
      
      // Render all blocks in the workflow
      renderWorkflow: function() {
          const workflowArea = document.querySelector('.workflow-area');
          if (!workflowArea) return;
          
          // Clear existing blocks
          workflowArea.innerHTML = '';
          
          if (this.blocks.length === 0) {
              workflowArea.innerHTML = `
                  <div class="empty-workflow-message">
                      <p>Drag blocks from the library to start building your application</p>
                  </div>
              `;
              return;
          }
          
          // Render each block
          this.blocks.forEach((block, index) => {
              const blockEl = this.createBlockElement(block, index);
              workflowArea.appendChild(blockEl);
          });
          
          // Setup drag-and-drop reordering
          this.setupDragReordering();
          
          // Update preview
          if (typeof updatePreview === 'function') {
              updatePreview();
          }
      },
      
      // Create a DOM element for a block
      createBlockElement: function(block, index) {
          const blockEl = document.createElement('div');
          blockEl.className = 'workflow-block';
          blockEl.id = block.id;
          blockEl.setAttribute('data-index', index);
          blockEl.setAttribute('data-type', block.type);
          blockEl.setAttribute('draggable', 'true'); // Make all blocks draggable
          
          // Create block content
          const blockContent = document.createElement('div');
          blockContent.className = 'block-content';
          
          // Set block title based on type
          const blockTitle = document.createElement('div');
          blockTitle.className = 'block-title';
          
          let title = '';
          let iconHtml = '';
          
          switch(block.type) {
              case 'drawText':
                  title = 'Text';
                  iconHtml = '<span class="block-icon">T</span>';
                  break;
              case 'setPixel':
                  title = 'Pixel';
                  iconHtml = '<span class="block-icon">⬛</span>';
                  break;
              case 'getData':
                  title = 'Data';
                  iconHtml = '<span class="block-icon">🔄</span>';
                  break;
              default:
                  title = block.type;
                  iconHtml = '<span class="block-icon">📦</span>';
          }
          
          blockTitle.innerHTML = iconHtml + ' ' + title;
          blockContent.appendChild(blockTitle);
          
          // Set layer indicator
          const layerIndicator = document.createElement('div');
          layerIndicator.className = 'layer-indicator';
          layerIndicator.textContent = `Layer ${index + 1}`;
          blockContent.appendChild(layerIndicator);
          
          // Create block summary
          const blockSummary = document.createElement('div');
          blockSummary.className = 'block-summary';
          
          // Populate summary based on block type
          switch(block.type) {
              case 'drawText':
                  blockSummary.innerHTML = `
                      <div>Text: <span class="text-value">${block.properties.text || 'Text'}</span></div>
                      <div>Position: (<span class="x-value">${block.properties.x || '0'}</span>, <span class="y-value">${block.properties.y || '0'}</span>)</div>
                  `;
                  break;
                  
              case 'setPixel':
                  blockSummary.innerHTML = `
                      <div>Position: (<span class="x-value">${block.properties.x || '0'}</span>, <span class="y-value">${block.properties.y || '0'}</span>)</div>
                  `;
                  break;
                  
              case 'getData':
                  const url = block.properties.url || 'api.example.com';
                  blockSummary.innerHTML = `
                      <div>URL: <span class="url-value">${url.replace(/^https?:\/\//, '')}</span></div>
                  `;
                  break;
          }
          
          blockContent.appendChild(blockSummary);
          blockEl.appendChild(blockContent);
          
          // Add block actions
          const blockActions = document.createElement('div');
          blockActions.className = 'block-actions';
          
          // Edit button
          const editBtn = document.createElement('button');
          editBtn.className = 'block-edit';
          editBtn.innerHTML = `
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M11 4H4C3.44772 4 3 4.44772 3 5V19C3 19.5523 3.44772 20 4 20H18C18.5523 20 19 19.5523 19 19V12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  <path d="M17.5 2.5C18.3284 1.67157 19.6716 1.67157 20.5 2.5C21.3284 3.32843 21.3284 4.67157 20.5 5.5L12 14L8 15L9 11L17.5 2.5Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
          `;
          editBtn.addEventListener('click', (e) => {
              e.stopPropagation(); // Prevent triggering the block selection
              this.selectBlock(block.id);
          });
          
          // Delete button
          const deleteBtn = document.createElement('button');
          deleteBtn.className = 'block-delete';
          deleteBtn.innerHTML = `
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M3 6H5H21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  <path d="M19 6V20C19 20.5304 18.7893 21.0391 18.4142 21.4142C18.0391 21.7893 17.5304 22 17 22H7C6.46957 22 5.96086 21.7893 5.58579 21.4142C5.21071 21.0391 5 20.5304 5 20V6M8 6V4C8 3.46957 8.21071 2.96086 8.58579 2.58579C8.96086 2.21071 9.46957 2 10 2H14C14.5304 2 15.0391 2.21071 15.4142 2.58579C15.7893 2.96086 16 3.46957 16 4V6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
          `;
          deleteBtn.addEventListener('click', (e) => {
              e.stopPropagation(); // Prevent triggering the block selection
              if (confirm('Are you sure you want to delete this block?')) {
                  this.removeBlock(block.id);
              }
          });
          
          // Drag handle
          const dragHandle = document.createElement('div');
          dragHandle.className = 'block-drag-handle';
          dragHandle.innerHTML = `
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M4 8H20M4 16H20" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
          `;
          
          blockActions.appendChild(editBtn);
          blockActions.appendChild(deleteBtn);
          blockActions.appendChild(dragHandle);
          blockEl.appendChild(blockActions);
          
          // Add click event to select block (but not during drag)
          blockEl.addEventListener('click', (e) => {
              // Don't trigger when clicking action buttons
              if (!e.target.closest('.block-actions')) {
                  this.selectBlock(block.id);
              }
          });
          
          return blockEl;
      },
      
      // Setup drag reordering functionality
      setupDragReordering: function() {
          const workflowArea = document.querySelector('.workflow-area');
          if (!workflowArea) return;
          
          const blocks = workflowArea.querySelectorAll('.workflow-block');
          
          // Add drag start event to all blocks
          blocks.forEach(block => {
              // Dragstart - when the user starts dragging
              block.addEventListener('dragstart', (e) => {
                  e.dataTransfer.effectAllowed = 'move';
                  e.dataTransfer.setData('text/plain', block.id);
                  block.classList.add('dragging');
                  
                  // Add a slight delay to allow the drag image to be created
                  setTimeout(() => {
                      block.style.opacity = '0.4';
                  }, 0);
                  
                  // Create ghost image for drag
                  const ghostEl = block.cloneNode(true);
                  ghostEl.style.position = 'absolute';
                  ghostEl.style.top = '-1000px';
                  ghostEl.style.opacity = '0.8';
                  document.body.appendChild(ghostEl);
                  e.dataTransfer.setDragImage(ghostEl, 20, 20);
                  
                  // Remove ghost after a short delay
                  setTimeout(() => {
                      document.body.removeChild(ghostEl);
                  }, 100);
              });
              
              // Dragend - when the user stops dragging
              block.addEventListener('dragend', () => {
                  block.classList.remove('dragging');
                  block.style.opacity = '1';
                  
                  // Remove all drop indicators
                  document.querySelectorAll('.drop-indicator').forEach(el => {
                      el.remove();
                  });
                  workflowArea.classList.remove('drag-active');
              });
          });
          
          // Setup the workflow area to accept drops
          workflowArea.addEventListener('dragover', (e) => {
              e.preventDefault();
              e.dataTransfer.dropEffect = 'move';
              workflowArea.classList.add('drag-active');
              
              // Get the block being dragged
              const draggingBlockId = e.dataTransfer.getData('text/plain');
              const draggingBlock = document.querySelector('.dragging');
              if (!draggingBlock) return;
              
              // Find the block we're dragging over
              const afterElement = this.getDragAfterElement(workflowArea, e.clientY);
              
              // Remove existing drop indicators
              document.querySelectorAll('.drop-indicator').forEach(el => {
                  el.remove();
              });
              
              // Create a drop indicator
              const dropIndicator = document.createElement('div');
              dropIndicator.className = 'drop-indicator';
              
              if (afterElement) {
                  workflowArea.insertBefore(dropIndicator, afterElement);
              } else {
                  workflowArea.appendChild(dropIndicator);
              }
          });
          
          // Handle dropping
          workflowArea.addEventListener('drop', (e) => {
              e.preventDefault();
              workflowArea.classList.remove('drag-active');
              
              // Remove drop indicators
              document.querySelectorAll('.drop-indicator').forEach(el => {
                  el.remove();
              });
              
              // Get the block being dropped
              const blockId = e.dataTransfer.getData('text/plain');
              if (!blockId) return;
              
              // Find the block in our data
              const blockIndex = this.blocks.findIndex(block => block.id === blockId);
              if (blockIndex === -1) return;
              
              // Find where to drop it
              const afterElement = this.getDragAfterElement(workflowArea, e.clientY);
              
              // Calculate new index
              let newIndex;
              if (afterElement) {
                  const afterBlockId = afterElement.id;
                  const afterBlockIndex = this.blocks.findIndex(block => block.id === afterBlockId);
                  
                  // If dropping above the current position, adjust index
                  newIndex = afterBlockIndex;
                  if (blockIndex < afterBlockIndex) {
                      newIndex--;
                  }
              } else {
                  // If dropping at the end
                  newIndex = this.blocks.length - 1;
              }
              
              // Don't reorder if the index is the same or invalid
              if (newIndex === blockIndex || newIndex < 0 || newIndex >= this.blocks.length) {
                  return;
              }
              
              // Reorder blocks
              const [movedBlock] = this.blocks.splice(blockIndex, 1);
              this.blocks.splice(newIndex, 0, movedBlock);
              
              // Re-render the workflow
              this.renderWorkflow();
          });
          
          // Handle drag leave from workflow area
          workflowArea.addEventListener('dragleave', (e) => {
              // Check if leaving the container (not just moving between children)
              const rect = workflowArea.getBoundingClientRect();
              if (
                  e.clientX <= rect.left ||
                  e.clientX >= rect.right ||
                  e.clientY <= rect.top ||
                  e.clientY >= rect.bottom
              ) {
                  workflowArea.classList.remove('drag-active');
                  document.querySelectorAll('.drop-indicator').forEach(el => {
                      el.remove();
                  });
              }
          });
      },
      
      // Helper function to determine where to drop
      getDragAfterElement: function(container, y) {
          // Get all non-dragging blocks
          const draggableElements = [...container.querySelectorAll('.workflow-block:not(.dragging)')];
          
          // Find the first element that's below the cursor
          return draggableElements.reduce((closest, child) => {
              const box = child.getBoundingClientRect();
              const offset = y - box.top - box.height / 2;
              
              if (offset < 0 && offset > closest.offset) {
                  return { offset: offset, element: child };
              } else {
                  return closest;
              }
          }, { offset: Number.NEGATIVE_INFINITY }).element;
      },
      
      // Update a block's summary display
      updateBlockSummary: function(blockId) {
          const blockEl = document.getElementById(blockId);
          if (!blockEl) return;
          
          const block = this.blocks.find(b => b.id === blockId);
          if (!block) return;
          
          // Get summary element
          const summary = blockEl.querySelector('.block-summary');
          if (!summary) return;
          
          switch(block.type) {
              case 'drawText':
                  const textValue = summary.querySelector('.text-value');
                  if (textValue) textValue.textContent = block.properties.text || 'Text';
                  
                  const xValue = summary.querySelector('.x-value');
                  if (xValue) xValue.textContent = block.properties.x || '0';
                  
                  const yValue = summary.querySelector('.y-value');
                  if (yValue) yValue.textContent = block.properties.y || '0';
                  break;
                  
              case 'setPixel':
                  const pixelX = summary.querySelector('.x-value');
                  if (pixelX) pixelX.textContent = block.properties.x || '0';
                  
                  const pixelY = summary.querySelector('.y-value');
                  if (pixelY) pixelY.textContent = block.properties.y || '0';
                  break;
                  
              case 'getData':
                  const urlValue = summary.querySelector('.url-value');
                  if (urlValue) {
                      const url = block.properties.url || 'api.example.com';
                      urlValue.textContent = url.replace(/^https?:\/\//, '');
                  }
                  break;
          }
      },
      
      // Show properties for the selected block
      updatePropertiesPanel: function() {
          const propertiesContainer = document.querySelector('.properties-container');
          if (!propertiesContainer) return;
          
          // Clear existing content
          propertiesContainer.innerHTML = '';
          
          // If no block is selected, show default message
          if (!this.selectedBlockId) {
              propertiesContainer.innerHTML = `
                  <div class="no-block-selected-message">
                      <p>Select a block to edit its properties</p>
                  </div>
              `;
              return;
          }
          
          // Find the selected block
          const block = this.blocks.find(b => b.id === this.selectedBlockId);
          if (!block) return;
          
          // Create properties form based on block type
          const propertiesForm = document.createElement('div');
          propertiesForm.className = 'block-properties';
          
          // Add form title
          const formTitle = document.createElement('h3');
          formTitle.className = 'properties-title';
          formTitle.textContent = this.getBlockTypeName(block.type) + ' Properties';
          propertiesForm.appendChild(formTitle);
          
          // Create form fields based on block type
          this.createPropertyFields(propertiesForm, block);
          
          // Add to container
          propertiesContainer.appendChild(propertiesForm);
          
          // Add event listeners to inputs
          this.setupPropertyListeners(propertiesForm, block.id);
      },
      
      // Helper to get block type display name
      getBlockTypeName: function(type) {
          switch(type) {
              case 'drawText': return 'Text';
              case 'setPixel': return 'Pixel';
              case 'getData': return 'Data';
              default: return type;
          }
      },
      
      // Create property fields based on block type
      createPropertyFields: function(container, block) {
          switch(block.type) {
              case 'drawText':
                  this.createTextField(container, 'text', 'Text', block.properties.text || 'Text');
                  this.createNumberField(container, 'x', 'X Position', block.properties.x || 0);
                  this.createNumberField(container, 'y', 'Y Position', block.properties.y || 0);
                  this.createColorField(container, 'color', 'Color', block.properties.color || '#00FF00');
                  this.createSelectField(container, 'font', 'Font', 
                      ['bitmap_3x4', 'bitmap_3x5', 'bitmap_4x5', 'bitmap_5x7', 'bitmap_6x8', 'bitmap_7x16', 'bitmap_10x16'],
                      block.properties.font || 'bitmap_5x7');
                  this.createSelectField(container, 'alignment', 'Alignment', 
                      ['left', 'center', 'right'],
                      block.properties.alignment || 'left');
                  break;
                  
              case 'setPixel':
                  this.createNumberField(container, 'x', 'X Position', block.properties.x || 0);
                  this.createNumberField(container, 'y', 'Y Position', block.properties.y || 0);
                  this.createColorField(container, 'color', 'Color', block.properties.color || '#FFFFFF');
                  break;
                  
              case 'getData':
                  this.createTextField(container, 'url', 'API URL', block.properties.url || 'https://api.example.com/data');
                  this.createTextField(container, 'apiKey', 'API Key', block.properties.apiKey || '');
                  this.createTextField(container, 'variable', 'Variable Name', block.properties.variable || 'data');
                  break;
          }
      },
      
      // Helper to create a text input field
      createTextField: function(container, name, label, value) {
          const group = document.createElement('div');
          group.className = 'form-group';
          
          const labelEl = document.createElement('label');
          labelEl.setAttribute('for', 'prop-' + name);
          labelEl.textContent = label;
          
          const input = document.createElement('input');
          input.type = 'text';
          input.id = 'prop-' + name;
          input.name = name;
          input.value = value;
          
          group.appendChild(labelEl);
          group.appendChild(input);
          container.appendChild(group);
      },
      
      // Helper to create a number input field
      createNumberField: function(container, name, label, value) {
          const group = document.createElement('div');
          group.className = 'form-group';
          
          const labelEl = document.createElement('label');
          labelEl.setAttribute('for', 'prop-' + name);
          labelEl.textContent = label;
          
          const input = document.createElement('input');
          input.type = 'number';
          input.id = 'prop-' + name;
          input.name = name;
          input.value = value;
          
          group.appendChild(labelEl);
          group.appendChild(input);
          container.appendChild(group);
      },
      
      // Helper to create a color input field
      createColorField: function(container, name, label, value) {
          const group = document.createElement('div');
          group.className = 'form-group';
          
          const labelEl = document.createElement('label');
          labelEl.setAttribute('for', 'prop-' + name);
          labelEl.textContent = label;
          
          const wrapper = document.createElement('div');
          wrapper.className = 'color-input-wrapper';
          wrapper.style.display = 'flex';
          wrapper.style.gap = '0.5rem';
          
          const colorInput = document.createElement('input');
          colorInput.type = 'color';
          colorInput.id = 'prop-' + name + '-picker';
          colorInput.value = value;
          colorInput.style.width = '50px';
          colorInput.style.height = '30px';
          colorInput.style.padding = '0';
          colorInput.style.border = 'none';
          
          const textInput = document.createElement('input');
          textInput.type = 'text';
          textInput.id = 'prop-' + name;
          textInput.name = name;
          textInput.value = value;
          textInput.style.flex = '1';
          
          // Sync inputs
          colorInput.addEventListener('input', () => {
              textInput.value = colorInput.value;
          });
          
          textInput.addEventListener('input', () => {
              if (/^#[0-9A-F]{6}$/i.test(textInput.value)) {
                  colorInput.value = textInput.value;
              }
          });
          
          wrapper.appendChild(colorInput);
          wrapper.appendChild(textInput);
          
          group.appendChild(labelEl);
          group.appendChild(wrapper);
          container.appendChild(group);
      },
      
      // Helper to create a select field
      createSelectField: function(container, name, label, options, value) {
          const group = document.createElement('div');
          group.className = 'form-group';
          
          const labelEl = document.createElement('label');
          labelEl.setAttribute('for', 'prop-' + name);
          labelEl.textContent = label;
          
          const select = document.createElement('select');
          select.id = 'prop-' + name;
          select.name = name;
          
          options.forEach(option => {
              const optionEl = document.createElement('option');
              optionEl.value = option;
              
              // For font options, show a simplified display name
              if (name === 'font') {
                  optionEl.textContent = option.replace('bitmap_', '');
              } else {
                  optionEl.textContent = option.charAt(0).toUpperCase() + option.slice(1);
              }
              
              if (option === value) {
                  optionEl.selected = true;
              }
              
              select.appendChild(optionEl);
          });
          
          group.appendChild(labelEl);
          group.appendChild(select);
          container.appendChild(group);
      },
      
      // Setup event listeners for property fields
      setupPropertyListeners: function(container, blockId) {
          container.querySelectorAll('input, select').forEach(input => {
              const eventType = input.type === 'color' ? 'input' : 'change';
              
              input.addEventListener(eventType, () => {
                  const propName = input.name;
                  let propValue = input.value;
                  
                  // Handle number conversion
                  if (input.type === 'number') {
                      propValue = parseInt(propValue);
                      if (isNaN(propValue)) propValue = 0;
                  }
                  
                  // Skip if no change
                  const block = this.blocks.find(b => b.id === blockId);
                  if (block && block.properties[propName] === propValue) {
                      return;
                  }
                  
                  // Update block properties
                  const updateData = {};
                  updateData[propName] = propValue;
                  this.updateBlock(blockId, updateData);
                  
                  // Update preview
                  if (typeof updatePreview === 'function') {
                      updatePreview();
                  }
              });
          });
      }
  };
}

/**
* Add CSS styles for the drag and drop interface
*/
function addDragDropStyles() {
  const styleId = 'drag-drop-styles';
  
  // Don't add styles if they already exist
  if (document.getElementById(styleId)) return;
  
  const style = document.createElement('style');
  style.id = styleId;
  style.textContent = `

  `;
  
  document.head.appendChild(style);
}

/**
* Initialize the drag and drop interface
*/
function initDragDropInterface() {
  // Add required styles
  addDragDropStyles();
  
  // Initialize the block manager
  window.blockManager = createBlockManager();
  
  // Render initial workflow
  if (window.blockManager.blocks && window.blockManager.blocks.length > 0) {
      window.blockManager.renderWorkflow();
  }
  
  // Setup block library drag-and-drop
//   setupBlockLibrary();
}

/**
* Setup block library drag-and-drop functionality
*/
// function setupBlockLibrary() {
//   const blockItems = document.querySelectorAll('.block');
//   const workflowArea = document.querySelector('.workflow-area');
  
//   if (!blockItems.length || !workflowArea) {
//       console.error('Block library or workflow area not found');
//       return;
//   }
  
//   // Setup block library items as draggable
//   blockItems.forEach(blockItem => {
//       blockItem.setAttribute('draggable', 'true');
      
//       blockItem.addEventListener('dragstart', (e) => {
//           const blockType = blockItem.getAttribute('data-block-type');
//           e.dataTransfer.setData('application/block-type', blockType);
//           e.dataTransfer.effectAllowed = 'copy';
//           blockItem.classList.add('dragging');
//       });
      
//       blockItem.addEventListener('dragend', () => {
//           blockItem.classList.remove('dragging');
//       });
//   });
  
//   // Setup workflow area as drop target
//   workflowArea.addEventListener('dragover', (e) => {
//       e.preventDefault();
//       e.dataTransfer.dropEffect = 'copy';
//       workflowArea.classList.add('drag-active');
//   });
  
//   workflowArea.addEventListener('dragleave', (e) => {
//       // Only remove highlighting if actually leaving the container
//       const rect = workflowArea.getBoundingClientRect();
//       if (
//           e.clientX <= rect.left ||
//           e.clientX >= rect.right ||
//           e.clientY <= rect.top ||
//           e.clientY >= rect.bottom
//       ) {
//           workflowArea.classList.remove('drag-active');
//       }
//   });
  
//   workflowArea.addEventListener('drop', (e) => {
//       e.preventDefault();
//       workflowArea.classList.remove('drag-active');
      
//       // Handle block library drops
//       const blockType = e.dataTransfer.getData('application/block-type');
//       if (blockType) {
//           // Get canvas dimensions for setting defaults
//           const canvasSize = document.body.getAttribute('data-canvas-size') || '64x32';
//           const [canvasWidth, canvasHeight] = canvasSize.split('x').map(Number);
          
//           // Create block with default properties
//           const blockData = {
//               type: blockType,
//               properties: getDefaultProperties(blockType, canvasWidth, canvasHeight)
//           };
          
//           window.blockManager.addBlock(blockData);
//       }
//   });
// }

/**
* Get default properties for block types
*/
function getDefaultProperties(blockType, canvasWidth = 64, canvasHeight = 32) {
  switch(blockType) {
      case 'text':
      case 'drawText':
          return {
              text: 'GLANCE',
              x: 5,
              y: 10,
              color: '#00FF00',
              font: 'bitmap_5x7',
              alignment: 'left'
          };
          
      case 'pixel':
      case 'setPixel':
          return {
              x: Math.floor(canvasWidth / 2),
              y: Math.floor(canvasHeight / 2),
              color: '#FFFFFF'
          };
          
      case 'api':
      case 'getData':
          return {
              url: 'https://api.example.com/data',
              apiKey: '',
              variable: 'data'
          };
          
      case 'shape':
          return {
              type: 'rectangle',
              x: 10,
              y: 10,
              width: 20,
              height: 10,
              color: '#FF0000'
          };
          
      case 'variable':
          return {
              name: 'myVariable',
              value: ''
          };
          
      case 'image':
          return {
              source: 'placeholder.png',
              x: 0,
              y: 0,
              width: 32,
              height: 32
          };
          
      default:
          return {};
  }
}

// Initialize drag and drop when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
  // Only initialize if we're in no-code mode
  if (document.body.getAttribute('data-mode') === 'no-code') {
      initDragDropInterface();
  }
});