<!-- #region GitDashboardPage [C:3] [TYPE Page] [SEMANTICS sveltekit, git, dashboard, environment, repository] -->
<!-- @BRIEF Git integration page for selecting environments and managing dashboard repositories. -->
<!-- @LAYER Page -->
<!-- @RELATION DEPENDS_ON -> [EXT:frontend:RepositoryDashboardGrid] -->
<!-- @RELATION BINDS_TO -> [EXT:frontend:environmentContextStore] -->
<!-- @UX_STATE Loading -> Environment and dashboard data are being resolved. -->
<!-- @UX_STATE Ready -> Git dashboard grid and environment selector are interactive. -->
<!-- @UX_STATE Refreshing -> Changing environment refreshes dashboard data while preserving page context. -->
<!-- @UX_STATE Error -> Toast-driven failure feedback preserves filter selection. -->
<!-- @UX_FEEDBACK Toast notifications on API errors. -->
<!-- @UX_RECOVERY User can retry by changing environment or refreshing. -->
<script lang="ts">
  import { onMount } from 'svelte';
  import RepositoryDashboardGrid from '../../components/RepositoryDashboardGrid.svelte';
  import { addToast as toast } from '$lib/toasts.svelte.js';
  import { api } from '../../lib/api.js';
  import type { DashboardMetadata } from '../../types/dashboard';
  import { t } from '$lib/i18n/index.svelte.js';
  import { Button, Card, PageHeader, Select } from '$lib/ui';
  import {
    environmentContextStore,
    initializeEnvironmentContext,
    setSelectedEnvironment,
  } from '$lib/stores/environmentContext.svelte.js';

  let selectedEnvId = $state("");
  let dashboards: DashboardMetadata[] = $state([]);
  let loading = $state(true);
  let fetchingDashboards = $state(false);
  let environments = $derived(
    environmentContextStore.value?.environments || [],
  );

  async function fetchEnvironments() {
    try {
      await initializeEnvironmentContext();
      selectedEnvId = environmentContextStore.value?.selectedEnvId || "";
    } catch (e) {
      toast(e.message, 'error');
    } finally {
      loading = false;
    }
  }

  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;
    }
  }

  onMount(fetchEnvironments);

  $effect(() => {
    const storeSelectedEnvId = environmentContextStore.value?.selectedEnvId || "";
    if (storeSelectedEnvId && selectedEnvId !== storeSelectedEnvId) {
      selectedEnvId = storeSelectedEnvId;
    }
  });

  $effect(() => {
    if (!selectedEnvId) return;
    setSelectedEnvironment(selectedEnvId);
    void fetchDashboards(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>
<!-- #endregion GitDashboardPage -->
