<template>
  <div class="app-query-filter" :class="{ 'is-expanded': expanded }">
    <a-button
      v-show="isMobile"
      type="outline"
      long
      class="app-query-filter__toggle"
      @click="expanded = !expanded"
    >
      <icon-filter />
      <span>{{ label }}</span>
      <icon-down class="app-query-filter__chevron" />
    </a-button>
    <div v-if="showPanel" class="app-query-filter__panel">
      <slot />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'

defineProps({
  label: { type: String, default: '筛选条件' }
})

const expanded = ref(false)
const isMobile = ref(false)

let mediaQuery = null

const syncMobile = () => {
  isMobile.value = mediaQuery?.matches ?? window.innerWidth <= 768
  if (!isMobile.value) expanded.value = false
}

const showPanel = computed(() => !isMobile.value || expanded.value)

onMounted(() => {
  mediaQuery = window.matchMedia('(max-width: 768px)')
  syncMobile()
  mediaQuery.addEventListener('change', syncMobile)
})

onUnmounted(() => {
  mediaQuery?.removeEventListener('change', syncMobile)
})
</script>
