<script setup lang="ts">
/**
 * 思考列表：PostCard + 暗色搜索条 + 历史/热搜面板。
 */
import { ref } from 'vue'
import { onLoad, onReachBottom } from '@dcloudio/uni-app'
import AppNavbar from '@/components/layout/AppNavbar.vue'
import AppPageShell from '@/components/layout/AppPageShell.vue'
import ContentPageHeader from '../../components/ContentPageHeader.vue'
import PostCard from '@/components/c-end/PostCard.vue'
import ArtSearchBar from '@/components/c-end/ArtSearchBar.vue'
import { getPosts, getHotSearches, type Post } from '@/api'
import { useSearchHistory } from '@/composables/useSearchHistory'
import { showUnsupported } from '@/utils/unsupported'

const { getHistory, addHistory, removeHistory, clearHistory } = useSearchHistory()

const q = ref('')
const list = ref<Post[]>([])
const page = ref(1)
const loading = ref(false)
const finished = ref(false)
const hot = ref<string[]>([])
const history = ref<string[]>([])
const showSuggest = ref(false)
/** 从详情页跳转带来的筛选 */
const filterCategoryId = ref('')
const filterTagId = ref('')
const filterTagName = ref('')
const filterLabel = ref('')

function refreshHistory() {
  history.value = getHistory()
}

async function fetchList(reset = false) {
  if (loading.value) return
  if (reset) {
    page.value = 1
    finished.value = false
    list.value = []
  }
  if (finished.value) return
  loading.value = true
  try {
    const keyword = q.value.trim()
    const res = await getPosts({
      ...(keyword ? { q: keyword } : {}),
      ...(filterCategoryId.value ? { categoryId: filterCategoryId.value } : {}),
      ...(filterTagId.value ? { tagId: filterTagId.value } : {}),
      ...(filterTagName.value && !filterTagId.value ? { tag: filterTagName.value } : {}),
      page: page.value,
      pageSize: 10,
    })
    const items = Array.isArray(res) ? res : (res as { list?: Post[] }).list || []
    list.value = reset ? items : [...list.value, ...items]
    if (items.length < 10) finished.value = true
    else page.value += 1
  }
  catch (e: unknown) {
    uni.showToast({ title: e instanceof Error ? e.message : '加载失败', icon: 'none' })
  }
  finally {
    loading.value = false
  }
}

onLoad(async (query) => {
  filterCategoryId.value = String(query?.categoryId || '')
  filterTagId.value = String(query?.tagId || '')
  filterTagName.value = query?.tagName ? decodeURIComponent(String(query.tagName)) : ''
  const catName = query?.categoryName ? decodeURIComponent(String(query.categoryName)) : ''
  if (catName) filterLabel.value = `分类：${catName}`
  else if (filterTagName.value) filterLabel.value = `标签：${filterTagName.value}`
  else filterLabel.value = ''

  refreshHistory()
  fetchList(true)
  try {
    const h = await getHotSearches(8)
    hot.value = (h || []).map(i => i.keyword)
  }
  catch { /* ignore */ }
})

function clearFilter() {
  filterCategoryId.value = ''
  filterTagId.value = ''
  filterTagName.value = ''
  filterLabel.value = ''
  fetchList(true)
}

onReachBottom(() => fetchList())

/** 提交搜索：写入历史并刷新列表 */
const onSearch = () => {
  const kw = q.value.trim()
  if (kw) {
    addHistory(kw)
    refreshHistory()
  }
  showSuggest.value = false
  fetchList(true)
}

const onClear = () => {
  q.value = ''
  showSuggest.value = false
  fetchList(true)
}

const applyKeyword = (kw: string) => {
  q.value = kw
  onSearch()
}

const onRemoveHistory = (kw: string) => {
  removeHistory(kw)
  refreshHistory()
}

const onClearHistory = () => {
  clearHistory()
  refreshHistory()
}

