<template>
  <div class="currently-building">
    <div class="status-header">
      <div class="status-indicator">
        <div
          :class="[
            'pulse-dot',
            updateFailed
              ? 'pulse-dot--error'
              : buildingPackages.length > 0
                ? 'pulse-dot--building'
                : 'pulse-dot--idle'
          ]" />
        <span class="status-text">
          {{
            updateFailed
              ? 'Could not fetch data'
              : buildingPackages.length > 0
                ? 'Building'
                : 'Idle'
          }}
        </span>
      </div>

      <div v-if="buildingPackages.length > 0" class="progress-section">
        <v-progress-linear
          :max="builtPackages.length + buildingPackages.length + queuedPackages.length"
          :model-value="builtPackages.length"
          class="build-progress"
          color="primary"
          height="8"
          rounded
          striped />
        <span class="progress-label">
          {{ builtPackages.length }} / {{ builtPackages.length + buildingPackages.length + queuedPackages.length }}
        </span>
      </div>

      <div class="timestamps">
        <template v-if="!updateFailed">
          <div class="timestamp-item">
            <v-icon icon="mdi-refresh" size="14" class="timestamp-icon" />
            <span>{{ formatTimeAgo(lastUpdatedSeconds) }}</span>
            <v-tooltip activator="parent" location="start">
              Last updated:
              {{ unixTimestampToLocalizedDate(Math.floor((packagesStore.state.lastUpdated || Date.now()) / 1000)) }}
            </v-tooltip>
          </div>
          <div class="timestamp-item">
            <v-icon icon="mdi-sync" size="14" class="timestamp-icon" />
            <span>{{ formatTimeAgo(lastMirrorSync) }}</span>
            <v-tooltip activator="parent" location="start">
              Last mirror sync:
              {{ unixTimestampToLocalizedDate(statsStore.state.stats?.last_mirror_timestamp || Math.floor(Date.now() / 1000)) }}
            </v-tooltip>
          </div>
        </template>
        <span v-else class="error-message">Please try again later.</span>
      </div>
    </div>

    <div v-if="buildingPackages.length > 0 || queuedPackages.length > 0" class="build-content">
      <div v-if="buildingPackages.length > 0" class="building-section">
        <h4 class="section-title">
          <v-icon icon="mdi-hammer" size="18" class="section-icon" />
          Currently Building
        </h4>
        <div class="package-list">
          <div
            v-for="pkg in buildingPackages"
            :key="`${pkg.pkgbase}-${pkg.repo}`"
            class="building-item">
            <div class="pulse-dot pulse-dot--building pulse-dot--sm" />
            <div class="package-info">
              <span class="package-name">{{ pkg.pkgbase }}</span>
              <span class="package-repo">{{ pkg.repo }}</span>
            </div>
            <code class="package-version">{{ pkg.arch_version }}</code>
          </div>
        </div>
      </div>

      <div v-if="queuedPackages.length > 0" class="queued-section">
        <h4 class="section-title">
          <v-icon icon="mdi-playlist-play" size="18" class="section-icon" />
          Queued
          <span class="queue-count">{{ queuedPackages.length }}</span>
        </h4>
        <queued-packages-list :packages="queuedPackages" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted } from 'vue'
import QueuedPackagesList from '@/components/CurrentlyBuilding/QueuedPackagesList.vue'
import { usePackagesStore, useStatsStore } from '@/stores'
import { useNowTimer } from '@/composables/useAutoRefresh'
import { unixTimestampToLocalizedDate, useRelativeTime } from '@/composables/useDateFormat'

const statsStore = useStatsStore()
const packagesStore = usePackagesStore()

const { formatTimeAgo } = useRelativeTime()
const { now, start: startTimer } = useNowTimer()

const updateFailed = computed(
  () => !!packagesStore.state.errorCurrentlyBuilding || !!statsStore.state.error
)
const lastUpdatedSeconds = computed(
  () => now.value - Math.floor((packagesStore.state.lastUpdated || Date.now()) / 1000)
)
const lastMirrorSync = computed(
  () => now.value - (statsStore.state.stats?.last_mirror_timestamp || Math.floor(Date.now() / 1000))
)

const buildingPackages = computed(
  () =>
    packagesStore.state.currentlyBuildingPackages.filter((pkg) => pkg.status === 'building') || []
)
const queuedPackages = computed(
  () =>
    packagesStore.state.currentlyBuildingPackages.filter((pkg) => pkg.status === 'queued') || []
)
const builtPackages = computed(
  () =>
    packagesStore.state.currentlyBuildingPackages.filter((pkg) => pkg.status === 'built') || []
)

onMounted(() => {
  startTimer()
})
</script>

<style scoped>
.currently-building {
  background: var(--color-bg-secondary);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-lg);
  overflow: hidden;
  margin-bottom: var(--space-4);
}

