<template>
  <el-dialog
    :visible.sync="visibleProxy"
    :show-close="false"
    width="1000px"
    top="2vh"
    :close-on-click-modal="false"
    custom-class="member-tier-report-dialog"
    append-to-body
    @opened="handleOpened"
  >
    <div class="dialog-inner" v-loading="loading">
      <div class="dialog-header">
        <div class="header-left">
          <div class="dialog-title">门店会员分层统计</div>
          <div class="dialog-sub">截止月末累计口径 · {{ storeName || '当前门店' }}</div>
        </div>
        <div class="header-actions">
          <el-date-picker
            v-model="statisticsMonthDate"
            type="month"
            placeholder="截止月份"
            value-format="yyyy-MM"
            size="small"
            :clearable="false"
            @change="fetchData"
          />
          <el-button size="small" icon="el-icon-download" :disabled="!trendRows.length" @click="exportCsv">
            导出
          </el-button>
          <span class="dialog-close" @click="visibleProxy = false"><i class="el-icon-close"></i></span>
        </div>
      </div>

      <template v-if="current">
        <div class="summary-grid">
          <div
            v-for="card in summaryCards"
            :key="card.key"
            class="summary-card"
            :class="'summary-card--' + card.key"
          >
            <div class="card-label">{{ card.label }}</div>
            <div class="card-value">{{ card.value }}</div>
            <div v-if="card.deltaShort" class="card-delta" :class="card.deltaClass">{{ card.deltaShort }}</div>
          </div>
        </div>

        <div class="report-sections">
          <div v-if="compareBarMetrics.length" class="section-panel">
            <div class="section-head">
              <span class="section-title">环比柱状对比</span>
              <span class="section-meta">
                <i class="legend-swatch legend-swatch--prev"></i>{{ previousMonthLabel }}
                <i class="legend-swatch legend-swatch--curr"></i>{{ current.periodLabel }}
              </span>
            </div>
            <div class="compare-bar-chart">
              <div v-for="item in compareBarMetrics" :key="item.key" class="compare-bar-group">
                <div class="compare-bar-label">{{ item.label }}</div>
                <div class="compare-bar-track">
                  <div class="compare-bar-col">
                    <div class="compare-bar compare-bar--prev" :style="{ height: item.prevHeight + '%', background: item.color }" />
                    <span class="compare-bar-num">{{ item.prev }}</span>
                  </div>
                  <div class="compare-bar-col">
                    <div class="compare-bar compare-bar--curr" :style="{ height: item.currHeight + '%', background: item.color }" />
                    <span class="compare-bar-num is-current">{{ item.curr }}</span>
                  </div>
                </div>
                <div class="compare-bar-diff" :class="'is-' + item.trend">
                  <i :class="item.trendIcon"></i><span>{{ item.diffText }}</span>
                </div>
              </div>
            </div>
          </div>

          <div v-if="sparklineSeries.length" class="section-panel">
            <div class="section-head">
              <span class="section-title">近 {{ trendRows.length }} 月趋势</span>
            </div>
            <div class="sparkline-grid">
              <div v-for="series in sparklineSeries" :key="series.key" class="sparkline-card">
                <div class="sparkline-head">
                  <span class="sparkline-label">{{ series.label }}</span>
                  <span class="sparkline-change" :class="'is-' + series.trend">
                    <i :class="series.trendIcon"></i>{{ series.changeText }}
                  </span>
                </div>
                <div class="sparkline-chart-area">
                  <svg class="sparkline-svg" viewBox="0 0 280 72" preserveAspectRatio="xMidYMid meet">
                    <line x1="10" y1="62" x2="270" y2="62" stroke="#e2e8f0" stroke-width="1" />
                    <defs>
                      <linearGradient :id="'grad-' + series.key" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="0%" :stop-color="series.color" stop-opacity="0.3" />
                        <stop offset="100%" :stop-color="series.color" stop-opacity="0.02" />
                      </linearGradient>
                    </defs>
                    <polygon :points="series.areaPoints" :fill="'url(#grad-' + series.key + ')'" />
                    <polyline
                      :points="series.linePoints"
                      fill="none"
                      :stroke="series.color"
                      stroke-width="2.5"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                    />
                    <circle
                      v-for="(pt, idx) in series.dots"
                      :key="idx"
                      :cx="pt.x"
                      :cy="pt.y"
                      r="3.5"
                      :fill="idx === series.dots.length - 1 ? series.color : '#fff'"
                      :stroke="series.color"
                      stroke-width="1.5"
                    />
                  </svg>
                </div>
                <div class="sparkline-axis sparkline-axis--full">
                  <span v-for="(lbl, idx) in series.labels" :key="idx">{{ lbl }}</span>
                </div>
              </div>
            </div>
          </div>

          <div class="section-panel section-panel--table">
            <div class="section-head">
              <span class="section-title">月度对比</span>
            </div>
            <el-table
              :data="trendRows"
              border
              size="small"
              stripe
              class="report-table"
              :row-class-name="tableRowClassName"
              :header-cell-style="greenHeaderStyle"
              empty-text="暂无数据"
            >
              <el-table-column prop="periodLabel" label="截止月份" min-width="128" show-overflow-tooltip />
              <el-table-column prop="totalCount" label="总人数" min-width="96" align="right" />
              <el-table-column prop="newCustomerCount" label="新客" min-width="88" align="right" />
              <el-table-column prop="activeCount" label="常到店" min-width="96" align="right" />
              <el-table-column prop="warnCount" label="预警客" min-width="96" align="right" />
              <el-table-column prop="grayCount" label="灰客" min-width="88" align="right" />
              <el-table-column prop="blackCount" label="黑客" min-width="88" align="right" />
              <el-table-column prop="refundCount" label="退款" min-width="88" align="right" />
            </el-table>
          </div>

          <div class="footer-split">
            <div class="section-panel">
              <div class="section-head">
                <span class="section-title">活跃度结构（{{ current.periodLabel }}）</span>
              </div>
              <div class="structure-bar">
                <div
                  v-for="seg in tierStructure"
                  :key="seg.key"
                  class="structure-seg"
                  :style="{ width: seg.pct + '%', background: seg.color }"
                  :title="`${seg.label} ${seg.count}人 (${seg.pct}%)`"
                />
              </div>
              <div class="structure-legend">
                <div v-for="seg in tierStructure" :key="seg.key" class="legend-item">
                  <span class="legend-dot" :style="{ background: seg.color }"></span>
                  <span class="legend-label">{{ seg.label }}</span>
                  <span class="legend-count">{{ seg.count }}</span>
                  <span class="legend-pct">{{ seg.pct }}%</span>
                </div>
              </div>
            </div>

            <div v-if="deltaRows.length" class="section-panel">
              <div class="section-head">
                <span class="section-title">相对上月增减</span>
              </div>
              <div class="delta-grid">
                <div v-for="row in deltaRows" :key="row.key" class="delta-cell">
                  <div class="delta-cell-label">{{ row.label }}</div>
                  <div class="delta-cell-ending">期末 {{ row.ending }}</div>
                  <div class="delta-cell-change">
                    <span v-if="row.increase > 0" class="change-up"><i class="el-icon-top"></i>+{{ row.increase }}</span>
                    <span v-if="row.decrease > 0" class="change-down"><i class="el-icon-bottom"></i>-{{ row.decrease }}</span>
                    <span v-if="!row.increase && !row.decrease" class="change-flat"><i class="el-icon-minus"></i>持平</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>

      <div v-else-if="!loading" class="empty-state">暂无统计数据</div>

      <div class="rule-tip">
        常到店 ≤90天 · 预警 91~150天 · 灰客 &gt;150天且有剩余次数 · 黑客 &gt;150天且无剩余次数
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { getMemberTierStatistics } from '@/api/memberTierReport'

