{% extends "base.html" %}
{% import "macros/ui.html" as m %}
{% block title %}{{ ws_name }} · {{ comp_name }}{% endblock %}
{% block nav_workspaces %}btn-active{% endblock %}

{% block content %}
{{ m::ws_tabs(ws_name=ws_name, active=ws_active_tab, ws_envs=ws_envs, ws_has_clusters=ws_has_clusters, ws_has_workflows=ws_has_workflows, current_env=current_env) }}

{% if component %}
<div class="max-w-3xl space-y-5">

  <div class="flex items-center gap-3">
    <h2 class="font-mono font-bold text-primary text-xl">{{ component.name }}</h2>
    {% if component.mode == "taskserv" %}
      <span class="badge badge-outline badge-sm">taskserv</span>
    {% elif component.mode == "cluster" %}
      <span class="badge badge-info badge-sm">cluster</span>
    {% endif %}
  </div>

  {% if component.ext_description %}
  <p class="text-sm text-base-content/60">{{ component.ext_description }}</p>
  {% endif %}

  {# Definition #}
  <div class="card bg-base-200 shadow">
    <div class="card-body p-4">
      <h3 class="font-mono text-xs text-base-content/40 uppercase tracking-wider mb-3">Definition</h3>
      <div class="font-mono text-sm space-y-1.5">
        <div class="flex gap-4">
          <span class="text-base-content/40 w-24 shrink-0">mode</span>
          <span>{% if component.mode %}{{ component.mode }}{% else %}—{% endif %}</span>
        </div>
        <div class="flex gap-4">
          <span class="text-base-content/40 w-24 shrink-0">target</span>
          <span>{% if component.target %}{{ component.target }}{% else %}—{% endif %}</span>
        </div>
        <div class="flex gap-4">
          <span class="text-base-content/40 w-24 shrink-0">namespace</span>
          <span>{% if component.namespace %}{{ component.namespace }}{% else %}—{% endif %}</span>
        </div>
        <div class="flex gap-4">
          <span class="text-base-content/40 w-24 shrink-0">version</span>
          <span>{% if component.version %}{{ component.version }}{% else %}—{% endif %}</span>
        </div>
        {% if component.operations %}
        <div class="flex gap-4">
          <span class="text-base-content/40 w-24 shrink-0">operations</span>
          <div class="flex flex-wrap gap-1">
            {% for op in component.operations %}
            <span class="badge badge-ghost badge-xs font-mono">{{ op }}</span>
            {% endfor %}
          </div>
        </div>
        {% endif %}
      </div>
    </div>
  </div>

  {# Extension capabilities #}
  {% if component.ext_provides or component.ext_requires or component.ext_conflicts %}
  <div class="card bg-base-200 shadow">
    <div class="card-body p-4 space-y-3">
      <h3 class="font-mono text-xs text-base-content/40 uppercase tracking-wider">Extension Capabilities</h3>
      {% if component.ext_provides %}
      <div>
        <p class="text-xs text-base-content/40 mb-1">Provides</p>
        <div class="flex flex-wrap gap-1">
          {% for cap in component.ext_provides %}<span class="badge badge-success badge-xs font-mono">{{ cap }}</span>{% endfor %}
        </div>
      </div>
      {% endif %}
      {% if component.ext_requires %}
      <div>
        <p class="text-xs text-base-content/40 mb-1">Requires</p>
        <div class="flex flex-wrap gap-1">
          {% for cap in component.ext_requires %}<span class="badge badge-warning badge-xs font-mono">{{ cap }}</span>{% endfor %}
        </div>
      </div>
      {% endif %}
      {% if component.ext_conflicts %}
      <div>
        <p class="text-xs text-base-content/40 mb-1">Conflicts With</p>
        <div class="flex flex-wrap gap-1">
          {% for cap in component.ext_conflicts %}<span class="badge badge-error badge-xs font-mono">{{ cap }}</span>{% endfor %}
        </div>
      </div>
      {% endif %}
    </div>
  </div>
  {% endif %}

  {# Live pod status — all modes that have pods (cluster namespace or name-based match) #}
  <div class="card bg-base-200 shadow" id="live-card">
    <div class="card-body p-4">
      <div class="flex items-center gap-2 mb-3">
        <h3 class="font-mono text-xs text-base-content/40 uppercase tracking-wider flex-1">Live Pods</h3>
        <button id="live-btn" onclick="loadPods()" class="btn btn-ghost btn-xs gap-1 font-mono text-base-content/40 hover:text-base-content">
          <span id="live-spin" class="loading loading-spinner loading-xs hidden"></span>
          <svg id="live-icon" class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
              d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
          </svg>
          ↺ live
        </button>
      </div>
      <div id="pods-container" class="font-mono text-xs text-base-content/40 italic">Click ↺ live to fetch pod status.</div>
    </div>
  </div>

  {# Describe output panel — shown when a pod's describe is loaded #}
  <div id="describe-panel" class="card bg-base-300 shadow hidden">
    <div class="card-body p-4">
      <div class="flex items-center gap-2 mb-2">
        <h3 class="font-mono text-xs text-base-content/40 uppercase tracking-wider flex-1">
          kubectl describe pod — <span id="describe-title" class="text-base-content/70"></span>
        </h3>
        <button onclick="copyDescribe()" class="btn btn-ghost btn-xs font-mono gap-1" title="Copy to clipboard">
          <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
              d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3"/>
          </svg>
          <span id="copy-label">copy</span>
        </button>
        <button onclick="closeDescribe()" class="btn btn-ghost btn-xs opacity-50">✕</button>
      </div>
      <pre id="describe-output" class="text-xs leading-relaxed overflow-x-auto whitespace-pre bg-base-100 rounded p-3 max-h-[28rem]"></pre>
    </div>
  </div>

  <script>
  const WS_NAME   = {{ ws_name | json_encode() | safe }};
  const COMP_NAME = {{ comp_name | json_encode() | safe }};
  const PODS_URL  = `/ui/workspaces/${WS_NAME}/components/${COMP_NAME}/pods`;

  function phaseClass(phase) {
    if (phase === 'Running')   return 'badge-success';
    if (phase === 'Pending')   return 'badge-warning';
    if (phase === 'Failed')    return 'badge-error';
    return 'badge-ghost';
  }

  async function loadPods() {
    const spin = document.getElementById('live-spin');
    const icon = document.getElementById('live-icon');
    const cont = document.getElementById('pods-container');
    spin.classList.remove('hidden'); icon.classList.add('hidden');
    try {
      const r = await fetch(PODS_URL);
      const data = await r.json();
      if (data.error) { cont.innerHTML = `<span class="text-error">${data.error}</span>`; return; }
      const items = data.items || [];
      if (items.length === 0) {
        cont.innerHTML = `<span class="text-base-content/40">No pods found in namespace <code>${data.namespace || '—'}</code>.</span>`;
        return;
      }
      cont.innerHTML = `
        <table class="table table-xs w-full">
          <thead><tr class="text-base-content/30 uppercase text-[10px]">
            <th>Pod</th><th>Ready</th><th>Phase</th><th>Restarts</th><th class="w-8"></th>
          </tr></thead>
          <tbody>${items.map(p => `
            <tr class="hover" id="row-${CSS.escape(p.name)}">
              <td class="font-mono text-xs truncate max-w-[18rem]" title="${p.name}">${p.name}</td>
              <td><span class="badge badge-xs font-mono ${phaseClass(p.phase)}">${p.ready}</span></td>
              <td><span class="badge badge-xs ${phaseClass(p.phase)}">${p.phase}</span></td>
              <td class="text-base-content/50">${p.restarts}</td>
              <td>
                <button onclick="loadDescribe('${p.namespace}','${p.name}')"
                  class="btn btn-ghost btn-xs font-mono opacity-50 hover:opacity-100" title="kubectl describe">▶</button>
              </td>
            </tr>`).join('')}
          </tbody>
        </table>`;
    } catch(e) {
      cont.innerHTML = `<span class="text-error">fetch failed: ${e}</span>`;
    } finally {
      spin.classList.add('hidden'); icon.classList.remove('hidden');
    }
  }

  async function loadDescribe(ns, pod) {
    const panel  = document.getElementById('describe-panel');
    const output = document.getElementById('describe-output');
    const title  = document.getElementById('describe-title');
    panel.classList.remove('hidden');
    title.textContent = `${ns}/${pod}`;
    output.textContent = 'Loading…';
    try {
      const r = await fetch(`${PODS_URL}/${ns}/${pod}/describe`);
      const data = await r.json();
      output.textContent = data.output || data.error || '(empty)';
    } catch(e) {
      output.textContent = `fetch failed: ${e}`;
    }
    panel.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
  }

  function closeDescribe() {
    document.getElementById('describe-panel').classList.add('hidden');
  }

  async function copyDescribe() {
    const text = document.getElementById('describe-output').textContent;
    const label = document.getElementById('copy-label');
    try {
      await navigator.clipboard.writeText(text);
      label.textContent = 'copied!';
      setTimeout(() => label.textContent = 'copy', 1500);
    } catch { label.textContent = 'failed'; }
  }
  </script>

  {# DAG execution #}
  {% if dag_entries %}
  <div class="card bg-base-200 shadow">
    <div class="card-body p-4">
      <h3 class="font-mono text-xs text-base-content/40 uppercase tracking-wider mb-3">DAG Execution — {{ dag_entries | length }} entries</h3>
      <div class="space-y-2 font-mono text-xs">
        {% for entry in dag_entries %}
        <div class="flex items-start gap-3 p-2 rounded bg-base-300">
          <div class="flex-1 space-y-0.5">
            <div class="flex gap-3">
              <span class="text-base-content/40">formula</span>
              <span class="text-primary">{{ entry.formula }}</span>
              {% if entry.server %}
              <span class="text-base-content/40">server</span>
              <span>{{ entry.server }}</span>
              {% endif %}
            </div>
            <div class="flex gap-3 text-base-content/50">
              <span>state: <span class="{% if entry.state == 'completed' %}text-success{% elif entry.state == 'failed' %}text-error{% elif entry.state == 'running' %}text-warning{% endif %}">{{ entry.state }}</span></span>
              {% if entry.started %}<span>started: {{ entry.started }}</span>{% endif %}
              {% if entry.ended %}<span>ended: {{ entry.ended }}</span>{% endif %}
            </div>
          </div>
        </div>
        {% endfor %}
      </div>
    </div>
  </div>
  {% endif %}

</div>
{% else %}
<div class="alert alert-warning">
  <span>Component <code class="font-mono">{{ comp_name }}</code> not found in <code class="font-mono">{{ ws_name }}</code>.</span>
</div>
{% endif %}

<div class="mt-6">
  <a href="/ui/workspaces/{{ ws_name }}/components" class="btn btn-sm btn-ghost">← Back to Components</a>
</div>
{% endblock %}
