<template>
  <div v-if="!statsStore.state.loading && !statsStore.state.error" class="build-stats">
    <StatsListSection title="Stats">
      <StatItem
        v-for="(stat, key) in generalStats"
        :key="key"
        :color="stat.color"
        :count="stat.count"
        :title="key" />
    </StatsListSection>

    <StatsListSection v-if="showLto" title="LTO">
      <StatItem
        v-for="(stat, key) in ltoStats"
        :key="key"
        :color="stat.color"
        :count="stat.count"
        :title="key" />
    </StatsListSection>
  </div>
  <div v-else-if="statsStore.state.loading" class="build-stats build-stats--loading">
    <v-progress-circular color="primary" indeterminate size="20" />
    <span class="loading-text">Loading stats...</span>
  </div>
  <div v-else-if="statsStore.state.error" class="build-stats build-stats--error">
    <v-icon icon="mdi-alert-circle" size="18" />
    <span class="error-text">Error loading stats</span>
  </div>
</template>

<script lang="ts" setup>
import { computed } from 'vue'
import { useStatsStore } from '@/stores/statsStore'
import StatsListSection from '@/components/MainNav/BuildStats/StatsListSection.vue'
import StatItem from '@/components/MainNav/BuildStats/StatItem.vue'

interface Props {
  showLto?: boolean
}

withDefaults(defineProps<Props>(), {
  showLto: true
})

const statsStore = useStatsStore()

const generalStats = computed(() => ({
  latest: {
    count: statsStore.state.stats?.latest || 0,
    color: 'var(--color-status-success)'
  },
  queued: {
    count: statsStore.state.stats?.queued || 0,
    color: 'var(--color-status-warning)'
  },
  building: {
    count: statsStore.state.stats?.building || 0,
    color: 'var(--color-status-info)'
  },
  skipped: {
    count: statsStore.state.stats?.skipped || 0,
    color: 'var(--color-status-neutral)'
  },
  failed: {
    count: statsStore.state.stats?.failed || 0,
    color: 'var(--color-status-error)'
  }
}))

const ltoStats = computed(() => ({
  enabled: {
    count: statsStore.state.stats?.lto?.enabled || 0,
    color: 'var(--color-status-success)'
  },
  disabled: {
    count: statsStore.state.stats?.lto?.disabled || 0,
    color: 'var(--color-status-error)'
  },
  unknown: {
    count: statsStore.state.stats?.lto?.unknown || 0,
    color: 'var(--color-status-neutral)'
  }
}))
</script>

<style scoped>
.build-stats {
  display: flex;
  align-items: center;
  gap: var(--space-8);
}

.build-stats--loading,
.build-stats--error {
  gap: var(--space-2);
}

.loading-text {
  font-size: var(--font-size-sm);
  color: var(--color-text-muted);
}

.build-stats--error {
  color: var(--color-status-error);
}

.error-text {
  font-size: var(--font-size-sm);
}

@media (max-width: 1200px) {
  .build-stats {
    gap: var(--space-6);
  }
}
</style>
