<template>
  <main class="marketplace-layout">
    <section class="filters-section">
      <!-- Filters Toggle -->
      <details class="filters-toggle" :open="showFilters">
        <summary @click.prevent="showFilters = !showFilters">
          Filters
          <small v-if="hasActiveFilters" style="margin-left: 0.5rem;">({{ activeFilterCount }} active)</small>
        </summary>

        <form @submit.prevent class="filters">
          <fieldset>
            <div class="grid">
              <label>
                Min Cost
                <input type="number" v-model.number="marketplace.minCost" inputmode="numeric" />
              </label>

              <label>
                Max Cost
                <input type="number" v-model.number="marketplace.maxCost" inputmode="numeric" />
              </label>
            </div>

            <label>
              Rarity
              <select v-model="marketplace.rarities" multiple size="6">
                <option value="Replacement">Replacement</option>
                <option value="Reserve">Reserve</option>
                <option value="Starter">Starter</option>
                <option value="All-Star">All-Star</option>
                <option value="MVP">MVP</option>
                <option value="Hall of Fame">Hall of Fame</option>
              </select>
            </label>

            <label>
              Cardset
              <select v-model="marketplace.cardset" multiple size="5">
                <option v-for="name in cardsetNames" :key="name" :value="name">
                  {{ name }}
                </option>
              </select>
            </label>

            <button type="button" @click="marketplace.clearFilters" class="secondary">
              Clear Filters
            </button>
          </fieldset>
        </form>
      </details>

      <!-- Active Filter Chips -->
      <div v-if="hasActiveFilters" class="filter-chips">
        <span v-if="marketplace.minCost" class="chip">
          Min: {{ marketplace.minCost }}
          <button @click="marketplace.minCost = null" aria-label="Remove Min Cost">&times;</button>
        </span>

        <span v-if="marketplace.maxCost" class="chip">
          Max: {{ marketplace.maxCost }}
          <button @click="marketplace.maxCost = null" aria-label="Remove Max Cost">&times;</button>
        </span>

        <span v-for="rar in marketplace.rarities" :key="rar" class="chip">
          {{ rar }}
          <button @click="removeRarity(rar)" aria-label="Remove Rarity">&times;</button>
        </span>

        <span v-for="set in marketplace.cardset" :key="set" class="chip">
          {{ set }}
          <button @click="removeCardset(set)" aria-label="Remove Cardset">&times;</button>
        </span>
      </div>
    </section>

      <!-- Player List -->
      <section class="player-list">
        <div v-if="loading">
          <article v-for="n in 6" :key="n" aria-busy="true">
            <header><h2>Loading...</h2></header>
            <p>Loading player data...</p>
          </article>
        </div>

        <div v-else>
          <article
            v-for="player in players"
            :key="player.player_id"
            class="player-card"
            @click="toggleExpanded(player.player_id)"
            :aria-expanded="expandedPlayerId === player.player_id"
          >
            <header class="clickable-header">
              <h2 class="player-name">{{ player.player_name }}</h2>
              <div class="summary-info">
                <small>
                  {{ player.cardset_name }} • {{ player.franchise_name }} • 
                    <span class="rarity-badge" :style="{ backgroundColor: '#' + player.rarity_color }">
                      {{ player.rarity_name }}
                    </span> • {{ player.player_cost }}₼
                </small>
              </div>
            </header>

            <transition name="fade">
              <div v-if="expandedPlayerId === player.player_id" class="expanded-content">
                <img :src="player.player_headshot" alt="Player Headshot" class="headshot" />

                <div class="strat-card-container">
                  <img :src="player.player_card_image" alt="Card Image" class="strat-card" />
                  <img v-if="player.player_card_image2" :src="player.player_card_image2" alt="Card Image 2" class="strat-card" />
                </div>
              </div>
            </transition>
          </article>
        </div>
      </section>

      <!-- Pagination -->
      <nav class="pagination-controls">
        <ul>
          <li>
            <button @click="previousPage" :disabled="page === 1">Previous</button>
          </li>
          <li>Page {{ page }}</li>
          <li>
            <button @click="nextPage">Next</button>
          </li>
        </ul>
      </nav>
  </main>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useMarketplaceStore } from '@/stores/marketplace'
import type { MarketplacePlayer } from '~/types/MarketplacePlayer'

const route = useRoute()
const router = useRouter()
const client = useSupabaseClient()
const marketplace = useMarketplaceStore()

const players = ref<MarketplacePlayer[]>([])
const loading = ref(false)
const pageSize = ref(20)
const page = ref(1)
const expandedPlayerId = ref<number | null>(null)
const showFilters = ref(false)

// Example cardset list
const cardsetNames = [
  '2021 Season', '2022 Season', '2023 Season', 'Mario Super Sluggers', 'Backyard Baseball'
]

// Computed
const hasActiveFilters = computed(() => {
  return (
    marketplace.minCost !== null ||
    marketplace.maxCost !== null ||
    marketplace.rarities.length > 0 ||
    marketplace.cardset.length > 0
  )
})

const activeFilterCount = computed(() => {
  let count = 0
  if (marketplace.minCost !== null) count++
  if (marketplace.maxCost !== null) count++
  count += marketplace.rarities.length
  count += marketplace.cardset.length
  return count
})