.status-header {
  display: flex;
  align-items: center;
  gap: var(--space-4);
  padding: var(--space-4);
  border-bottom: 1px solid var(--color-border-subtle);
  flex-wrap: wrap;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: var(--space-2);
  min-width: 100px;
}

.status-text {
  font-weight: var(--font-weight-semibold);
  color: var(--color-text-primary);
  white-space: nowrap;
}

.progress-section {
  flex: 1;
  display: flex;
  align-items: center;
  gap: var(--space-3);
  min-width: 200px;
}

.build-progress {
  flex: 1;
  border-radius: var(--radius-full);
}

.progress-label {
  font-size: var(--font-size-xs);
  color: var(--color-text-muted);
  font-family: var(--font-family-mono);
  white-space: nowrap;
}

.timestamps {
  display: flex;
  flex-direction: column;
  gap: var(--space-1);
  font-size: var(--font-size-xs);
  color: var(--color-text-muted);
  text-align: right;
  margin-left: auto;
}

.timestamp-item {
  display: flex;
  align-items: center;
  gap: var(--space-1);
  cursor: help;
  justify-content: flex-end;
}

.timestamp-icon {
  opacity: 0.6;
}

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

.build-content {
  padding: var(--space-4);
  display: flex;
  flex-direction: column;
  gap: var(--space-4);
}

.building-section,
.queued-section {
  background: var(--color-bg-tertiary);
  border-radius: var(--radius-md);
  padding: var(--space-3);
}

.section-title {
  display: flex;
  align-items: center;
  gap: var(--space-2);
  font-size: var(--font-size-sm);
  font-weight: var(--font-weight-semibold);
  color: var(--color-text-secondary);
  text-transform: uppercase;
  letter-spacing: 0.05em;
  margin-bottom: var(--space-3);
}

.section-icon {
  opacity: 0.7;
}

.queue-count {
  background: var(--color-bg-hover);
  padding: var(--space-1) var(--space-2);
  border-radius: var(--radius-full);
  font-size: var(--font-size-xs);
  font-weight: var(--font-weight-medium);
  color: var(--color-text-muted);
  margin-left: var(--space-1);
}

.package-list {
  display: flex;
  flex-direction: column;
  gap: var(--space-2);
}

.building-item {
  display: flex;
  align-items: center;
  gap: var(--space-3);
  padding: var(--space-2) var(--space-3);
  background: var(--color-bg-secondary);
  border-radius: var(--radius-sm);
  transition: background-color var(--transition-fast);
}

.building-item:hover {
  background: var(--color-bg-hover);
}

.package-info {
  flex: 1;
  display: flex;
  align-items: baseline;
  gap: var(--space-2);
}

.package-name {
  font-weight: var(--font-weight-semibold);
  color: var(--color-text-primary);
}

.package-repo {
  font-size: var(--font-size-xs);
  color: var(--color-text-muted);
}

.package-version {
  font-family: var(--font-family-mono);
  font-size: var(--font-size-xs);
  color: var(--color-text-secondary);
  background: var(--color-bg-tertiary);
  padding: var(--space-1) var(--space-2);
  border-radius: var(--radius-sm);
}

/* Pulse dot animations */
.pulse-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  flex-shrink: 0;
  position: relative;
}

.pulse-dot--sm {
  width: 8px;
  height: 8px;
}

.pulse-dot--idle {
  background: var(--color-status-success);
}

.pulse-dot--idle::before {
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: var(--color-status-success);
  animation: pulse-ring 2s ease-in-out infinite;
}

.pulse-dot--building {
  background: var(--color-status-warning);
}

.pulse-dot--building::before {
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: var(--color-status-warning);
  animation: pulse-ring 1.25s cubic-bezier(0.215, 0.61, 0.355, 1) infinite;
}

.pulse-dot--error {
  background: var(--color-status-error);
}

.pulse-dot--error::before {
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: var(--color-status-error);
  animation: pulse-ring 1.25s cubic-bezier(0.215, 0.61, 0.355, 1) infinite;
}

@keyframes pulse-ring {
  0% {
    transform: scale(1);
    opacity: 0.8;
  }
  100% {
    transform: scale(2.5);
    opacity: 0;
  }
}

/* Responsive */
@media (max-width: 960px) {
  .status-header {
    gap: var(--space-3);
  }

  .progress-section {
    order: 3;
    flex-basis: 100%;
    min-width: auto;
  }
}

@media (max-width: 600px) {
  .currently-building {
    border-radius: 0;
    border-left: none;
    border-right: none;
    margin-left: calc(-1 * var(--space-4));
    margin-right: calc(-1 * var(--space-4));
  }

  .status-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .timestamps {
    text-align: left;
    margin-left: 0;
  }

  .timestamp-item {
    justify-content: flex-start;
  }
}
</style>
