<template>
  <nav aria-label="Navigation">
    <ol class="flex items-center gap-1 text-sm flex-wrap">
      <li v-if="showRoot" class="flex items-center gap-1">
        <button
          @click="$emit('navigate', null)"
          class="text-indigo-600 hover:underline font-medium"
        >
          {{ rootLabel }}
        </button>
      </li>

      <template v-for="(segment, idx) in visibleSegments" :key="segment.id ?? 'static-' + idx">
        <li
          v-if="showRoot || idx > 0"
          class="shrink-0"
          aria-hidden="true"
        >
          <AppIcon name="chevronRight" class="w-3 h-3 text-gray-400" />
        </li>

        <li v-if="segment.id === 'ellipsis'" class="flex items-center">
          <span class="px-2 py-1 text-gray-400">…</span>
        </li>

        <li v-else-if="idx === visibleSegments.length - 1" class="flex items-center">
          <span class="text-gray-900 font-medium">{{ segment.label }}</span>
        </li>

        <li v-else-if="segment.id" class="flex items-center">
          <button
            @click="$emit('navigate', segment.id)"
            class="text-indigo-600 hover:underline font-medium"
          >
            {{ segment.label }}
          </button>
        </li>

        <li v-else class="flex items-center">
          <span class="text-gray-500">{{ segment.label }}</span>
        </li>
      </template>

      <!-- Freshness indicator — shown only when folderFreshness is set -->
      <li v-if="folderFreshness" class="flex items-center ml-2 shrink-0" data-test="freshness-indicator">
        <!-- Refreshing spinner -->
        <span
          v-if="folderFreshness === 'refreshing'"
          class="inline-flex items-center gap-1 text-xs text-gray-400"
          aria-label="Refreshing folder contents"
          role="status"
          data-freshness="refreshing"
        >
          <svg class="animate-spin w-3 h-3 text-gray-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" aria-hidden="true">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/>
          </svg>
          <span class="sr-only">Refreshing</span>
        </span>

        <!-- Fresh checkmark — fades after 3s -->
        <transition name="freshness-fade">
          <span
            v-if="folderFreshness === 'fresh' && showFreshMark"
            class="inline-flex items-center gap-1 text-xs text-green-500"
            aria-label="Folder contents are up to date"
            role="status"
            data-freshness="fresh"
          >
            <AppIcon name="checkMark" class="w-3 h-3" />
            <span class="sr-only">Up to date</span>
          </span>
        </transition>

        <!-- Warning indicator for stale / error -->
        <template v-if="folderFreshness === 'stale'">
          <span
            class="inline-flex items-center gap-1 text-xs text-amber-500 cursor-default"
            :title="staleTooltip"
            aria-label="staleWarningLabel"
            role="status"
            data-freshness="stale"
          >
            <AppIcon name="warning" class="w-3 h-3 text-amber-400" />
            <span class="hidden sm:inline">{{ staleWarningLabel }}</span>
          </span>
        </template>
      </li>
    </ol>

    <!-- Stale warning banner — shown below breadcrumb when stale -->
    <div
      v-if="folderFreshness === 'stale'"
      class="mt-1.5 px-3 py-2 rounded-lg bg-amber-50 border border-amber-200 text-xs text-amber-800 flex items-start gap-2"
      role="alert"
      data-test="stale-warning-banner"
    >
      <AppIcon name="warning" class="w-3.5 h-3.5 text-amber-500 shrink-0 mt-0.5" />
      <span>
        Could not refresh folder contents.
        <template v-if="lastRefreshedAt">Last updated {{ staleRelativeTime }}.</template>
        Please check your connection and try again.
      </span>
    </div>
  </nav>
</template>

<script>
import AppIcon from './AppIcon.vue'
import { formatRelativeTime } from '../../utils/formatters.js'

export default {
  name: 'BreadcrumbBar',
  components: { AppIcon },
  props: {
    segments:         { type: Array,   default: () => [] },
    rootLabel:        { type: String,  default: 'Home' },
    showRoot:         { type: Boolean, default: true },
    /** 'refreshing' | 'fresh' | 'stale' | null */
    folderFreshness:  { type: String,  default: null },
    /** ISO timestamp of last successful refresh */
    lastRefreshedAt:  { type: String,  default: null },
  },
  emits: ['navigate'],
  data() {
    return {
      showFreshMark: false,
      freshTimer: null,
    }
  },
  computed: {
    visibleSegments() {
      if (this.segments.length > 4) {
        return [
          this.segments[0],
          { id: 'ellipsis', label: '…' },
          ...this.segments.slice(-2),
        ]
      }
      return this.segments
    },
    staleWarningLabel() {
      if (this.lastRefreshedAt) {
        return `Last updated ${formatRelativeTime(this.lastRefreshedAt)}`
      }
      return 'Refresh failed'
    },
    staleTooltip() {
      return this.staleWarningLabel + '. Please check your connection and try again.'
    },
    staleRelativeTime() {
      return this.lastRefreshedAt ? formatRelativeTime(this.lastRefreshedAt) : ''
    },
  },
  watch: {
    folderFreshness: {
      immediate: true,
      handler(val) {
        if (val === 'fresh') {
          this.showFreshMark = true
          clearTimeout(this.freshTimer)
          // Fade out after 3 seconds without layout shift
          this.freshTimer = setTimeout(() => {
            this.showFreshMark = false
          }, 3000)
        } else {
          this.showFreshMark = false
          clearTimeout(this.freshTimer)
        }
      },
    },
  },
  beforeUnmount() {
    clearTimeout(this.freshTimer)
  },
}
</script>

<style scoped>
.freshness-fade-enter-active {
  transition: opacity 0.3s;
}
.freshness-fade-leave-active {
  transition: opacity 1s;
}
.freshness-fade-enter-from,
.freshness-fade-leave-to {
  opacity: 0;
}
</style>
