<template>
  <view class="page">
    <!-- 固定顶部导航栏 -->
    <AnalyticsTopBar 
      :title="'商品洞察'"
      :lastUpdateTime="lastUpdateTime"
      :sidebarVisible="showSidebarMenu"
      @menu-click="handleMenu"
      @refresh="refreshData"
      @search="handleSearch"
      @notification="handleNotification"
      @fullscreen="handleFullscreen"
      @mobile="handleMobile"
      @dropdown="handleDropdown"
      @settings="handleSettings"
    />
    
    <view class="page-layout">
      <!-- 侧边栏菜单组件 -->
      <AnalyticsSidebarMenu 
        :visible="showSidebarMenu" 
        :currentPath="currentPath"
        @visible-change="handleSidebarUpdate"
      />
      
      <!-- 主内容区域 -->
      <view class="main-content">
        <view class="container">

      <!-- 时间维度筛选（快捷 + 自定义） -->
      <view class="tabs">
        <view
          v-for="p in timePeriods"
          :key="p.value"
          class="tab"
          :class="{ active: selectedPeriod === p.value && !customRangeEnabled }"
          @click="selectPeriod(p.value)"
        >
          {{ p.label }}
        </view>
        <view
          class="tab"
          :class="{ active: customRangeEnabled }"
          @click="toggleCustomRange"
        >
          自定义
        </view>
      </view>

      <AnalyticsDateRangePicker
        v-if="customRangeEnabled"
        :initialStartDate="selectedStartDate"
        :initialEndDate="selectedEndDate"
        @apply="onDateRangeApply"
        @clear="onDateRangeClear"
      />

      <!-- KPI 指标卡片 -->
      <view class="kpi-grid">
        <view class="kpi-card">
          <text class="kpi-label">商品总数</text>
          <text class="kpi-value">{{ formatInt(productData.total_products) }}</text>
          <text class="kpi-meta">较上期：{{ formatPct(productData.product_growth) }}</text>
        </view>
        <view class="kpi-card">
          <text class="kpi-label">热销商品</text>
          <text class="kpi-value">{{ formatInt(productData.hot_products) }}</text>
          <text class="kpi-meta">销量 &gt; 100</text>
        </view>
        <view class="kpi-card">
          <text class="kpi-label">库存周转率</text>
          <text class="kpi-value">{{ formatPct(productData.turnover_rate) }}</text>
          <text class="kpi-meta">较上期：{{ formatPct(productData.turnover_growth) }}</text>
        </view>
        <view class="kpi-card">
          <text class="kpi-label">平均库存</text>
          <text class="kpi-value">{{ formatInt(productData.avg_stock) }}</text>
          <text class="kpi-meta">较上期：{{ formatPct(productData.stock_growth) }}</text>
        </view>
      </view>

      <!-- 商品销售分析 -->
      <view class="card card-full">
        <view class="card-head">
          <text class="card-title">商品销售分析</text>
          <view class="card-head-right">
            <select class="select" :value="selectedProductId" @change="(e: any) => { selectedProductId = parseInt(e.detail?.value ?? e.target?.value ?? '0'); handleProductChange(); }">
              <option v-for="p in topProducts" :key="p.id" :value="p.id">{{ p.name }}</option>
            </select>
          </view>
        </view>
        <view v-if="loading || !salesChartOption || !salesChartOption.series || salesChartOption.series.length === 0" class="chart-loading">
          <text>{{ loading ? '加载中...' : '暂无数据' }}</text>
        </view>
        <EChartsView v-else class="chart-box" :option="salesChartOption" />
      </view>

      <!-- 第二行：分类 & 排行 -->
      <view class="grid-row">
        <!-- 商品分类分析 -->
        <view class="card grid-col-item">
          <view class="card-head">
            <text class="card-title">商品分类分析</text>
            <text class="card-desc">按分类统计销售额</text>
          </view>
          <view v-if="loading || !categoryChartOption || !categoryChartOption.series || categoryChartOption.series.length === 0" class="chart-loading chart-loading-sm">
            <text>{{ loading ? '加载中...' : '暂无数据' }}</text>
          </view>
          <EChartsView v-else class="chart-box chart-box-sm" :option="categoryChartOption" />
        </view>

        <!-- 热销商品排行 -->
        <view class="card grid-col-item">
          <view class="card-head">
            <text class="card-title">热销商品排行 TOP 10</text>
            <text class="card-desc">按销量排序</text>
          </view>
          <view v-if="loading || topProducts.length === 0" class="chart-loading chart-loading-sm">
            <text>{{ loading ? '加载中...' : '暂无数据' }}</text>
          </view>
          <view v-else class="rank-list-scroll">
            <view class="rank-list">
              <view v-for="p in topProducts" :key="p.id" class="rank-item">
                <text class="rank-no">{{ p.rank }}</text>
                <text class="rank-name">{{ p.name }}</text>
                <view class="rank-right">
                  <text class="rank-val">{{ p.sales }} 件</text>
                  <text class="chip" :class="p.growth >= 0 ? 'pos' : 'neg'">
                    {{ p.growth >= 0 ? '+' : '' }}{{ p.growth }}%
                  </text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 第三行：库存 & 价格 -->
      <view class="grid-row">
        <!-- 商品库存分析 -->
        <view class="card grid-col-item">
          <view class="card-head">
            <text class="card-title">商品库存分析</text>
            <text class="card-desc">库存分布情况</text>
          </view>
          <view v-if="loading || !stockChartOption || !stockChartOption.series || stockChartOption.series.length === 0" class="chart-loading chart-loading-sm">
            <text>{{ loading ? '加载中...' : '暂无数据' }}</text>
          </view>
          <EChartsView v-else class="chart-box chart-box-sm" :option="stockChartOption" />
        </view>

        <!-- 商品价格趋势 -->
        <view class="card grid-col-item">
          <view class="card-head">
            <text class="card-title">商品价格趋势</text>
            <text class="card-desc">平均价格变化</text>
          </view>
          <view v-if="loading || !priceChartOption || !priceChartOption.series || priceChartOption.series.length === 0" class="chart-loading chart-loading-sm">
            <text>{{ loading ? '加载中...' : '暂无数据' }}</text>
          </view>
          <EChartsView v-else class="chart-box chart-box-sm" :option="priceChartOption" />
        </view>
      </view>

      <!-- 第四行：评价 -->
      <view class="card card-full">
        <view class="card-head">
          <text class="card-title">商品评价分析</text>
          <text class="card-desc">评分分布</text>
        </view>
        <view v-if="loading || !reviewChartOption || !reviewChartOption.series || reviewChartOption.series.length === 0" class="chart-loading">
          <text>{{ loading ? '加载中...' : '暂无数据' }}</text>
        </view>
        <EChartsView v-else class="chart-box" :option="reviewChartOption" />
      </view>

      <!-- 留白 -->
      <view style="height: 24px;"></view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="uts">
