<template>
  <v-container fluid class="pt-2 pb-6">

    <!-- Search lives in BrowseView's sticky bar (shared across tabs); this view
         reacts to route.query.q. The platform filter stays here. -->
    <div class="fc-artists__controls">
      <v-select
        v-model="platformModel"
        :items="platformItems"
        density="compact" variant="outlined" hide-details
        placeholder="Platform" clearable style="max-width: 220px;"
      />
    </div>

    <v-alert v-if="store.error" type="error" variant="tonal" closable class="my-4">
      Failed to load: {{ store.error }}
    </v-alert>
    <v-alert v-else-if="store.isEmpty" type="info" variant="tonal" class="my-4">
      No artists match.
    </v-alert>

    <div class="fc-artists__grid">
      <ArtistCard v-for="c in store.cards" :key="c.id" :card="c" />
    </div>

    <div v-if="store.loading" class="fc-artists__sentinel">
      <v-progress-circular indeterminate color="accent" size="28" />
    </div>
    <div v-else-if="store.hasMore" ref="sentinelEl" class="fc-artists__sentinel" />
  </v-container>
</template>

<script setup>
import { computed, ref, watch, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useArtistDirectoryStore } from '../stores/artistDirectory.js'
import { usePlatformsStore } from '../stores/platforms.js'
import { useInfiniteScroll } from '../composables/useInfiniteScroll.js'
import ArtistCard from '../components/discovery/ArtistCard.vue'

const route = useRoute()
const store = useArtistDirectoryStore()
const platformsStore = usePlatformsStore()

const platformModel = ref(null)
const sentinelEl = ref(null)

const platformItems = ref([])

// Search term comes from BrowseView's shared sticky bar via route.query.q.
const searchTerm = computed(() => (typeof route.query.q === 'string' ? route.query.q : ''))
watch(searchTerm, (v) => store.setQuery(v || ''))
watch(platformModel, (v) => store.setPlatform(v || null))

useInfiniteScroll(sentinelEl, () => {
  if (store.hasMore && !store.loading) store.loadMore()
})

onMounted(async () => {
  await platformsStore.loadAll()
  platformItems.value = (platformsStore.platforms || []).map(p => ({
    title: p.key, value: p.key,
  }))
  // Apply any deep-linked q (and load). setQuery resets + fetches.
  store.setQuery(searchTerm.value || '')
})
</script>

<style scoped>
.fc-artists__controls {
  display: flex; align-items: center; gap: 16px;
  flex-wrap: wrap; margin-bottom: 16px;
}
.fc-artists__grid {
  display: grid;
  /* min(360px, 100%) so a card never exceeds the viewport (phones collapse to
     one column). 360 keeps a LONE column under ~732px wide, so the 3/1 preview
     strip stays ≲244px tall and always fills the card width (no dead space),
     while giving 2+ columns on a normal desktop. */
  grid-template-columns: repeat(auto-fill, minmax(min(360px, 100%), 1fr));
  gap: 12px;
}
.fc-artists__sentinel {
  display: flex; justify-content: center; padding: 32px 0; min-height: 60px;
}
</style>
