<script>
  import { onMount } from "svelte";
  import { get, post } from "../lib/api.js";

  let containers = $state([]);
  let loading = $state(true);
  let error = $state("");
  let logTarget = $state("");
  let logContent = $state("");
  let loadingLogs = $state(false);
  let actionLoading = $state("");

  async function load() {
    loading = true;
    error = "";
    try {
      containers = (await get("/docker/containers")) || [];
    } catch (e) {
      error = e.message || "Docker API unavailable";
      containers = [];
    }
    loading = false;
  }

  async function action(id, act) {
    actionLoading = id + act;
    try {
      await post(`/docker/containers/${id}/${act}`);
      await load();
    } catch (e) {
      error = e.message || "Action failed";
    }
    actionLoading = "";
  }

  async function showLogs(id, name) {
    logTarget = name;
    loadingLogs = true;
    try {
      const r = await get(`/docker/containers/${id}/logs?tail=200`);
      logContent = r?.logs || "No logs available";
    } catch (e) {
      logContent = "Failed to load logs";
    }
    loadingLogs = false;
  }

  onMount(load);
</script>

<div class="space-y-6">
  <div class="flex items-center justify-between">
    <div>
      <h1 class="text-2xl font-bold text-surface-900 dark:text-white tracking-tight">Docker</h1>
      <p class="text-sm text-surface-400 mt-1">{containers.length} containers · {containers.filter(c => c.status === "running").length} running</p>
    </div>
    <button onclick={load} class="text-xs font-medium text-primary-600 bg-primary-50 hover:bg-primary-100 px-3 py-1.5 rounded-lg transition-colors">
      Refresh
    </button>
  </div>

  {#if loading}
    <div class="space-y-3">
      {#each Array(5) as _}
        <div class="h-[72px] rounded-xl bg-surface-100 dark:bg-surface-800 animate-pulse"></div>
      {/each}
    </div>
  {:else if error}
    <div class="bg-rose-50 dark:bg-rose-900/20 border border-rose-200 dark:border-rose-800 rounded-xl p-4">
      <div class="flex items-center justify-between">
        <div class="flex items-center gap-2">
          <svg class="w-5 h-5 text-rose-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z" /></svg>
          <p class="text-sm font-medium text-rose-700 dark:text-rose-300">{error}</p>
        </div>
        <button onclick={load} class="text-xs font-medium text-rose-600 bg-rose-100 hover:bg-rose-200 px-3 py-1.5 rounded-lg transition-colors">
          Retry
        </button>
      </div>
    </div>
  {:else}
    <div class="space-y-2">
      {#each containers as c}
        <div class="bg-white dark:bg-surface-800 rounded-xl border border-surface-200 dark:border-surface-700 p-4 flex items-center justify-between shadow-sm hover:shadow-md transition-all duration-200 group">
          <div class="flex items-center gap-3 min-w-0">
            <span class="relative flex h-2.5 w-2.5 shrink-0">
              {#if c.status === "running"}
                <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
                <span class="relative inline-flex rounded-full h-2.5 w-2.5 bg-emerald-500"></span>
              {:else}
                <span class="relative inline-flex rounded-full h-2.5 w-2.5 bg-surface-300"></span>
              {/if}
            </span>
            <div class="min-w-0">
              <p class="text-sm font-semibold text-surface-800 dark:text-surface-100 truncate">{c.name}</p>
              <p class="text-xs text-surface-400 truncate mt-0.5">{c.image}</p>
            </div>
          </div>
          <div class="flex items-center gap-1.5 opacity-70 group-hover:opacity-100 transition-opacity">
            {#if c.status === "running"}
              <button
                class="text-xs font-medium px-2.5 py-1.5 rounded-lg text-rose-600 bg-rose-50 hover:bg-rose-100 transition-colors disabled:opacity-50"
                onclick={() => action(c.id, "stop")}
                disabled={actionLoading === c.id + "stop"}
              >
                {actionLoading === c.id + "stop" ? "..." : "Stop"}
              </button>
              <button
                class="text-xs font-medium px-2.5 py-1.5 rounded-lg text-amber-600 bg-amber-50 hover:bg-amber-100 transition-colors disabled:opacity-50"
                onclick={() => action(c.id, "restart")}
                disabled={actionLoading === c.id + "restart"}
              >
                {actionLoading === c.id + "restart" ? "..." : "Restart"}
              </button>
            {:else}
              <button
                class="text-xs font-medium px-2.5 py-1.5 rounded-lg text-emerald-600 bg-emerald-50 hover:bg-emerald-100 transition-colors disabled:opacity-50"
                onclick={() => action(c.id, "start")}
                disabled={actionLoading === c.id + "start"}
              >
                {actionLoading === c.id + "start" ? "..." : "Start"}
              </button>
            {/if}
            <button
              class="text-xs font-medium px-2.5 py-1.5 rounded-lg text-surface-600 bg-surface-100 hover:bg-surface-200 transition-colors"
              onclick={() => showLogs(c.id, c.name)}
            >
              Logs
            </button>
          </div>
        </div>
      {/each}
    </div>
  {/if}

  <!-- Log Modal -->
  {#if logTarget}
    <div class="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center z-50" role="dialog" aria-modal="true" onclick={() => { logTarget = ""; logContent = ""; }} onkeydown={(e) => e.key === "Escape" && (logTarget = "", logContent = "")}>
      <div class="bg-white dark:bg-surface-800 rounded-2xl shadow-2xl w-[90vw] max-w-4xl max-h-[80vh] flex flex-col" role="document" onclick={(e) => e.stopPropagation()} onkeydown={(e) => e.stopPropagation()}>
        <div class="flex items-center justify-between px-5 py-4 border-b border-surface-200 dark:border-surface-700">
          <div>
            <h3 class="text-sm font-bold text-surface-800 dark:text-surface-100">Container Logs</h3>
            <p class="text-xs text-surface-400 mt-0.5">{logTarget}</p>
          </div>
          <button aria-label="Close logs" class="text-surface-400 hover:text-surface-600 transition-colors" onclick={() => { logTarget = ""; logContent = ""; }}>
            <svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" /></svg>
          </button>
        </div>
        <div class="flex-1 overflow-auto p-1">
          {#if loadingLogs}
            <div class="flex items-center justify-center h-40">
              <div class="w-6 h-6 border-2 border-primary-500 border-t-transparent rounded-full animate-spin"></div>
            </div>
          {:else}
            <pre class="bg-surface-900 text-emerald-400 text-xs p-4 rounded-xl whitespace-pre-wrap leading-relaxed font-mono min-h-[200px]">{logContent}</pre>
          {/if}
        </div>
      </div>
    </div>
  {/if}
</div>
