<!-- [DEF:GitDashboardPage:Component] -->
<script lang="ts">
  import { onMount } from 'svelte';
  import DashboardGrid from '../../components/DashboardGrid.svelte';
  import { addToast as toast } from '../../lib/toasts.js';
  import type { DashboardMetadata } from '../../types/dashboard';

  let environments: any[] = [];
  let selectedEnvId = "";
  let dashboards: DashboardMetadata[] = [];
  let loading = true;
  let fetchingDashboards = false;

  async function fetchEnvironments() {
    try {
      const response = await fetch('/api/environments');
      if (!response.ok) throw new Error('Failed to fetch environments');
      environments = await response.json();
      if (environments.length > 0) {
        selectedEnvId = environments[0].id;
      }
    } catch (e) {
      toast(e.message, 'error');
    } finally {
      loading = false;
    }
  }

  async function fetchDashboards(envId: string) {
    if (!envId) return;
    fetchingDashboards = true;
    try {
      const response = await fetch(`/api/environments/${envId}/dashboards`);
      if (!response.ok) throw new Error('Failed to fetch dashboards');
      dashboards = await response.json();
    } catch (e) {
      toast(e.message, 'error');
      dashboards = [];
    } finally {
      fetchingDashboards = false;
    }
  }

  onMount(fetchEnvironments);

  $: if (selectedEnvId) {
    fetchDashboards(selectedEnvId);
    localStorage.setItem('selected_env_id', selectedEnvId);
  }
</script>

<div class="max-w-6xl mx-auto p-6">
  <div class="flex justify-between items-center mb-6">
    <h1 class="text-2xl font-bold text-gray-800">Git Dashboard Management</h1>
    <div class="flex items-center space-x-4">
      <label for="env-select" class="text-sm font-medium text-gray-700">Environment:</label>
      <select
        id="env-select"
        bind:value={selectedEnvId}
        class="border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 p-2 border bg-white"
      >
        {#each environments as env}
          <option value={env.id}>{env.name}</option>
        {/each}
      </select>
    </div>
  </div>

  {#if loading}
    <div class="flex justify-center py-12">
      <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
    </div>
  {:else}
    <div class="bg-white rounded-lg shadow p-6">
      <h2 class="text-lg font-medium mb-4">Select Dashboard to Manage</h2>
      {#if fetchingDashboards}
        <p class="text-gray-500">Loading dashboards...</p>
      {:else if dashboards.length > 0}
        <DashboardGrid {dashboards} />
      {:else}
        <p class="text-gray-500 italic">No dashboards found in this environment.</p>
      {/if}
    </div>
  {/if}
</div>
<!-- [/DEF:GitDashboardPage:Component] -->