export default {
  name: 'MemberTierReportDialog',
  props: {
    visible: { type: Boolean, default: false },
    storeId: { type: String, default: '' },
    storeName: { type: String, default: '' }
  },
  data() {
    const now = new Date()
    const ym = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
    return {
      loading: false,
      statisticsMonthDate: ym,
      current: null,
      trendRows: [],
      greenHeaderStyle: { background: '#f0fdf4', color: '#166534', fontWeight: 600 }
    }
  },
  computed: {
    visibleProxy: {
      get() { return this.visible },
      set(v) { this.$emit('update:visible', v) }
    },
    statisticsMonth() {
      return this.statisticsMonthDate ? this.statisticsMonthDate.replace('-', '') : ''
    },
    previousMonth() {
      if (!this.trendRows || this.trendRows.length < 2) return null
      return this.trendRows[this.trendRows.length - 2]
    },
    previousMonthLabel() {
      return this.previousMonth ? this.previousMonth.periodLabel : '上月'
    },
    compareBarMetrics() {
      const prev = this.previousMonth
      const curr = this.current
      if (!curr) return []
      const defs = [
        { key: 'activeCount', label: '常到店', color: '#22c55e' },
        { key: 'warnCount', label: '预警客', color: '#f59e0b' },
        { key: 'grayCount', label: '灰客', color: '#94a3b8' },
        { key: 'blackCount', label: '黑客', color: '#475569' }
      ]
      const rows = defs.map(d => {
        const p = prev ? Number(prev[d.key] || 0) : 0
        const c = Number(curr[d.key] || 0)
        const diff = c - p
        const trend = diff > 0 ? 'up' : diff < 0 ? 'down' : 'flat'
        return {
          ...d,
          prev: p,
          curr: c,
          diff,
          trend,
          trendIcon: trend === 'up' ? 'el-icon-top' : trend === 'down' ? 'el-icon-bottom' : 'el-icon-minus',
          diffText: diff > 0 ? `+${diff}` : diff < 0 ? `${diff}` : '持平'
        }
      })
      const maxVal = Math.max(...rows.flatMap(r => [r.prev, r.curr]), 1)
      return rows.map(r => ({
        ...r,
        prevHeight: Math.max(10, Math.round((r.prev / maxVal) * 100)),
        currHeight: Math.max(10, Math.round((r.curr / maxVal) * 100))
      }))
    },
    sparklineSeries() {
      if (!this.trendRows || this.trendRows.length < 2) return []
      const defs = [
        { key: 'totalCount', label: '总人数', color: '#059669' },
        { key: 'activeCount', label: '常到店', color: '#22c55e' },
        { key: 'warnCount', label: '预警客', color: '#f59e0b' },
        { key: 'blackCount', label: '黑客', color: '#475569' }
      ]
      return defs.map(d => this.buildSparkline(d.key, d.label, d.color))
    },
    summaryCards() {
      const c = this.current
      if (!c) return []
      const d = c.delta || {}
      const fmt = (inc, dec, net) => {
        if (!c.delta) return { text: '', cls: '', trend: '' }
        const trend = net > 0 ? 'up' : net < 0 ? 'down' : 'flat'
        if (inc > 0 && dec > 0) return { text: `+${inc} / -${dec}`, cls: 'delta-mix', trend }
        if (net > 0) return { text: `+${net}`, cls: 'delta-up', trend: 'up' }
        if (net < 0) return { text: `${net}`, cls: 'delta-down', trend: 'down' }
        return { text: '持平', cls: 'delta-flat', trend: 'flat' }
      }
      const items = [
        { key: 'total', label: '总人数', value: c.totalCount, inc: d.totalIncrease, dec: d.totalDecrease, net: c.totalCount - (this.previousMonth ? this.previousMonth.totalCount : c.totalCount) },
        { key: 'new', label: '新客', value: c.newCustomerCount, inc: d.newCustomerIncrease, dec: d.newCustomerDecrease, net: c.newCustomerCount - (this.previousMonth ? this.previousMonth.newCustomerCount : c.newCustomerCount) },
        { key: 'active', label: '常到店', value: c.activeCount, inc: d.activeIncrease, dec: d.activeDecrease, net: c.activeCount - (this.previousMonth ? this.previousMonth.activeCount : c.activeCount) },
        { key: 'warn', label: '预警客', value: c.warnCount, inc: d.warnIncrease, dec: d.warnDecrease, net: c.warnCount - (this.previousMonth ? this.previousMonth.warnCount : c.warnCount) },
        { key: 'gray', label: '灰客', value: c.grayCount, inc: d.grayIncrease, dec: d.grayDecrease, net: c.grayCount - (this.previousMonth ? this.previousMonth.grayCount : c.grayCount) },
        { key: 'black', label: '黑客', value: c.blackCount, inc: d.blackIncrease, dec: d.blackDecrease, net: c.blackCount - (this.previousMonth ? this.previousMonth.blackCount : c.blackCount) },
        { key: 'refund', label: '退款', value: c.refundCount, inc: d.refundIncrease, dec: d.refundDecrease, net: c.refundCount - (this.previousMonth ? this.previousMonth.refundCount : c.refundCount) }
      ]
      return items.map(item => {
        const delta = fmt(item.inc, item.dec, item.net)
        return { ...item, deltaShort: delta.text, deltaClass: delta.cls, trend: delta.trend }
      })
    },
    tierStructure() {
      const c = this.current
      if (!c) return []
      const base = c.activeCount + c.warnCount + c.grayCount + c.blackCount
      const total = base > 0 ? base : 1
      const pct = n => Math.round((n / total) * 1000) / 10
      return [
        { key: 'active', label: '常到店', count: c.activeCount, pct: pct(c.activeCount), color: '#22c55e' },
        { key: 'warn', label: '预警客', count: c.warnCount, pct: pct(c.warnCount), color: '#f59e0b' },
        { key: 'gray', label: '灰客', count: c.grayCount, pct: pct(c.grayCount), color: '#94a3b8' },
        { key: 'black', label: '黑客', count: c.blackCount, pct: pct(c.blackCount), color: '#475569' }
      ].filter(seg => seg.count > 0 || seg.key === 'active')
    },
    deltaRows() {
      const c = this.current
      if (!c || !c.delta) return []
      const d = c.delta
      const row = (key, label, ending, incKey, decKey) => ({
        key,
        label,
        ending,
        increase: d[incKey] || 0,
        decrease: d[decKey] || 0
      })
      return [
        row('total', '总人数', c.totalCount, 'totalIncrease', 'totalDecrease'),
        row('new', '新客', c.newCustomerCount, 'newCustomerIncrease', 'newCustomerDecrease'),
        row('active', '常到店', c.activeCount, 'activeIncrease', 'activeDecrease'),
        row('warn', '预警客', c.warnCount, 'warnIncrease', 'warnDecrease'),
        row('gray', '灰客', c.grayCount, 'grayIncrease', 'grayDecrease'),
        row('black', '黑客', c.blackCount, 'blackIncrease', 'blackDecrease'),
        row('refund', '退款', c.refundCount, 'refundIncrease', 'refundDecrease')
      ]
    }
  },
  methods: {
    tableRowClassName({ rowIndex }) {
      return rowIndex === this.trendRows.length - 1 ? 'row-current-month' : ''
    },
    buildSparkline(fieldKey, label, color) {
      const rows = this.trendRows || []
      const values = rows.map(r => Number(r[fieldKey] || 0))
      const labels = rows.map(r => {
        const text = r.periodLabel || ''
        const m = text.match(/(\d+)月/)
        return m ? `${m[1]}月` : text.slice(-4)
      })
      const min = Math.min(...values)
      const max = Math.max(...values)
      const span = max - min || 1
      const w = 280
      const h = 72
      const padX = 10
      const padY = 10
      const step = rows.length > 1 ? (w - padX * 2) / (rows.length - 1) : 0
      const dots = values.map((v, i) => ({
        x: padX + step * i,
        y: h - padY - ((v - min) / span) * (h - padY * 2)
      }))
      const linePoints = dots.map(p => `${p.x},${p.y}`).join(' ')
      const areaPoints = `${padX},${h - padY} ${linePoints} ${padX + step * (rows.length - 1)},${h - padY}`
      const diff = values[values.length - 1] - values[0]
      const trend = diff > 0 ? 'up' : diff < 0 ? 'down' : 'flat'
      return {
        key: fieldKey,
        label,
        color,
        dots,
        linePoints,
        areaPoints,
        labels,
        trend,
        trendIcon: trend === 'up' ? 'el-icon-top' : trend === 'down' ? 'el-icon-bottom' : 'el-icon-minus',
        changeText: diff > 0 ? `+${diff}` : diff < 0 ? `${diff}` : '持平'
      }
    },
    handleOpened() {
      this.fetchData()
    },
    normalizeItem(item) {
      if (!item) return null
      return {
        periodLabel: item.periodLabel || item.PeriodLabel || '',
        storeId: item.storeId || item.StoreId || '',
        storeName: item.storeName || item.StoreName || '',
        totalCount: Number(item.totalCount ?? item.TotalCount ?? 0),
        newCustomerCount: Number(item.newCustomerCount ?? item.NewCustomerCount ?? 0),
        activeCount: Number(item.activeCount ?? item.ActiveCount ?? 0),
        warnCount: Number(item.warnCount ?? item.WarnCount ?? 0),
        grayCount: Number(item.grayCount ?? item.GrayCount ?? 0),
        blackCount: Number(item.blackCount ?? item.BlackCount ?? 0),
        refundCount: Number(item.refundCount ?? item.RefundCount ?? 0),
        delta: this.normalizeDelta(item.delta || item.Delta)
      }
    },
    normalizeDelta(d) {
      if (!d) return null
      const pick = (a, b) => d[a] ?? d[b] ?? 0
      return {
        totalIncrease: pick('totalIncrease', 'TotalIncrease'),
        totalDecrease: pick('totalDecrease', 'TotalDecrease'),
        newCustomerIncrease: pick('newCustomerIncrease', 'NewCustomerIncrease'),
        newCustomerDecrease: pick('newCustomerDecrease', 'NewCustomerDecrease'),
        activeIncrease: pick('activeIncrease', 'ActiveIncrease'),
        activeDecrease: pick('activeDecrease', 'ActiveDecrease'),
        warnIncrease: pick('warnIncrease', 'WarnIncrease'),
        warnDecrease: pick('warnDecrease', 'WarnDecrease'),
        grayIncrease: pick('grayIncrease', 'GrayIncrease'),
        grayDecrease: pick('grayDecrease', 'GrayDecrease'),
        blackIncrease: pick('blackIncrease', 'BlackIncrease'),
        blackDecrease: pick('blackDecrease', 'BlackDecrease'),
        refundIncrease: pick('refundIncrease', 'RefundIncrease'),
        refundDecrease: pick('refundDecrease', 'RefundDecrease')
      }
    },
    async fetchData() {
      if (!this.storeId || !this.statisticsMonth) return
      try {
        this.loading = true
        const res = await getMemberTierStatistics({
          storeId: this.storeId,
          statisticsMonth: this.statisticsMonth,
          includeMonthCompare: true,
          trendMonthCount: 6
        })
        const data = res && res.data ? res.data : {}
        this.current = this.normalizeItem(data.current || data.Current)
        const trend = data.trend || data.Trend || []
        this.trendRows = trend.map(item => this.normalizeItem(item)).filter(Boolean)
      } catch (e) {
        console.error('[会员分层] 加载失败', e)
        this.current = null
        this.trendRows = []
      } finally {
        this.loading = false
      }
    },
    exportCsv() {
      if (!this.trendRows.length) return
      const lines = [['截止月份', '门店ID', '门店名称', '总人数', '新客', '常到店', '预警客', '灰客', '黑客', '退款'].join(',')]
      this.trendRows.forEach(row => {
        lines.push([
          row.periodLabel,
          row.storeId,
          `"${(row.storeName || '').replace(/"/g, '""')}"`,
          row.totalCount,
          row.newCustomerCount,
          row.activeCount,
          row.warnCount,
          row.grayCount,
          row.blackCount,
          row.refundCount
        ].join(','))
      })
      const blob = new Blob(['\ufeff' + lines.join('\n')], { type: 'text/csv;charset=utf-8;' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `门店会员分层统计_${this.statisticsMonth}_${this.storeName || '门店'}.csv`
      a.click()
      URL.revokeObjectURL(url)
    }
  }
}
</script>

<style lang="scss">
.member-tier-report-dialog {
  border-radius: 14px;
  overflow: hidden;
  margin-top: 2vh !important;
  margin-bottom: 2vh !important;
  box-shadow: 0 24px 48px rgba(15, 23, 42, 0.12);

  .el-dialog__header {
    display: none;
  }

  .el-dialog__body {
    padding: 0;
    max-height: 96vh;
    overflow: hidden;
  }

  .report-table {
    .el-table__header th {
      padding: 8px 0;
      font-size: 13px;
    }

    .el-table__body td {
      padding: 6px 0;
      font-size: 13px;
    }

    .cell {
      padding-left: 10px !important;
      padding-right: 10px !important;
    }

    .row-current-month td {
      background: #ecfdf5 !important;
      font-weight: 600;
    }
  }
}
</style>

<style lang="scss" scoped>
.dialog-inner {
  padding: 16px 22px 14px;
  background: #fff;
  height: calc(96vh - 4px);
  max-height: 1040px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-sizing: border-box;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  margin-bottom: 14px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f1f5f9;
  flex-shrink: 0;
}

.header-left {
  min-width: 0;
}

.dialog-title {
  font-size: 18px;
  font-weight: 700;
  color: #14532d;
}

.dialog-sub {
  margin-top: 4px;
  font-size: 13px;
  color: #64748b;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-shrink: 0;
}

.dialog-close {
  cursor: pointer;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  color: #64748b;

  &:hover {
    background: #f1f5f9;
    color: #334155;
  }
}

.summary-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 10px;
  margin-bottom: 12px;
  flex-shrink: 0;
}

.summary-card {
  border-radius: 12px;
  padding: 12px 10px;
  text-align: center;
  min-width: 0;
  border: 1px solid transparent;
}

.summary-card--total { background: #ecfdf5; border-color: #bbf7d0; }
.summary-card--new { background: #f0fdf4; border-color: #bbf7d0; }
.summary-card--active { background: #fdf2f8; border-color: #fbcfe8; }
.summary-card--warn { background: #fffbeb; border-color: #fde68a; }
.summary-card--gray { background: #f0fdf4; border-color: #bbf7d0; }
.summary-card--black { background: #f0fdfa; border-color: #99f6e4; }
.summary-card--refund { background: #f8fafc; border-color: #e2e8f0; }

.card-label {
  font-size: 13px;
  color: #64748b;
  white-space: nowrap;
}

.card-value {
  margin-top: 6px;
  font-size: 24px;
  font-weight: 700;
  color: #0f172a;
  line-height: 1.1;
}

.card-delta {
  margin-top: 4px;
  font-size: 13px;
  font-weight: 600;
}

.delta-up { color: #16a34a; }
.delta-down { color: #dc2626; }
.delta-flat { color: #94a3b8; }
.delta-mix { color: #d97706; }

.report-sections {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.section-panel {
  background: #fafafa;
  border: 1px solid #f1f5f9;
  border-radius: 12px;
  padding: 14px 16px;
  flex-shrink: 0;
}

.section-panel--table {
  padding-bottom: 10px;
}

.section-head {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  gap: 12px;
}

.section-title {
  font-size: 15px;
  font-weight: 600;
  color: #334155;
}

.section-meta {
  font-size: 12px;
  color: #94a3b8;
  display: inline-flex;
  align-items: center;
  gap: 12px;
}

.legend-swatch {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 2px;
  margin-right: 4px;
  vertical-align: -1px;
}

.legend-swatch--prev { background: #cbd5e1; }
.legend-swatch--curr { background: #059669; }

.compare-bar-chart {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
}

.compare-bar-group {
  background: #fff;
  border: 1px solid #e2e8f0;
  border-radius: 10px;
  padding: 12px 10px 10px;
}

.compare-bar-label {
  text-align: center;
  font-size: 13px;
  color: #64748b;
  margin-bottom: 10px;
}

.compare-bar-track {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  gap: 16px;
  height: 100px;
}

.compare-bar-col {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
  height: 100%;
  width: 36px;
}

.compare-bar {
  width: 100%;
  border-radius: 6px 6px 2px 2px;
  min-height: 6px;
}

.compare-bar--prev { opacity: 0.45; }

.compare-bar-num {
  margin-top: 6px;
  font-size: 13px;
  color: #64748b;
  font-weight: 600;

  &.is-current {
    color: #0f172a;
    font-weight: 700;
  }
}

.compare-bar-diff {
  margin-top: 8px;
  text-align: center;
  font-size: 13px;
  font-weight: 700;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 3px;

  &.is-up { color: #16a34a; }
  &.is-down { color: #dc2626; }
  &.is-flat { color: #94a3b8; }
}

.sparkline-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.sparkline-card {
  background: #fff;
  border: 1px solid #e2e8f0;
  border-radius: 10px;
  padding: 12px 14px 10px;
}

.sparkline-head {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.sparkline-label {
  font-size: 14px;
  color: #475569;
  font-weight: 600;
}

.sparkline-change {
  font-size: 13px;
  font-weight: 700;
  display: inline-flex;
  align-items: center;
  gap: 2px;

  &.is-up { color: #16a34a; }
  &.is-down { color: #dc2626; }
  &.is-flat { color: #94a3b8; }
}

.sparkline-chart-area {
  width: 100%;
}

.sparkline-svg {
  width: 100%;
  height: auto;
  aspect-ratio: 280 / 72;
  display: block;
}

.sparkline-axis {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #94a3b8;
  margin-top: 6px;

  &--full {
    justify-content: space-between;
    gap: 4px;
  }
}

.report-table {
  width: 100%;
}

.footer-split {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.structure-bar {
  display: flex;
  height: 16px;
  border-radius: 999px;
  overflow: hidden;
  background: #e2e8f0;
  margin-bottom: 14px;
}

.structure-seg {
  min-width: 2px;
}

.structure-legend {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px 16px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: #475569;
}

.legend-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  flex-shrink: 0;
}

.legend-label {
  flex: 1;
}

.legend-count {
  font-weight: 700;
  color: #0f172a;
}

.legend-pct {
  color: #94a3b8;
  min-width: 44px;
  text-align: right;
}

.delta-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.delta-cell {
  background: #fff;
  border: 1px solid #e2e8f0;
  border-radius: 10px;
  padding: 10px 12px;
}

.delta-cell-label {
  font-size: 13px;
  color: #64748b;
}

.delta-cell-ending {
  margin-top: 4px;
  font-size: 18px;
  font-weight: 700;
  color: #0f172a;
}

.delta-cell-change {
  margin-top: 6px;
  font-size: 13px;
  font-weight: 600;
}

.change-up { color: #16a34a; margin-right: 8px; }
.change-down { color: #dc2626; }
.change-flat { color: #94a3b8; }

.change-up i,
.change-down i,
.change-flat i {
  margin-right: 3px;
}

.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #94a3b8;
  font-size: 15px;
}

.rule-tip {
  flex-shrink: 0;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #f1f5f9;
  font-size: 12px;
  color: #94a3b8;
  text-align: center;
  line-height: 1.4;
}
</style>
