<template>
  <div class="view-container">
    <div class="search-container" style="max-width:100%;margin-bottom:16px">
      <input v-model="q" @keyup.enter="applyQuery" placeholder="Suchen..." />
      <select v-model="cat">
        <option value="">Alle Kategorien</option>
        <option v-for="c in CATEGORIES" :key="c">{{ c }}</option>
      </select>
      <input v-model="plz" class="location-input" placeholder="PLZ" @change="applyQuery" />
      <button class="btn-primary" @click="applyQuery">Suchen</button>
    </div>

    <div v-if="plzError" style="color:#f44336;font-size:13px;margin-bottom:12px">
      ⚠️ PLZ „{{ plz }}" nicht bekannt. Bitte eine PLZ aus dem NRW-Raum eingeben.
    </div>

    <div class="category-chips">
      <span :class="['chip', !cat && 'active']" @click="cat=''">Alle</span>
      <span v-for="c in CATEGORIES" :key="c" :class="['chip', cat===c && 'active']" @click="cat=c">{{ c }}</span>
    </div>

    <div class="marketplace-body">
      <aside class="filter-sidebar">
        <h3>UMKREIS</h3>
        <label v-for="r in [5,10,20,50]" :key="r">
          <input type="radio" v-model="radius" :value="r" /> {{ r }} km
        </label>
        <h3>ANBIETERTYP</h3>
        <label><input type="checkbox" v-model="types" value="Fachhandel" /> Fachhandel</label>
        <label><input type="checkbox" v-model="types" value="Baumarkt" /> Baumarkt</label>
        <h3>PREIS BIS</h3>
        <input type="range" v-model="maxPrice" min="1" max="500" style="width:100%" />
        <span style="font-size:13px">max. {{ maxPrice }} €</span>
      </aside>

      <main style="flex:1">
        <div class="feed-header">
          <strong>{{ filtered.length }} Ergebnisse</strong>
          <span class="tag" v-if="q"> für „{{ q }}"</span>
          <span class="tag" v-if="!plzError"> · Umkreis {{ radius }} km um {{ plz }}</span>
        </div>
        <div v-if="filtered.length === 0" style="color:#888;margin-top:40px;text-align:center">
          Keine Ergebnisse gefunden.
        </div>
        <div class="products-grid">
          <div v-for="p in filtered" :key="p.id" class="product-card" @click="router.push(`/produkt/${p.id}`)">
            <div class="card-image-placeholder"><span>{{ p.icon }}</span></div>
            <div class="card-details">
              <span class="price">{{ p.price }} €</span>
              <h4 style="margin:6px 0 4px">{{ p.title }}</h4>
              <p style="margin:0;font-size:12px;color:#aaa">{{ p.provider }}</p>
              <div class="card-footer">
                <span>📍 {{ p.distance }} km</span>
                <span class="badge-cat">{{ p.category }}</span>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { CATEGORIES, providers, productsWithDistance } from '@/stores/products'
import { resolveCoords } from '@/utils/geo'

const route = useRoute()
const router = useRouter()

const q       = ref((route.query.q   as string) ?? '')
const cat     = ref((route.query.cat as string) ?? '')
const plz     = ref((route.query.plz as string) ?? '42103')
const radius  = ref(20)
const maxPrice= ref(500)
const types   = ref<string[]>([])

const plzError = computed(() => !resolveCoords(plz.value))

const enriched = computed(() => productsWithDistance(plz.value))

const filtered = computed(() => {
  if (plzError.value) return []
  return enriched.value.filter(p => {
    if (q.value && !p.title.toLowerCase().includes(q.value.toLowerCase())) return false
    if (cat.value && p.category !== cat.value) return false
    if (p.distance === null || p.distance > radius.value) return false
    if (p.price > maxPrice.value) return false
    if (types.value.length) {
      const prov = providers.find(pr => pr.id === p.providerId)
      if (prov && !types.value.includes(prov.type)) return false
    }
    return true
  }).sort((a, b) => (a.distance ?? 999) - (b.distance ?? 999))
})

watch(() => route.query, qry => {
  q.value   = (qry.q   as string) ?? ''
  cat.value = (qry.cat as string) ?? ''
  plz.value = (qry.plz as string) ?? plz.value
})

function applyQuery() {
  router.replace({ query: { q: q.value, cat: cat.value, plz: plz.value } })
}
</script>