const fetchPlayers = async () => {
  loading.value = true
  const from = (page.value - 1) * pageSize.value
  const to = from + pageSize.value - 1

  let query = client.from('marketplace').select('*').range(from, to)

  if (marketplace.minCost !== null && marketplace.minCost > 0) {
    query = query.gte('player_cost', marketplace.minCost)
  }
  if (marketplace.maxCost !== null && marketplace.maxCost > 0) {
    query = query.lte('player_cost', marketplace.maxCost)
  }
  if (marketplace.rarities?.length > 0) {
    query = query.in('rarity_name', marketplace.rarities)
  }
  if (marketplace.cardset?.length > 0) {
    query = query.in('cardset_name', marketplace.cardset)
  }

  const { data, error } = await query
  if (error) console.error('Supabase error:', error)

  loading.value = false
  players.value = data || []
}

const toggleExpanded = (playerId: number) => {
  expandedPlayerId.value = expandedPlayerId.value === playerId ? null : playerId
}

const removeRarity = (rarity: string) => {
  marketplace.rarities = marketplace.rarities.filter(r => r !== rarity)
}

const removeCardset = (cardset: string) => {
  marketplace.cardset = marketplace.cardset.filter(c => c !== cardset)
}

const updateRoute = () => {
  router.replace({
    query: {
      page: page.value.toString(),
      ...(marketplace.minCost != null && { minCost: marketplace.minCost }),
      ...(marketplace.maxCost != null && { maxCost: marketplace.maxCost }),
      ...(marketplace.rarities.length && { rarity: marketplace.rarities }),
      ...(marketplace.cardset.length && { cardset: marketplace.cardset }),
    }
  })
}

const previousPage = () => {
  if (page.value > 1) {
    page.value--
    updateRoute()
    fetchPlayers()
  }
}

const nextPage = () => {
  page.value++
  updateRoute()
  fetchPlayers()
}

onMounted(async () => {
  const { getNumber, getArray } = useSafeQuery()

  page.value = getNumber('page') || 1

  marketplace.setFilters({
    minCost: getNumber('minCost'),
    maxCost: getNumber('maxCost'),
    rarities: getArray('rarities'),
    cardset: getArray('cardset'),
  })

  await fetchPlayers()
})


watch(
  [() => marketplace.minCost, () => marketplace.maxCost, () => marketplace.rarities, () => marketplace.cardset],
  () => {
    page.value = 1
    updateRoute()
    fetchPlayers()
  },
  { deep: true }
)
</script>

<style scoped>
.marketplace-layout {
  display: flex;
  flex-direction: column;
  min-height: 100vh; /* Full height of screen */
}

.filters-section {
  padding-left: 1rem;
  padding-right: 1rem;
  padding-top: 1rem;
}

.player-list {
  flex: 1 1 auto; /* Take up the leftover space */
  overflow-y: auto; /* Scroll if too many players */
  padding-left: 1rem;
  padding-right: 1rem;
  padding-bottom: 1rem;
}

.pagination-controls {
  padding: 1rem;
  text-align: center;
}

.grid {
  display: grid;
  gap: 1rem;
  grid-template-columns: 1fr 1fr;
}

.filters-toggle summary {
  cursor: pointer;
  font-size: 1.25rem;
}

.filter-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  margin: 1rem 0;
}

.chip {
  display: inline-flex;
  align-items: center;
  background: var(--pico-primary-background);
  color: var(--pico-primary-contrast);
  padding: 0.25rem 0.5rem;
  border-radius: var(--pico-border-radius);
}

.chip button {
  background: transparent;
  border: none;
  color: inherit;
  margin-left: 0.25rem;
  cursor: pointer;
  font-size: 1rem;
}

.player-card {
  padding: 1rem;
  margin-bottom: 1rem;
  border: 1px solid var(--pico-border-color);
  border-radius: var(--pico-border-radius);
  cursor: pointer;
  transition: background 0.3s;
  display: flex;
  flex-direction: column;
}

.player-card .clickable-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;  /* Allow wrapping of content if it exceeds screen width */
  gap: 0.5rem;  /* Space between name and summary info */
}

.player-card .player-name {
  font-size: 1.25rem;
  font-weight: bold;
}

.player-card .summary-info {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.player-card .summary-info small {
  font-size: 1rem;
  color: var(--pico-muted-color);
}

.player-card:hover {
  background: var(--pico-muted-color);
}

.rarity-badge {
  display: inline-block;
  padding: 0.2rem 0.5rem;
  border-radius: 999px;
  font-weight: bold;
  font-size: 0.85rem;
  line-height: 1;
}

.clickable-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.expanded-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
}

.strat-card-container {
  display: flex;
  justify-content: center;
  gap: 1rem;
  flex-wrap: wrap; /* Wrap on small screens */
}

img.strat-card {
  width: 100%;
  height: auto;
  margin-bottom: 1rem;
}

img.headshot {
  min-width: 80px;
  max-width: 120px;
  width: 20%;
  aspect-ratio: 1/1; /* Force it to be a perfect square */
  object-fit: cover;
  border-radius: 50%;
  border: 3px solid white;
  background: white;
  margin: 0 auto 8px;
}

.fade-enter-active,
.fade-leave-active {
  transition: all 0.3s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}
</style>
