/**
 * OpenRPC UI JavaScript
 * Handles the interactive functionality of the OpenRPC UI
 */

document.addEventListener('DOMContentLoaded', function() {
  // Initialize form elements
  const specForm = document.getElementById('specForm');
  const rpcForm = document.getElementById('rpcForm');
  const paramsEditor = document.getElementById('paramsEditor');
  const resultContainer = document.getElementById('resultContainer');
  const resultOutput = document.getElementById('resultOutput');
  const errorContainer = document.getElementById('errorContainer');
  const errorOutput = document.getElementById('errorOutput');
  
  // Format JSON in the parameters editor
  if (paramsEditor && paramsEditor.value) {
    try {
      const params = JSON.parse(paramsEditor.value);
      paramsEditor.value = JSON.stringify(params, null, 2);
    } catch (e) {
      // If not valid JSON, leave as is
      console.warn('Could not format parameters as JSON:', e);
    }
  }
  
  // Handle RPC execution
  if (rpcForm) {
    rpcForm.addEventListener('submit', function(e) {
      e.preventDefault();
      
      // Hide previous results
      if (resultContainer) resultContainer.classList.add('d-none');
      if (errorContainer) errorContainer.classList.add('d-none');
      
      // Get form data
      const spec = document.getElementById('spec').value;
      const method = document.querySelector('input[name="selectedMethod"]').value;
      const socketPath = document.getElementById('socketPath').value;
      const paramsText = paramsEditor.value;
      
      // Show loading indicator
      const submitButton = rpcForm.querySelector('button[type="submit"]');
      const originalButtonText = submitButton.innerHTML;
      submitButton.disabled = true;
      submitButton.innerHTML = '<span class="loading-spinner me-2"></span>Executing...';
      
      // Validate
      if (!spec || !method || !socketPath) {
        showError('Missing required fields: spec, method, or socketPath');
        resetButton();
        return;
      }
      
      // Parse params
      let params;
      try {
        params = JSON.parse(paramsText);
      } catch (e) {
        showError('Invalid JSON parameters: ' + e.message);
        resetButton();
        return;
      }
      
      // Execute RPC
      fetch('/api/rpcui/execute', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          spec: spec,
          method: method,
          socketPath: socketPath,
          params: params
        })
      })
      .then(response => response.json())
      .then(data => {
        if (data.error) {
          showError(data.error);
        } else {
          showResult(data.result);
        }
      })
      .catch(error => {
        showError('Request failed: ' + error.message);
      })
      .finally(() => {
        resetButton();
      });
      
      function resetButton() {
        submitButton.disabled = false;
        submitButton.innerHTML = originalButtonText;
      }
      
      function showError(message) {
        if (errorContainer && errorOutput) {
          errorContainer.classList.remove('d-none');
          errorOutput.textContent = message;
        }
      }
      
      function showResult(result) {
        if (resultContainer && resultOutput) {
          resultContainer.classList.remove('d-none');
          resultOutput.textContent = JSON.stringify(result, null, 2);
        }
      }
    });
  }
  
  // Method tree navigation
  const methodItems = document.querySelectorAll('.method-item');
  methodItems.forEach(item => {
    item.addEventListener('click', function(e) {
      // Already handled by href, but could add additional functionality here
    });
  });
  
  // Format JSON examples
  const jsonExamples = document.querySelectorAll('pre code');
  jsonExamples.forEach(example => {
    try {
      const content = example.textContent;
      const json = JSON.parse(content);
      example.textContent = JSON.stringify(json, null, 2);
    } catch (e) {
      // If not valid JSON, leave as is
      console.warn('Could not format example as JSON:', e);
    }
  });
  
  // Add syntax highlighting if a library like highlight.js is available
  if (typeof hljs !== 'undefined') {
    document.querySelectorAll('pre code').forEach((block) => {
      hljs.highlightBlock(block);
    });
  }
});