<!-- #region MaintenanceEventsTable [C:3] [TYPE Component] [SEMANTICS maintenance, table, events, active, completed, remove] -->
<!-- @BRIEF Active/completed maintenance events table with removal actions. Uses inline table, skeleton rows, empty state, and status badges. -->
<!-- @LAYER Component -->
<!-- @RELATION DEPENDS_ON -> [MaintenanceStore] -->
<!-- @RELATION DEPENDS_ON -> [MaintenanceApi] -->
<!-- @UX_STATE idle -> Table rendered with events. -->
<!-- @UX_STATE removing -> One row shows spinner on its Remove button, other buttons disabled. -->
<!-- @UX_STATE removing_all -> All buttons disabled, "Remove All" shows spinner. -->
<!-- @UX_STATE empty -> No active events: dashed border placeholder. -->
<!-- @UX_STATE loading -> Skeleton rows displayed. -->
<!-- @UX_STATE error -> Toast shown on removal failure. -->
<!-- @UX_FEEDBACK Toast success/error on removal. -->
<!-- @UX_RECOVERY Retry via individual or bulk remove. -->
<!-- @UX_REACTIVITY Props -> $props(), LocalState -> $state(removingEventId, isRemovingAll) -->
<script lang="ts">
  import { maintenanceStore } from "$lib/stores/maintenance.svelte.js";
  import Button from "$lib/ui/Button.svelte";
  import { t } from "$lib/i18n/index.svelte.js";

  let removingEventId = $state(null);
  let isRemovingAll = $state(false);

  let isLoading = $derived(maintenanceStore.isLoading);
  let activeEvents = $derived(maintenanceStore.activeEvents);
  let completedEvents = $derived(maintenanceStore.completedEvents);

  /**
   * Get CSS class for status badge.
   * @param {string} status
   * @returns {string}
   */
  function statusBadgeClass(status) {
    switch ((status || "").toLowerCase()) {
      case "active":
      case "applying":
      case "pending":
        return "bg-green-100 text-green-700";
      case "completed":
        return "bg-blue-100 text-blue-700";
      case "failed":
      case "partial":
        return "bg-red-100 text-red-700";
      case "ending":
        return "bg-amber-100 text-amber-700";
      default:
        return "bg-gray-100 text-gray-700";
    }
  }

  /**
   * Handle removing a single event.
   * @param {object} event
   */
  async function handleRemove(event) {
    const confirmed = confirm($t.maintenance?.remove_event_confirm || "Remove banners for this event?");
    if (!confirmed) return;

    removingEventId = event.id;
    try {
      await maintenanceStore.endEvent(event.id);
    } catch {
      // Toast is handled by store
    } finally {
      removingEventId = null;
    }
  }

  /**
   * Handle removing all events.
   */
  async function handleRemoveAll() {
    const confirmed = confirm($t.maintenance?.remove_all_confirm || "Remove all active maintenance banners?");
    if (!confirmed) return;

    isRemovingAll = true;
    try {
      await maintenanceStore.endAllEvents();
    } catch {
      // Toast handled by store
    } finally {
      isRemovingAll = false;
    }
  }

  /**
   * Format a timestamp string for display.
   * @param {string} ts
   * @returns {string}
   */
  function formatTime(ts) {
    if (!ts) return "-";
    try {
      const d = new Date(ts);
      if (isNaN(d.getTime())) return ts;
      return d.toLocaleString();
    } catch {
      return ts;
    }
  }
</script>

