<!-- [DEF:GitDashboardPage:Component] -->
<!--
@PURPOSE:   Dashboard management page for Git integration.
@LAYER:     Page
@SEMANTICS: git, dashboard, management, ui
-->
<script lang="ts">
  import { onMount } from 'svelte';
  import RepositoryDashboardGrid from '../../components/RepositoryDashboardGrid.svelte';
  import { addToast as toast } from '../../lib/toasts.js';
  import { api } from '../../lib/api.js';
  import type { DashboardMetadata } from '../../types/dashboard';
  import { t } from '$lib/i18n';
  import { Button, Card, PageHeader, Select } from '$lib/ui';
  import {
    environmentContextStore,
    initializeEnvironmentContext,
    setSelectedEnvironment,
  } from '$lib/stores/environmentContext.js';

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

  // [DEF:fetchEnvironments:Function]
  // @PURPOSE: Fetches the list of deployment environments from the API.
  // @PRE: Component is mounted.
  // @POST: `environments` array is populated with data from /api/environments.
  async function fetchEnvironments() {
    try {
      await initializeEnvironmentContext();
      environments = $environmentContextStore?.environments || [];
      selectedEnvId = $environmentContextStore?.selectedEnvId || "";
    } catch (e) {
      toast(e.message, 'error');
    } finally {
      loading = false;
    }
  }
  // [/DEF:fetchEnvironments:Function]

  // [DEF:fetchDashboards:Function]
  // @PURPOSE: Fetches dashboards for a specific environment.
  // @PRE: `envId` is a valid environment ID.
  // @POST: `dashboards` array is updated with results from the environment.
  async function fetchDashboards(envId: string) {
    if (!envId) return;
    fetchingDashboards = true;
    try {
      const pageSize = 100;
      let page = 1;
      let aggregatedDashboards: DashboardMetadata[] = [];
      let totalPages = 1;

      while (page <= totalPages) {
        const response = await api.requestApi(
          `/dashboards?env_id=${encodeURIComponent(envId)}&page=${page}&page_size=${pageSize}`,
        );
        const pageDashboards = Array.isArray(response?.dashboards)
          ? response.dashboards
          : [];
        aggregatedDashboards = aggregatedDashboards.concat(pageDashboards);
        totalPages = Number(response?.total_pages || 1);
        page += 1;
      }

      dashboards = aggregatedDashboards;
    } catch (e) {
      toast(e.message, 'error');
      dashboards = [];
    } finally {
      fetchingDashboards = false;
    }
  }
  // [/DEF:fetchDashboards:Function]

  onMount(fetchEnvironments);

  $: environments = $environmentContextStore?.environments || [];
  $: if (
    $environmentContextStore?.selectedEnvId &&
    selectedEnvId !== $environmentContextStore.selectedEnvId
  ) {
    selectedEnvId = $environmentContextStore.selectedEnvId;
  }

  $: if (selectedEnvId) {
    fetchDashboards(selectedEnvId);
    setSelectedEnvironment(selectedEnvId);
  }
</script>

<div class="max-w-6xl mx-auto p-6">
  <PageHeader title={$t.git?.management }>
    <div slot="actions" class="flex items-center space-x-4">
      <Select
        label={$t.dashboard?.environment }
        bind:value={selectedEnvId}
        options={environments.map(e => ({ value: e.id, label: e.name }))}
      />
    </div>
  </PageHeader>

  {#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}
    <Card title={$t.git?.select_dashboard }>
      {#if fetchingDashboards}
        <p class="text-gray-500">{$t.common?.loading }</p>
      {:else if dashboards.length > 0}
        <RepositoryDashboardGrid {dashboards} statusMode="repository" />
      {:else}
        <p class="text-gray-500 italic">{$t.dashboard?.no_dashboards }</p>
      {/if}
    </Card>
  {/if}
</div>
<!-- [/DEF:GitDashboardPage:Component] -->
