function integrazo_wz_showErrorDetails(errorLogID) {
  jQuery.ajax({
    url: integrazo_wz_error_log.ajax_url,
    type: 'POST',
    data: {
      action: 'INTEGRAZO_WZ_Error_Log_show_action',
      log_id: errorLogID,
      security: integrazo_wz_error_log.error_log_nonce
    },
    success: function (response) {

      if (!response || !response.success || !response.data || !response.data.details) {
        alert('Failed to fetch error log details: ' + (response?.data?.message || 'Unknown error'));
        return;
      }

      const details   = response.data.details;
      const formData  = details.submitted_data;

      // --- Normalize response_data (string | object | array | null) ---
      const parsed    = parseMaybeJson(details.response_data);
      const apiEntity = drillIntoData(parsed); // unwrap { data: ... } if present

      let content = `<h3>Log Details</h3>
        <table class="integrazo-wz-error-table">
          <tr><th>Integration Name</th><td>${esc(details.integration_name) || 'N/A'}</td></tr>
          <tr><th>Status</th><td>${esc(details.category) || 'N/A'}</td></tr>
          <tr><th>Message</th><td>${esc(details.message) || 'N/A'}</td></tr>
          <tr><th>Retry Count</th><td>${esc(details.retry_count) || 'N/A'}</td></tr>
          <tr><th>Created At</th><td>${esc(details.created_at) || 'N/A'}</td></tr>
          <tr><th>Updated At</th><td>${esc(details.updated_at) || 'N/A'}</td></tr>
        </table>`;

      // Captured (submitted) data
      content += `<h4>Captured Details</h4><table class="integrazo-wz-error-table">`;
      if (formData && typeof formData === 'object') {
        for (const [key, value] of Object.entries(formData)) {
          const displayValue = Array.isArray(value) ? value.join(', ') : value;
          content += `<tr><th>${esc(key)}</th><td>${esc(String(displayValue))}</td></tr>`;
        }
      } else {
        content += `<tr><td colspan="2">N/A</td></tr>`;
      }
      content += `</table>`;

      // API response
      content += `<h4>API Response</h4>`;
      if (apiEntity != null) {
        const displayVal = JSON.stringify(apiEntity, null, 2);
        content += `<pre class="integrazo-wz-json-pre">${esc(displayVal)}</pre>`;
      } else if (typeof details.response_data === 'string' && details.response_data.trim() !== '') {
        // show raw string if it wasn't valid JSON but non-empty
        content += `<pre class="integrazo-wz-json-pre">${esc(details.response_data)}</pre>`;
      } else {
        content += `<table class="integrazo-wz-error-table"><tr><td colspan="2">N/A</td></tr></table>`;
      }

      document.getElementById('integrazo-wz-error-content').innerHTML = content;
      const overlay = document.getElementById('integrazo-wz-error-overlay');
      overlay.style.visibility = 'visible';
      overlay.style.opacity = '1';
    },
    error: function (xhr, status, error) {
      console.error('AJAX error:', status, error);
      alert('An error occurred while fetching error log details.');
    }
  });
}

/** Safely parse JSON if it's a string; pass objects/arrays through; else null */
function parseMaybeJson(input) {
  if (input == null) return null;
  if (typeof input === 'object') return input; // already parsed (object or array)
  if (typeof input === 'string') {
    const s = input.trim();
    if (!s) return null;
    try { return JSON.parse(s); } catch (e) { console.warn('Bad JSON in response_data:', e); return null; }
  }
  return null;
}

/** Unwrap common shapes:
 *  - { data: ... }  -> return ...
 *  - array/object   -> return as-is
 *  - other/null     -> null
 */
function drillIntoData(obj) {
  if (obj == null) return null;
  // Prefer obj.data if present
  if (Object.prototype.hasOwnProperty.call(obj, 'data')) {
    const inner = obj.data;
    // Return inner as-is (object or array)
    return (inner !== undefined) ? inner : obj;
  }
  // If top-level is array/object, return as-is
  if (typeof obj === 'object') return obj;
  return null;
}

/** Minimal HTML escaper for safe rendering in the admin */
function esc(val) {
  if (val == null) return '';
  return String(val)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
}

function integrazo_wz_closeErrorOverlay() {
  const overlay = document.getElementById('integrazo-wz-error-overlay');
  if (overlay) {
    overlay.style.visibility = 'hidden';
    overlay.style.opacity = '0';
  }
}