const open = (id: string | number) =>
  uni.navigateTo({ url: `/subPackages/content/pages/blog/detail?id=${id}` })
</script>

<template>
  <AppPageShell>
    <AppNavbar title="思考" show-back />
    <view class="page-pad">
      <ContentPageHeader eyebrow="Think" title="思考" desc="记录与沉淀" />
      <ArtSearchBar
        v-model="q"
        placeholder="搜索文章"
        @search="onSearch"
        @clear="onClear"
        @focus="showSuggest = true; refreshHistory()"
      />

      <view v-if="filterLabel" class="filter-bar">
        <text class="filter-text text-art-accent">{{ filterLabel }}</text>
        <text class="filter-clear text-art-muted" @click="clearFilter">清除</text>
      </view>

      <view v-if="showSuggest && (history.length || hot.length)" class="suggest art-card">
        <view v-if="history.length" class="block">
          <view class="block-head">
            <text class="font-mono-label text-art-muted">搜索历史</text>
            <text class="clear-all text-art-muted" @click="onClearHistory">清空</text>
          </view>
          <view class="chips">
            <view v-for="k in history" :key="`h-${k}`" class="chip" @click="applyKeyword(k)">
              <text class="chip-text">{{ k }}</text>
              <view class="chip-x" @click.stop="onRemoveHistory(k)">
                <wd-icon name="close" size="12px" color="rgb(136,136,136)" />
              </view>
            </view>
          </view>
        </view>
        <view v-if="hot.length" class="block">
          <text class="font-mono-label text-art-muted">热搜</text>
          <view class="chips">
            <view v-for="k in hot" :key="`hot-${k}`" class="chip chip--hot" @click="applyKeyword(k)">
              <text class="chip-text">{{ k }}</text>
            </view>
          </view>
        </view>
      </view>

      <view v-else-if="hot.length && !q" class="hot-inline">
        <text class="font-mono-label text-art-muted">热搜</text>
        <view class="chips">
          <view v-for="k in hot" :key="k" class="chip chip--hot" @click="applyKeyword(k)">
            <text class="chip-text">{{ k }}</text>
          </view>
        </view>
      </view>

      <PostCard
        v-for="item in list"
        :key="String(item.id)"
        :post="item"
        @click="open(item.id)"
      />
      <wd-loadmore v-if="list.length" :state="finished ? 'finished' : loading ? 'loading' : 'finished'" />
      <wd-empty v-if="!loading && !list.length" description="暂无文章" />
      <view class="export-tip text-art-muted" @click="showUnsupported('文章批量导出')">导出功能 ›</view>
    </view>
  </AppPageShell>
</template>

<style scoped lang="scss">
.page-pad { padding: 24rpx 32rpx 48rpx; }
.filter-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 16rpx 0 8rpx;
  padding: 14rpx 20rpx;
  border-radius: 12rpx;
  background: rgba(212, 179, 131, 0.1);
}
.filter-text { font-size: 24rpx; }
.filter-clear { font-size: 22rpx; }
.suggest {
  margin: 20rpx 0 28rpx;
  padding: 24rpx;
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}
.hot-inline { margin: 20rpx 0 28rpx; }
.block { display: flex; flex-direction: column; gap: 14rpx; }
.block-head {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.clear-all { font-size: 22rpx; }
.chips { display: flex; flex-wrap: wrap; gap: 12rpx; margin-top: 8rpx; }
.chip {
  display: inline-flex;
  align-items: center;
  gap: 8rpx;
  padding: 10rpx 18rpx;
  border-radius: 999rpx;
  background: rgba(127, 127, 127, 0.1);
  border: 1px solid var(--art-border);
}
.chip--hot { border-color: rgba(212, 179, 131, 0.35); }
.chip-text { font-size: 24rpx; color: rgb(var(--art-text)); }
.chip-x { display: flex; align-items: center; padding: 2rpx; }
.export-tip { text-align: center; font-size: 24rpx; margin-top: 24rpx; }
</style>