import { computed, reactive, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

import AnalyticsSidebarMenu from '@/components/analytics/AnalyticsSidebarMenu.uvue'
import AnalyticsTopBar from '@/components/analytics/AnalyticsTopBar.uvue'
import AnalyticsDateRangePicker from '@/components/analytics/AnalyticsDateRangePicker.uvue'
import EChartsView from '@/uni_modules/charts/EChartsView.vue'
import { fetchProductOverview, fetchTopProducts, fetchProductTrend, fetchCategorySales, fetchStockInsights, fetchPriceTrend, fetchReviewInsights } from '@/services/analytics/productInsightsService.uts'
import { mapAnalyticsError } from '@/services/analytics/errorMapper.uts'

import type { TimePeriod } from '@/types/analytics/common.uts'
import type { ProductData, ProductRank } from '@/types/analytics/product.uts'

const lastUpdateTime = ref('')
const selectedPeriod = ref('7d')

const customRangeEnabled = ref(false)
const selectedStartDate = ref('')
const selectedEndDate = ref('')

const showMoreMenu = ref(false)
const showSidebarMenu = ref(false)
const currentPath = ref('/pages/mall/analytics/product-insights')

const timePeriods = ref<Array<TimePeriod>>([
  { value: '7d', label: '7天' },
  { value: '30d', label: '30天' },
  { value: '90d', label: '90天' },
  { value: '1y', label: '1年' }
])

const productData = reactive<ProductData>({
  total_products: 0,
  product_growth: 0,
  hot_products: 0,
  turnover_rate: 0,
  turnover_growth: 0,
  avg_stock: 0,
  stock_growth: 0
})

const topProducts = reactive<Array<ProductRank>>([])

const salesChartOption = ref<any>({})
const categoryChartOption = ref<any>({})
const stockChartOption = ref<any>({})
const priceChartOption = ref<any>({})
const reviewChartOption = ref<any>({})

const selectedProductId = ref('')
const loading = ref(false)

const selectedPeriodText = computed((): string => {
  const p = timePeriods.value.find((t) => t.value === selectedPeriod.value)
  return p ? p.label : '7天'
})

onLoad(() => {
  updateTime()
  loadProductData()
})

function updateTime() {
  const now = new Date()
  const hh = now.getHours().toString().padStart(2, '0')
  const mm = now.getMinutes().toString().padStart(2, '0')
  lastUpdateTime.value = `${hh}:${mm}`
}

function formatInt(n: number): string {
  const v = isFinite(n) ? Math.round(n) : 0
  if (v >= 10000) return (v / 10000).toFixed(1) + '万'
  return v.toString()
}

function formatPct(n: number): string {
  const v = isFinite(n) ? n : 0
  const sign = v > 0 ? '+' : ''
  return `${sign}${v.toFixed(1)}%`
}

async function loadSelectedProductTrend() {
  try {
    if (selectedProductId.value == null || selectedProductId.value === '') {
      salesChartOption.value = {}
      priceChartOption.value = {}
      return
    }

    const range = selectedStartDate.value && selectedEndDate.value
      ? { start: selectedStartDate.value, end: selectedEndDate.value }
      : null

    const trend = await fetchProductTrend(selectedPeriod.value, selectedProductId.value, range)
    const rows: Array<any> = trend as any

    const x: Array<string> = []
    const gmv: Array<number> = []
    const qty: Array<number> = []
    const orders: Array<number> = []

    for (let i = 0; i < rows.length; i++) {
      const d = `${rows[i].date}`
      x.push(d.slice(5))
      gmv.push(Number(rows[i].gmv) || 0)
      qty.push(Number(rows[i].qty) || 0)
      orders.push(Number(rows[i].orders) || 0)
    }

    salesChartOption.value = {
      grid: { left: 50, right: 50, top: 20, bottom: 46 },
      tooltip: { trigger: 'axis' },
      legend: { data: ['GMV', '件数', '订单数'], bottom: 0 },
      xAxis: { type: 'category', data: x, axisLabel: { color: 'rgba(0,0,0,0.55)' } },
      yAxis: [
        { type: 'value', name: 'GMV', axisLabel: { color: 'rgba(0,0,0,0.55)' }, splitLine: { lineStyle: { color: 'rgba(0,0,0,0.06)' } } },
        { type: 'value', name: '件/单', axisLabel: { color: 'rgba(0,0,0,0.55)' }, splitLine: { show: false } }
      ],
      series: [
        { name: 'GMV', type: 'bar', data: gmv, barWidth: 14, itemStyle: { borderRadius: 6 } },
        { name: '件数', type: 'line', yAxisIndex: 1, data: qty, smooth: true, symbolSize: 6 },
        { name: '订单数', type: 'line', yAxisIndex: 1, data: orders, smooth: true, symbolSize: 6 }
      ]
    }

    const avgPrice: Array<number> = []
    for (let i = 0; i < rows.length; i++) {
      const g = Number(rows[i].gmv) || 0
      const q = Number(rows[i].qty) || 0
      avgPrice.push(q > 0 ? g / q : 0)
    }

    priceChartOption.value = {
      grid: { left: 40, right: 18, top: 20, bottom: 40 },
      tooltip: { trigger: 'axis' },
      xAxis: { type: 'category', data: x, axisLabel: { color: 'rgba(0,0,0,0.55)' } },
      yAxis: { type: 'value', name: '均价', axisLabel: { color: 'rgba(0,0,0,0.55)' }, splitLine: { lineStyle: { color: 'rgba(0,0,0,0.06)' } } },
      series: [{ name: '均价', type: 'line', data: avgPrice, smooth: true, symbolSize: 6, color: '#f97316' }]
    }
  } catch (e) {
    console.error('loadSelectedProductTrend failed', e)
    salesChartOption.value = {}
    uni.showToast({ title: mapAnalyticsError(e, { fallbackMessage: '加载商品趋势失败' }), icon: 'none' })
  }
}

function handleProductChange() {
  loadSelectedProductTrend()
}

function buildCategoryChart(catRows: any) {
  const rows: Array<any> = Array.isArray(catRows) ? (catRows as Array<any>) : []
  const names: Array<string> = []
  const values: Array<number> = []
  for (let i = 0; i < rows.length; i++) {
    names.push(`${rows[i].category_name ?? '未分类'}`)
    values.push(Number(rows[i].total_sales) || 0)
  }

  categoryChartOption.value = {
    tooltip: { trigger: 'axis' },
    grid: { left: 60, right: 18, top: 20, bottom: 40 },
    xAxis: { type: 'value', axisLabel: { color: 'rgba(0,0,0,0.55)' } },
    yAxis: { type: 'category', data: names, axisLabel: { color: 'rgba(0,0,0,0.55)' } },
    series: [{ type: 'bar', data: values, barWidth: 14, itemStyle: { borderRadius: 6 } }]
  }
}

function buildStockChart(stockRows: any) {
  const rows: Array<any> = Array.isArray(stockRows) ? (stockRows as Array<any>) : []
  const names: Array<string> = []
  const values: Array<number> = []
  for (let i = 0; i < rows.length; i++) {
    names.push(`${rows[i].bucket ?? ''}`)
    values.push(Number(rows[i].value) || 0)
  }

  stockChartOption.value = {
    tooltip: { trigger: 'axis' },
    grid: { left: 60, right: 18, top: 20, bottom: 40 },
    xAxis: { type: 'value', axisLabel: { color: 'rgba(0,0,0,0.55)' } },
    yAxis: { type: 'category', data: names, axisLabel: { color: 'rgba(0,0,0,0.55)' } },
    series: [{ type: 'bar', data: values, barWidth: 14, itemStyle: { borderRadius: 6 } }]
  }
}

function buildReviewChart(reviewRows: any) {
  const rows: Array<any> = Array.isArray(reviewRows) ? (reviewRows as Array<any>) : []
  const names: Array<string> = []
  const values: Array<number> = []
  for (let i = 0; i < rows.length; i++) {
    names.push(`${rows[i].rating ?? ''}`)
    values.push(Number(rows[i].count) || 0)
  }

  reviewChartOption.value = {
    tooltip: { trigger: 'axis' },
    grid: { left: 40, right: 18, top: 20, bottom: 40 },
    xAxis: { type: 'category', data: names, axisLabel: { color: 'rgba(0,0,0,0.55)' } },
    yAxis: { type: 'value', axisLabel: { color: 'rgba(0,0,0,0.55)' } },
    series: [{ type: 'bar', data: values, barWidth: 14, itemStyle: { borderRadius: 6 } }]
  }
}

async function loadProductData() {
  loading.value = true
  try {
    updateTime()

    const range = selectedStartDate.value && selectedEndDate.value
      ? { start: selectedStartDate.value, end: selectedEndDate.value }
      : null

    const [overview, topList, catRows, stockRows, _priceRows, reviewRows] = await Promise.all([
      fetchProductOverview(selectedPeriod.value, range),
      fetchTopProducts(selectedPeriod.value, 10, range),
      fetchCategorySales(selectedPeriod.value, range),
      fetchStockInsights(selectedPeriod.value),
      fetchPriceTrend(selectedPeriod.value, range),
      fetchReviewInsights()
    ])

    productData.total_products = overview.total_products
    productData.product_growth = overview.product_growth
    productData.hot_products = overview.hot_products
    productData.turnover_rate = overview.turnover_rate
    productData.turnover_growth = overview.turnover_growth
    productData.avg_stock = overview.avg_stock
    productData.stock_growth = overview.stock_growth

    const top = topList.slice()
    for (let i = 0; i < top.length; i++) top[i].rank = i + 1
    topProducts.splice(0, topProducts.length, ...top)

    if ((selectedProductId.value == null || selectedProductId.value === '') && top.length > 0) {
      const real = top.find((it) => !String(it.id).startsWith('fake-product-'))
      selectedProductId.value = real ? real.id : ''
    }

    if (selectedProductId.value == null || selectedProductId.value === '') {
      salesChartOption.value = {}
    } else {
      await loadSelectedProductTrend()
    }

    buildCategoryChart(catRows)
    buildStockChart(stockRows)
    buildReviewChart(reviewRows)

    updateTime()
  } catch (e) {
    console.error('loadProductData failed', e)
    uni.showToast({ title: mapAnalyticsError(e, { fallbackMessage: '商品洞察数据加载失败' }), icon: 'none', duration: 2000 })
  } finally {
    loading.value = false
    updateTime()
  }
}

function selectPeriod(p: string) {
  selectedPeriod.value = p
  customRangeEnabled.value = false
  selectedStartDate.value = ''
  selectedEndDate.value = ''
  loadProductData()
}

function toggleCustomRange() {
  customRangeEnabled.value = !customRangeEnabled.value
}

function onDateRangeApply(range: { start: string; end: string }) {
  selectedStartDate.value = range.start
  selectedEndDate.value = range.end
  customRangeEnabled.value = true
  loadProductData()
}

function onDateRangeClear() {
  selectedStartDate.value = ''
  selectedEndDate.value = ''
  customRangeEnabled.value = false
  loadProductData()
}

function refreshData() {
  loadProductData()
  uni.showToast({ title: '已刷新', icon: 'success' })
}

function exportReport() {
  uni.showActionSheet({
    itemList: ['导出Excel', '导出PDF', '导出图片'],
    success: () => uni.showToast({ title: '导出成功', icon: 'success' })
  })
}

function handleMenu() {
  showSidebarMenu.value = true
}

function handleSidebarUpdate(visible: boolean) {
  showSidebarMenu.value = visible
}

function toggleMoreMenu() {
  showMoreMenu.value = !showMoreMenu.value
}

function closeMoreMenu() {
  showMoreMenu.value = false
}

function handleSearch() {
  uni.showToast({ title: '搜索', icon: 'none' })
}

function handleNotification() {
  uni.showToast({ title: '通知', icon: 'none' })
}

function handleFullscreen() {
  uni.showToast({ title: '全屏', icon: 'none' })
}

function handleMobile() {
  uni.showToast({ title: '移动端', icon: 'none' })
}

function handleDropdown() {
  uni.showToast({ title: '下拉菜单', icon: 'none' })
}

function handleSettings() {
  uni.showToast({ title: '设置', icon: 'none' })
}
</script>

<style>
.page {
  min-height: 100vh;
  background: #f6f7fb;
}

/* 页面布局：宽屏时侧边栏+内容，窄屏时全屏内容 */
.page-layout {
  display: flex;
  flex-direction: row !important;
  min-height: 100vh;
}

.main-content {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  padding-top: 64px; /* 为固定顶部导航栏留出空间 */
}

.container {
  width: 100%;
  max-width: 1280px;
  margin: 0 auto;
  padding: 16px 16px 28px;
  box-sizing: border-box;
}

/* 顶部栏 */
.topbar {
  display: flex;
  flex-direction: row !important;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
  padding: 14px 16px;
  background: #fff;
  border-radius: 14px;
  border: 1px solid rgba(0,0,0,0.06);
  width: 100%;
  box-sizing: border-box;
  overflow: hidden;
}

.topbar-left {
  display: flex;
  flex-direction: row !important;
  align-items: center;
  gap: 12px;
  flex: 1;
  min-width: 0;
}

.menu-icon {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  background: #f3f4f6;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
}

.menu-icon:active {
  background: #e5e7eb;
  transform: scale(0.95);
}

.menu-icon .icon {
  font-size: 18px;
  color: #111;
  line-height: 1;
}

.title-group {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 4px;
  min-width: 0;
}

.title {
  font-size: 18px;
  font-weight: 700;
  color: #111;
  max-width: 420px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.subtitle {
  font-size: 12px;
  color: rgba(0,0,0,0.55);
  max-width: 420px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.topbar-right {
  display: flex;
  flex-direction: row !important;
  gap: 8px;
  align-items: center;
  flex-wrap: nowrap;
  flex-shrink: 0;
  position: relative;
  white-space: nowrap;
}

.icon-btn-icon {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  background: #f3f4f6;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  position: relative;
  transition: all 0.2s;
  flex-shrink: 0;
}

.icon-btn-icon:active {
  background: #e5e7eb;
  transform: scale(0.95);
}

.icon-btn-icon .icon {
  font-size: 16px;
  line-height: 1;
}

.more-btn {
  display: none;
  width: 32px;
  height: 32px;
  border-radius: 8px;
  background: #f3f4f6;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  position: relative;
  transition: all 0.2s;
  flex-shrink: 0;
}

.more-btn.active {
  background: #e5e7eb;
}

.more-btn .icon {
  font-size: 18px;
  line-height: 1;
  color: #111;
}

/* 时间维度 tabs */
.tabs {
  margin-top: 12px;
  display: flex;
  flex-direction: row !important;
  gap: 8px;
  padding: 8px;
  background: #fff;
  border-radius: 14px;
  border: 1px solid rgba(0,0,0,0.06);
  overflow-x: auto;
  flex-wrap: wrap;
  justify-content: center;
}

.tab {
  padding: 8px 12px;
  border-radius: 999px;
  background: #f3f4f6;
  color: #111;
  font-size: 13px;
  white-space: nowrap;
  flex-shrink: 0;
}

.tab.active {
  background: #111;
  color: #fff;
}

/* KPI 网格 */
.kpi-grid {
  margin-top: 12px;
  display: flex;
  flex-direction: row !important;
  flex-wrap: wrap;
  gap: 12px;
}

.kpi-card {
  background: #fff;
  border-radius: 14px;
  border: 1px solid rgba(0,0,0,0.06);
  padding: 14px;
  box-sizing: border-box;
  flex: 1 1 calc(50% - 6px);
  min-width: 260px;
}

.kpi-label {
  font-size: 12px;
  color: rgba(0,0,0,0.55);
}

.kpi-value {
  margin-top: 8px;
  font-size: 22px;
  font-weight: 800;
  color: #111;
}

.kpi-meta {
  margin-top: 8px;
  font-size: 12px;
  color: rgba(0,0,0,0.55);
}

/* 卡片 */
.card {
  margin-top: 12px;
  background: #fff;
  border-radius: 16px;
  border: 1px solid rgba(0,0,0,0.06);
  box-shadow: 0 2px 10px rgba(0,0,0,0.04);
  padding: 14px;
  box-sizing: border-box;
}

.card-full {
  width: 100%;
}

.card-head {
  display: flex;
  flex-direction: row !important;
  align-items: baseline;
  justify-content: space-between;
  margin-bottom: 16px;
}

.card-title {
  font-size: 14px;
  font-weight: 600;
  color: #111;
}

.card-desc {
  font-size: 12px;
  color: rgba(0,0,0,0.55);
}

.card-head-right {
  display: flex;
  flex-direction: row !important;
  gap: 8px;
  align-items: center;
}

.select {
  padding: 6px 10px;
  border: 1px solid rgba(0,0,0,0.1);
  border-radius: 10px;
  font-size: 13px;
}

.chart-box {
  width: 100%;
  height: 360px;
}

.chart-box-sm {
  height: 300px;
}

.chart-loading {
  width: 100%;
  height: 320px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: rgba(0,0,0,0.45);
  font-size: 14px;
}

.chart-loading-sm {
  height: 220px;
}

.grid-row {
  display: flex;
  flex-direction: row !important;
  flex-wrap: wrap;
  gap: 12px;
  align-items: stretch;
  margin-top: 12px;
}

.grid-col-item {
  flex: 1 1 calc(50% - 6px);
  min-width: 360px;
}

.rank-list-scroll {
  max-height: 320px;
  overflow-y: auto;
}

.rank-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.rank-item {
  display: flex;
  flex-direction: row !important;
  align-items: center;
  gap: 10px;
  padding: 10px 0;
  border-bottom: 1px solid rgba(0,0,0,0.06);
}

.rank-item:last-child {
  border-bottom: none;
}

.rank-no {
  width: 28px;
  height: 28px;
  border-radius: 999px;
  background: rgba(0,0,0,0.06);
  text-align: center;
  line-height: 28px;
  font-size: 12px;
  flex: 0 0 auto;
}

.rank-name {
  flex: 1;
  font-size: 13px;
  color: #111;
}

.rank-right {
  display: flex;
  flex-direction: row !important;
  align-items: center;
  gap: 8px;
}

.rank-val {
  font-size: 13px;
  color: rgba(0,0,0,0.65);
}

.chip {
  padding: 3px 8px;
  border-radius: 999px;
  font-size: 12px;
}

.chip.pos {
  background: rgba(34,197,94,0.12);
  color: #16a34a;
}

.chip.neg {
  background: rgba(239,68,68,0.12);
  color: #dc2626;
}

@media screen and (max-width: 960px) {
  .grid-row {
    flex-direction: column;
  }

  .grid-col-item {
    flex: 1 1 100%;
    min-width: 100%;
  }

  .title,
  .subtitle {
    max-width: 200px;
  }

  .topbar-right .btn-hidden {
    display: none !important;
  }

  .more-btn {
    display: flex !important;
  }
}

/* 响应式：窄屏时全屏显示 */
@media screen and (max-width: 959px) {
  .page-layout {
    flex-direction: column !important;
  }

  .main-content {
    width: 100%;
  }
}
</style>