<div class="space-y-6">
  <!-- Active Events -->
  <div>
    <div class="flex items-center justify-between mb-3">
      <h3 class="text-lg font-semibold text-gray-900">
        {$t.maintenance?.active_events || "Active Events"}
      </h3>

      {#if activeEvents.length > 0}
        <Button
          variant="danger"
          size="sm"
          onclick={handleRemoveAll}
          isLoading={isRemovingAll}
          disabled={isRemovingAll}
        >
          {$t.maintenance?.remove_all || "Remove All"}
        </Button>
      {/if}
    </div>

    {#if isLoading && activeEvents.length === 0}
      <!-- Skeleton -->
      <div class="border border-gray-200 rounded-lg overflow-hidden">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tables</th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Dashboards</th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Start</th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">End</th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            {#each [1, 2, 3] as _, i (i)}
              <tr>
                <td class="px-4 py-3"><div class="animate-pulse bg-gray-200 h-4 w-24 rounded"></div></td>
                <td class="px-4 py-3"><div class="animate-pulse bg-gray-200 h-4 w-32 rounded"></div></td>
                <td class="px-4 py-3"><div class="animate-pulse bg-gray-200 h-4 w-16 rounded"></div></td>
                <td class="px-4 py-3"><div class="animate-pulse bg-gray-200 h-4 w-28 rounded"></div></td>
                <td class="px-4 py-3"><div class="animate-pulse bg-gray-200 h-4 w-28 rounded"></div></td>
                <td class="px-4 py-3"><div class="animate-pulse bg-gray-200 h-6 w-16 rounded-full"></div></td>
                <td class="px-4 py-3"><div class="animate-pulse bg-gray-200 h-8 w-24 rounded"></div></td>
              </tr>
            {/each}
          </tbody>
        </table>
      </div>
    {:else if activeEvents.length === 0}
      <!-- Empty state -->
      <div class="border-dashed border-2 border-gray-300 bg-gray-50 p-8 text-center rounded-lg">
        <p class="text-sm text-gray-500">
          {$t.maintenance?.no_active_events || "No active maintenance events"}
        </p>
      </div>
    {:else}
      <!-- Events table -->
      <div class="border border-gray-200 rounded-lg overflow-hidden">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                {$t.maintenance?.event_id || "Event ID"}
              </th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                {$t.maintenance?.tables || "Tables"}
              </th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                {$t.maintenance?.affected_dashboards || "Dashboards"}
              </th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                {$t.maintenance?.start_time || "Start Time"}
              </th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                {$t.maintenance?.end_time || "End Time"}
              </th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                {$t.maintenance?.status || "Status"}
              </th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                {$t.maintenance?.actions || "Actions"}
              </th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            {#each activeEvents as event (event.id)}
              <tr class="hover:bg-gray-50">
                <td class="px-4 py-3 text-sm text-gray-900 font-mono text-xs" title={event.id}>
                  {event.id?.length > 16 ? event.id.slice(0, 16) + "…" : event.id}
                </td>
                <td class="px-4 py-3 text-sm text-gray-600 max-w-[200px] truncate" title={(event.tables || []).join(", ")}>
                  {(event.tables || []).join(", ") || "-"}
                </td>
                <td class="px-4 py-3 text-sm text-gray-900">
                  {event.affected_count ?? "-"}
                </td>
                <td class="px-4 py-3 text-sm text-gray-600">
                  {formatTime(event.start_time)}
                </td>
                <td class="px-4 py-3 text-sm text-gray-600">
                  {formatTime(event.end_time)}
                </td>
                <td class="px-4 py-3">
                  <span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium {statusBadgeClass(event.status)}">
                    {event.status}
                  </span>
                </td>
                <td class="px-4 py-3">
                  <Button
                    variant="danger"
                    size="sm"
                    onclick={() => handleRemove(event)}
                    isLoading={removingEventId === event.id}
                    disabled={isRemovingAll || removingEventId !== null}
                  >
                    {$t.maintenance?.remove_banners || "Remove"}
                  </Button>
                </td>
              </tr>
            {/each}
          </tbody>
        </table>
      </div>
    {/if}
  </div>

  <!-- Completed Events (collapsible) -->
  {#if completedEvents.length > 0}
    <details class="rounded-lg border border-gray-200 bg-white">
      <summary class="cursor-pointer px-4 py-3 text-sm font-semibold text-gray-900 hover:bg-gray-50 rounded-lg">
        {$t.maintenance?.completed_events || "Completed Events"} ({completedEvents.length})
      </summary>

      <div class="px-4 pb-4">
        <div class="border border-gray-200 rounded-lg overflow-hidden">
          <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
              <tr>
                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tables</th>
                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Dashboards</th>
                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Start</th>
                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">End</th>
                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
              </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
              {#each completedEvents as event (event.id)}
                <tr class="hover:bg-gray-50">
                  <td class="px-4 py-3 text-sm text-gray-900 font-mono text-xs" title={event.id}>
                    {event.id?.length > 16 ? event.id.slice(0, 16) + "…" : event.id}
                  </td>
                  <td class="px-4 py-3 text-sm text-gray-600 max-w-[200px] truncate" title={(event.tables || []).join(", ")}>
                    {(event.tables || []).join(", ") || "-"}
                  </td>
                  <td class="px-4 py-3 text-sm text-gray-900">
                    {event.affected_count ?? "-"}
                  </td>
                  <td class="px-4 py-3 text-sm text-gray-600">
                    {formatTime(event.start_time)}
                  </td>
                  <td class="px-4 py-3 text-sm text-gray-600">
                    {formatTime(event.end_time)}
                  </td>
                  <td class="px-4 py-3">
                    <span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium {statusBadgeClass(event.status)}">
                      {event.status}
                    </span>
                  </td>
                </tr>
              {/each}
            </tbody>
          </table>
        </div>
      </div>
    </details>
  {/if}
</div>
<!-- #endregion MaintenanceEventsTable -->
