{{ extends "../layout" }}

{{ block documentBody() }}
<article class="processes-info">
  <header>
    <h2 class="title">System Processes</h2>
    <p class="description text-muted">Overview of running processes with CPU and memory usage</p>
  </header>

  <div class="grid" style="display: grid; grid-template-columns: 1fr; gap: 1rem;">
    <div>
      <article class="processes-table">
        <header>
          <h3 id="processes-title">Running Processes</h3>
          <p class="refresh-status">
            <button class="btn btn-sm" onclick="refreshProcesses()">
              Refresh
              <span class="loading-indicator" id="refresh-loading" style="display: none;">&nbsp;Loading...</span>
            </button>
          </p>
        </header>

        <div class="processes-table-content" up-poll="/admin/system/processes-data" up-hungry="true" up-interval="10000" style="display: block; width: 100%;" id="processes-content">
          {{ if isset(., "error") }}
            <div class="alert alert-danger">{{ .error }}</div>
          {{ end }}

          <table class="table table-striped" id="processes-stats">
            <thead>
              <tr>
                <th scope="col">PID</th>
                <th scope="col">Name</th>
                <th scope="col">Status</th>
                <th scope="col">CPU (%)</th>
                <th scope="col">Memory (MB)</th>
                <th scope="col">Created</th>
              </tr>
            </thead>
            <tbody>
              {{ if isset(., "processes") && len(.processes) > 0 }}
                {{ range .processes }}
                <tr class="{{ if .is_current }}table-primary{{ end }}">
                  <td>{{ .pid }}</td>
                  <td>{{ .name }}</td>
                  <td>{{ .status }}</td>
                  <td>{{ .cpu_percent_str }}</td>
                  <td>{{ .memory_mb_str }}</td>
                  <td>{{ .create_time_str }}</td>
                </tr>
                {{ end }}
              {{ else }}
                <tr>
                  <td colspan="6">No process data available.</td>
                </tr>
              {{ end }}
            </tbody>
          </table>
        </div>
      </article>
    </div>
  </div>
</article>

<script>
  // Ensure processes data is loaded on page load
  document.addEventListener('DOMContentLoaded', function() {
    // Check if the processes content is empty or shows 'No process data available'
    const processesContent = document.getElementById('processes-content');
    const tableBody = processesContent ? processesContent.querySelector('tbody') : null;
    
    if (tableBody && (tableBody.innerText.includes('No process data available') || tableBody.children.length <= 1)) {
      console.log('Triggering initial process data load');
      refreshProcesses();
    }
  });
</script>
{{ end }}