<template>
  <div class="bill-tracker-root" ref="trackerRoot">
    <div class="bt-topbar">
      <TopBar
        :keyword="filters.searchText"
        :china-related-only="filters.isCN"
        :sort-by="filters.sortBy"
        :sort-options="sortOptions"
        @update:keyword="updateKeyword"
        @toggle-china-related="updateChinaRelated(!filters.isCN)"
        @update:sort="updateSort"
      />
    </div>

    <div class="bt-main">
      <div class="bt-sidebar">
        <SidebarFilter
          :domains="filterOptions.domains"
          :time-ranges="filterOptions.timeRanges"
          :selected-domains="filters.selectedDomains"
          :selected-time-ranges="filters.selectedTimeRanges"
          @toggle-domain="toggleDomain"
          @toggle-time="toggleTimeRange"
        />
      </div>

      <div class="bt-list-area">
        <BillList
          :bills="bills"
          :loading="loading"
          :total="total"
          :current-page="currentPage"
          :page-size="pageSize"
          :progress-stages="stageConfig"
          @page-change="onPageChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import TopBar from './TopBar.vue'
import SidebarFilter from './SidebarFilter.vue'
import BillList from './BillList.vue'
import { useBills } from '../composables/useBills.js'

const trackerRoot = ref(null)

const {
  bills,
  stageConfig,
  total,
  loading,
  currentPage,
  pageSize,
  filters,
  filterOptions,
  sortOptions,
  init,
  updateKeyword,
  toggleDomain,
  toggleTimeRange,
  updateSort,
  updateChinaRelated,
  handlePageChange,
} = useBills()

const onPageChange = async (page) => {
  await handlePageChange(page)
  // 数据加载完成后滚动到顶部
  if (trackerRoot.value) {
    trackerRoot.value.scrollIntoView({ behavior: 'smooth', block: 'start' })
  }
}

onMounted(async () => {
  try {
    await init()
  } catch (err) {
    console.error('初始化失败:', err)
  }
})
</script>

<style scoped>
.bill-tracker-root {
  width: 100%;
  font-family: 'Source Han Sans CN', 'Microsoft YaHei', 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  color: rgba(59, 65, 75, 1);
}
.bt-topbar {
  padding: 12px 0;
}
.bt-main {
  display: flex;
  gap: 16px;
}
.bt-sidebar {
  flex-shrink: 0;
}
.bt-list-area {
  flex: 1;
  min-width: 0;
}
</style>
