<template>
  <div class="pc-sports-list-container">
    <div class="list-wrapper layout-column">
      
      <div class="sticky-tabs" v-if="dateTabs.length > 0">
        <el-scrollbar>
          <div class="segmented-control-wrapper">
            <div class="segmented-control">
              <div
                class="segmented-item"
                v-for="(date, index) in dateTabs"
                :key="index"
                :class="{ 'is-active': activeDateTab === date }"
                @click="scrollToDate(date)"
              >
                <span class="tab-text">{{ formatDateTab(date) }}</span>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>

      <div class="right-content">
        <div class="match-list-body">
          <el-scrollbar height="100%" ref="scrollbarRef">
            <el-skeleton :loading="skeletonLoading" animated>
              <template #template>
                <div class="match-card" v-for="i in 5" :key="i">
                  <div class="match-card-header">
                    <div class="league-info">
                      <div class="decorate-bar"></div>
                      <el-skeleton-item variant="circle" style="width: 16px; height: 16px; margin-right: 6px;" />
                      <el-skeleton-item variant="text" style="width: 80px;" />
                    </div>
                    <div class="match-status-time">
                      <el-skeleton-item variant="text" style="width: 40px; margin-right: 8px;" />
                      <el-skeleton-item variant="text" style="width: 100px;" />
                    </div>
                  </div>

                  <div class="match-card-main">
                    <div class="match-teams">
                      <div class="team-row">
                        <div class="team-info">
                          <el-skeleton-item variant="circle" style="width: 18px; height: 18px;" />
                          <el-skeleton-item variant="text" style="width: 60px; margin-left: 6px;" />
                        </div>
                        <el-skeleton-item variant="text" style="width: 20px;" />
                      </div>
                      <div class="team-row mt-3">
                        <div class="team-info">
                          <el-skeleton-item variant="circle" style="width: 18px; height: 18px;" />
                          <el-skeleton-item variant="text" style="width: 80px; margin-left: 6px;" />
                        </div>
                        <el-skeleton-item variant="text" style="width: 20px;" />
                      </div>
                    </div>

                    <div class="match-odds-grids">
                      <div class="market-col" v-for="j in 3" :key="j">
                        <div style="display: flex; justify-content: center;">
                          <el-skeleton-item variant="text" style="width: 60px; margin-bottom: 4px;" />
                        </div>
                        <div class="market-values">
                          <el-skeleton-item variant="button" class="odds-btn" style="border: none;" v-for="k in 3" :key="k" />
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </template>

              <template #default>
                <div>
                  <div class="match-card" v-for="item in sportList" :key="item.data_id || item.id" :id="'match-' + (item.data_id || item.id)" v-show="item.league_id === 1">

                    <div class="match-card-header">
                      <div class="league-info">
                        <div class="decorate-bar"></div>
                        <el-avatar v-if="item.league_logo" :src="item.league_logo" :size="16" style="margin-right: 6px; background-color: transparent;"></el-avatar>
                        <span class="league-name" :title="locale === 'zh' ? item.league : item.league_en">{{ locale === 'zh' ? item.league : item.league_en }}</span>
                        <el-tag style="margin-left: 10px" size="small" v-if="item.state === 1 && item.fixture_status">
                          {{ t(item.fixture_status?.long) }}
                        </el-tag>
                        <el-tag v-if="item.is_roll === 1" style="margin-left: 10px">{{ t('滚球') }}</el-tag>
                        <span v-if="item.state === 1" style="font-size: 12px;color: #999;margin-left: 10px">
                          <template v-if="item.fixture_status">
                            {{ item.fixture_status?.seconds }}
                          </template>
                        </span>
                      </div>
                      <div class="match-status-time">
                        <span style="font-size: 13px;color: #999">
                          {{ item.game_time || '--:--' }}
                        </span>
                      </div>
                    </div>

                    <div class="match-card-main" @click="goDetail(item)">
                      <div class="match-teams">
                        <div class="team-row">
                          <div style="display: flex;align-items: center;gap: 6px;">
                            <div class="team-info">
                              <el-avatar :src="item.home_team_logo" :size="24" class="team-logo"></el-avatar>
                              <span class="team-name" :title="locale === 'zh' ? item.home_team : item.home_team_en">
                                {{ locale === 'zh' ? item.home_team : item.home_team_en }}
                              </span>
                            </div>
                            <el-tag size="small" type="success">{{ t('主') }}</el-tag>
                          </div>
                          <span class="team-score" v-if="item.state !== 0" :class="{'text-live': item.state === 1}">
                            {{ getScore(item.score, 0) }}
                          </span>
                        </div>

                        <div class="team-row mt-3">
                          <div style="display: flex;align-items: center;gap: 6px;">
                            <div class="team-info">
                              <el-avatar :src="item.guest_team_logo" :size="24" class="team-logo"></el-avatar>
                              <span class="team-name" :title="locale === 'zh' ? item.guest_team : item.guest_team_en">{{ locale === 'zh' ? item.guest_team : item.guest_team_en }}</span>
                            </div>
                            <el-tag size="small" type="danger">{{ t('客') }}</el-tag>
                          </div>
                          <span class="team-score" v-if="item.state !== 0" :class="{'text-live': item.state === 1}">
                            {{ getScore(item.score, 1) }}
                          </span>
                        </div>
                      </div>

                      <div class="match-odds-grids">
                        <template v-if="[0, 1].includes(item.state) && item.odds && item.odds.length > 0">
                          <div class="market-col" v-for="(market, m) in item.odds.slice(0, 3)" :key="market.id">
                            <div class="market-name" :title="locale === 'zh' ? market.name : market.name_en">{{ locale === 'zh' ? market.name : market.name_en }}</div>

                            <div class="preview-pair-headers" v-if="hasPairHeaders(market) || isThreeWayHAD(market)">
                              <template v-if="isThreeWayHAD(market)">
                                <div class="preview-pair-item">{{ getThreeWayHeaders(market)[0] }}</div>
                                <div class="preview-pair-item">{{ getThreeWayHeaders(market)[1] }}</div>
                                <div class="preview-pair-item">{{ getThreeWayHeaders(market)[2] }}</div>
                              </template>
                              <template v-else>
                                <div class="preview-pair-item">{{ getPairHeaders(market)[0] }}</div>
                                <div class="preview-pair-item">{{ getPairHeaders(market)[1] }}</div>
                              </template>
                            </div>
                            <div class="preview-pair-headers" v-else></div> 
                            <div :class="['market-values', m > 0 ? 'market-values-border-left' : '']">
                              <div
                                  class="odds-btn"
                                  v-for="(opt, optIndex) in getPreviewMarketValues(market)"
                                  :key="optIndex"
                                  :class="{
                                    'is-locked': item.is_locked || opt.suspended || !opt.odd || market.is_findLocked,
                                    'is-active': isSelected(item.id, market.id, opt),
                                    'odds-up': isOddsUp(getOddsKey(item.id, market.id, opt)),
                                    'odds-down': isOddsDown(getOddsKey(item.id, market.id, opt)),
                                    'is-centered-odds': isHeaderValue(market, opt.value) && !opt.handicap_text
                                  }"
                                  :style="{
                                    flexDirection: Boolean(!opt.odd || opt.suspended || item.is_locked || market.is_findLocked) ? 'column' : 'row',
                                  }"
                                  @click.stop="handleOddsClick(item, market, opt)"
                              >
                                <div class="odds-name-wrapper" v-if="!isHeaderValue(market, opt.value) || opt.handicap_text">
                                  <span class="selection-name" style="margin-right: 4px" v-if="!isHeaderValue(market, opt.value)" :title="locale === 'zh' ? opt.value_text : opt.value">
                                    {{ translateSelection(locale === 'zh' ? opt.value_text : opt.value) }}
                                  </span>
                                  <span class="handicap-val" v-if="opt.handicap_text">{{ opt.handicap_text }}</span>
                                </div>

                                <div class="odds-val-wrapper">
                                  <el-icon v-if="!opt.odd || opt.suspended || item.is_locked || market.is_findLocked" class="lock-icon"><Lock /></el-icon>
                                  <span v-else class="odds-val">
                                    <span>{{ opt.odd || opt.odd === 0 ? opt.odd : '-' }}</span>
                                    <span v-if="showChangeIcon(getOddsKey(item.id, market.id, opt))"
                                          class="change-icon"
                                          :class="isOddsUp(getOddsKey(item.id, market.id, opt)) ? 'up' : 'down'">
                                       <el-icon v-show="isOddsUp(getOddsKey(item.id, market.id, opt))"><CaretTop /></el-icon>
                                      <el-icon v-show="!isOddsUp(getOddsKey(item.id, market.id, opt))"><CaretBottom /></el-icon>
                                    </span>
                                  </span>
                                </div>
                              </div>
                            </div>
                          </div>
                        </template>

                        <div class="empty-odds-tip" v-else>
                          <span class="empty-text" v-if="item.state !== 2">{{ t('暂无盘口数据') }}</span>
                          <span class="empty-text" v-else>{{ t('已完场') }}</span>
                        </div>
                      </div>
                    </div>
                  </div>

                  <el-empty v-if="sportList.length === 0" :description="t('暂无赛事数据')" />
                </div>
              </template>
            </el-skeleton>
          </el-scrollbar>
        </div>
      </div>
    </div>

    <pcFooter  />

  </div>
</template>

<script setup>
defineOptions({
  name: 'SportsBettingList'
})

import { ref, watch, computed, onMounted, onActivated, onUnmounted, nextTick } from "vue"
import { useRouter } from "vue-router"
import { useI18n } from "vue-i18n"
import { getWorldCupSport } from "@/request/api.js"
import { useOrderStore } from "@/store/bettingSheet.js"
import { Lock, CaretBottom, CaretTop } from '@element-plus/icons-vue'
import socket from '@/utils/websocket.js'
import pcFooter from '@/businessComponents/pcFooter/index.vue'

import { threeColMarkets, pairPriority } from '@/views/SportsBetting/config.js';

const { t, locale } = useI18n()
const router = useRouter()
const orderStore = useOrderStore()

const skeletonLoading = ref(true)
const sportList = ref([])
const scrollbarRef = ref(null)

const selectedMap = ref({})

// === 提取日期与原生的锚点逻辑 ===
const activeDateTab = ref('');

const dateTabs = computed(() => {
  const dates = [];
  const dateSet = new Set();
  sportList.value.forEach(item => {
    if (item.game_time) {
      const datePart = item.game_time.split(' ')[0]; // 截取年月日
      if (!dateSet.has(datePart)) {
        dateSet.add(datePart);
        dates.push(datePart);
      }
    }
  });
  return dates;
});

watch(dateTabs, (newVal) => {
  if (newVal.length > 0 && !activeDateTab.value) {
    activeDateTab.value = newVal[0];
  }
});

const scrollToDate = (datePart) => {
  activeDateTab.value = datePart;
  const targetItem = sportList.value.find(item => item.game_time && item.game_time.split(' ')[0] === datePart);
  if (targetItem) {
    const elId = 'match-' + (targetItem.data_id || targetItem.id);
    const el = document.getElementById(elId);
    if (el) {
      el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  }
};

// 格式化日期：MM/DD 周几，若为今天则返回 "今天"
const formatDateTab = (dateStr) => {
  if (!dateStr) return '';
  const [year, month, day] = dateStr.split('-');
  const dateObj = new Date(dateStr.replace(/-/g, '/'));
  const daysArr = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  const dayOfWeek = daysArr[dateObj.getDay()];

  const today = new Date();
  const isToday =
    today.getFullYear() === parseInt(year) &&
    today.getMonth() + 1 === parseInt(month) &&
    today.getDate() === parseInt(day);

  if (isToday) {
    return t('今天');
  }
  return `${month}/${day} ${t(dayOfWeek)}`;
};
// =========================

// ====================== 基础工具方法 ======================
const isThreeWayHAD = (market) => {
  if (!market || !market.values) return false;
  const hasHome = market.values.some(v => ['Home', '1'].includes(v.value));
  const hasDraw = market.values.some(v => ['Draw', 'X'].includes(v.value));
  const hasAway = market.values.some(v => ['Away', '2'].includes(v.value));
  return hasHome && hasDraw && hasAway;
};

const getThreeWayHeaders = (market) => {
  if (!market || !market.values) return ['', '', ''];
  let home = '', draw = '', away = '';
  for (const v of market.values) {
    if (!home && ['Home', '1'].includes(v.value)) {
      home = translateSelection(locale.value === 'zh' ? v.value_text : v.value);
    } else if (!draw && ['Draw', 'X'].includes(v.value)) {
      draw = translateSelection(locale.value === 'zh' ? v.value_text : v.value);
    } else if (!away && ['Away', '2'].includes(v.value)) {
      away = translateSelection(locale.value === 'zh' ? v.value_text : v.value);
    }
  }
  return [home, draw, away];
};

const isHeaderValue = (market, val) => {
  if (isThreeWayHAD(market)) {
    return ['Home', '1', 'Draw', 'X', 'Away', '2'].includes(val);
  }
  return hasPairHeaders(market) && pairPriority[val];
};

const getUniqueKey = (matchId, marketId, selection) => {
  if (selection.handicap !== null && selection.handicap !== undefined && selection.handicap !== '') {
    return `${matchId}_${marketId}_${selection.value}_${selection.handicap}`;
  }
  return `${matchId}_${marketId}_${selection.value}`;
};

const getPairHeaders = (market) => {
  if (!market || !market.values) return ['', ''];
  let left = '';
  let right = '';
  for (const v of market.values) {
    if (pairPriority[v.value] === 1 && !left) {
      left = translateSelection(locale.value === 'zh' ? v.value_text : v.value);
    } else if (pairPriority[v.value] === 2 && !right) {
      right = translateSelection(locale.value === 'zh' ? v.value_text : v.value);
    }
  }
  return [left, right];
};

const hasPairHeaders = (market) => {
  if (threeColMarkets.includes(market.name_en)) return false;
  if (isThreeWayHAD(market)) return false; 
  const headers = getPairHeaders(market);
  return !!(headers[0] || headers[1]);
};

const zipperSort = (market, values) => {
  if (!values) return [];
  if (threeColMarkets.includes(market.name_en)) return values;
  
  if (isThreeWayHAD(market)) {
    const homes = [], draws = [], aways = [], others = [];
    values.forEach(v => {
      if (['Home', '1'].includes(v.value)) homes.push(v);
      else if (['Draw', 'X'].includes(v.value)) draws.push(v);
      else if (['Away', '2'].includes(v.value)) aways.push(v);
      else others.push(v);
    });
    let sortedValues = [];
    const maxLen = Math.max(homes.length, draws.length, aways.length);
    for (let i = 0; i < maxLen; i++) {
      if (homes[i]) sortedValues.push(homes[i]);
      if (draws[i]) sortedValues.push(draws[i]);
      if (aways[i]) sortedValues.push(aways[i]);
    }
    return sortedValues.concat(others);
  }
  
  const lefts = [];
  const rights = [];
  const others = [];
  
  values.forEach(v => {
    const p = pairPriority[v.value];
    if (p === 1) lefts.push(v);
    else if (p === 2) rights.push(v);
    else others.push(v);
  });

  let sortedValues = [];
  if (lefts.length > 0 || rights.length > 0) {
    const maxLen = Math.max(lefts.length, rights.length);
    for (let i = 0; i < maxLen; i++) {
      if (lefts[i]) sortedValues.push(lefts[i]);
      if (rights[i]) sortedValues.push(rights[i]);
    }
    sortedValues = sortedValues.concat(others);
  } else {
    sortedValues = [...values];
  }
  return sortedValues;
};

const getPreviewMarketValues = (market) => {
  const sorted = zipperSort(market, market.values);
  if (threeColMarkets.includes(market.name_en)) return sorted.slice(0, 3);
  if (isThreeWayHAD(market)) return sorted.slice(0, 3);
  return sorted.slice(0, 2);
};

// ====================== 赔率变化闪烁逻辑 ======================
const oddsChangeMap = ref(new Map()) 

const getOddsKey = (matchId, marketId, opt) => {
  if (opt.handicap !== null && opt.handicap !== undefined && opt.handicap !== '') {
    return `${matchId}_${marketId}_${opt.value}_${opt.handicap}`
  }
  return `${matchId}_${marketId}_${opt.value}`
}

const isOddsUp = (key) => {
  const change = oddsChangeMap.value.get(key)
  return change?.direction === 'up' && (Date.now() - change.timestamp < 3000)
}

const isOddsDown = (key) => {
  const change = oddsChangeMap.value.get(key)
  return change?.direction === 'down' && (Date.now() - change.timestamp < 3000)
}

const showChangeIcon = (key) => {
  const change = oddsChangeMap.value.get(key)
  return !!change && (Date.now() - change.timestamp < 3000)
}

// ========== WebSocket 实时刷新 ============
const handleSocketMessage = (e) => {
  const res = e.detail;
  if (!res || res.type !== 'sport_list' || !Array.isArray(res.message)) return;

  res.message.forEach((newMatch) => {
    if(newMatch.league_id !== 1) return
    const idx = sportList.value.findIndex(item => item.data_id === newMatch.data_id);

    if (idx !== -1) {
      const oldMatch = sportList.value[idx];

      if (newMatch.odds && Array.isArray(newMatch.odds) && oldMatch.odds && Array.isArray(oldMatch.odds)) {
        newMatch.odds.forEach(newMarket => {
          const oldMarket = oldMatch.odds.find(m => m.id === newMarket.id);
          if (oldMarket && oldMarket.values && newMarket.values) {
            newMarket.values.forEach(newOpt => {
              const oldOpt = oldMarket.values.find(o =>
                  o.value === newOpt.value &&
                  (o.handicap === newOpt.handicap || (!o.handicap && !newOpt.handicap))
              );

              if (oldOpt && oldOpt.odd && newOpt.odd) {
                const oldOddNum = parseFloat(oldOpt.odd);
                const newOddNum = parseFloat(newOpt.odd);

                if (!isNaN(oldOddNum) && !isNaN(newOddNum) && oldOddNum !== newOddNum) {
                  const key = getOddsKey(oldMatch.id, newMarket.id, newOpt);
                  const direction = newOddNum > oldOddNum ? 'up' : 'down';

                  oddsChangeMap.value.set(key, {
                    direction,
                    timestamp: Date.now()
                  });

                  let timer = setTimeout(() => {
                    oddsChangeMap.value.delete(key);
                    clearTimeout(timer);
                  }, 3100);
                }
              }
            });
          }
        });
      }

      newMatch.odds.forEach(jtem => {
        if (newMatch.odd_ids_locked && Array.isArray(newMatch.odd_ids_locked)) {
          if (newMatch.odd_ids_locked.find(trim => jtem.id === trim)) {
            jtem.is_findLocked = true;
          }
        }
      });

      sportList.value[idx] = { ...sportList.value[idx], ...newMatch };
      if (typeof orderStore.updateMatchStatus === 'function') {
        orderStore.updateMatchStatus(newMatch.data_id, newMatch);
      }
    } else {
      const isStatusOnline = newMatch.status === undefined || Number(newMatch.status) === 1;

      if (isStatusOnline) {
        let matchToInsert = { ...newMatch };
        if (typeof matchToInsert.odds === 'string') {
          try { matchToInsert.odds = JSON.parse(matchToInsert.odds); } catch (e) { matchToInsert.odds = []; }
        }

        if (matchToInsert.odds && Array.isArray(matchToInsert.odds)) {
          matchToInsert.odds.forEach(jtem => {
            if (matchToInsert.odd_ids_locked && Array.isArray(matchToInsert.odd_ids_locked)) {
              if (matchToInsert.odd_ids_locked.find(trim => jtem.id === trim)) {
                jtem.is_findLocked = true;
              }
            }
          });
        }

        sportList.value.push(matchToInsert);

        sportList.value.sort((a, b) => {
          const timeA = a.game_time ? new Date(a.game_time.replace(/-/g, '/')).getTime() : 0;
          const timeB = b.game_time ? new Date(b.game_time.replace(/-/g, '/')).getTime() : 0;
          return timeA - timeB;
        });
      }
    }
  });
};

onMounted(() => {
  syncFromStore();
  fetchData();
  socket.eventBus.addEventListener('onSocketMessage', handleSocketMessage);
});

onActivated(() => {
  syncFromStore();
});

onUnmounted(() => {
  socket.eventBus.removeEventListener('onSocketMessage', handleSocketMessage);
});

// ========== 初始化请求数据 ============
async function fetchData() {
  skeletonLoading.value = true;
  sportList.value = [];

  try {
    const res = await getWorldCupSport();
    
    if (res && res.code === 1 && res.data && res.data.list && res.data.list.length > 0) {
      const formatList = res.data.list.map(item => {
        if (typeof item.odds === 'string') {
          try { item.odds = JSON.parse(item.odds); } catch(e) { item.odds = []; }
        }
        if (item.odds && Array.isArray(item.odds)) {
          item.odds.forEach(jtem => {
            if (item.odd_ids_locked && Array.isArray(item.odd_ids_locked) && item.odd_ids_locked.find(trim => jtem.id === trim)) {
              jtem.is_findLocked = true;
            }
          });
        }
        return item;
      });
      sportList.value = formatList;

      // 根据接口返回的 extend.date 自动定位逻辑
      const extendDate = res.data.extend?.date;
      nextTick(() => {
        if (extendDate && dateTabs.value.length > 0) {
          // 寻找 date 之后（包含 date 当天），最近的一场未开始 (state === 0) 的比赛
          const targetMatch = sportList.value.find(item => {
            if (item.state === 0 && item.game_time) {
              const itemDate = item.game_time.split(' ')[0];
              return itemDate >= extendDate;
            }
            return false;
          });

          if (targetMatch) {
            // 定位到该比赛，并更新顶部高亮 tab
            const targetDatePart = targetMatch.game_time.split(' ')[0];
            activeDateTab.value = targetDatePart;
            const elId = 'match-' + (targetMatch.data_id || targetMatch.id);
            const el = document.getElementById(elId);
            if (el) {
              el.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
          } else {
            // 假如没有未开始的数据，则定位到最后一个日期
            const lastDate = dateTabs.value[dateTabs.value.length - 1];
            scrollToDate(lastDate);
          }
        }
      });
    }
  } catch (error) {
    console.error(error);
  } finally {
    skeletonLoading.value = false;
  }
}

const goDetail = (item) => {
  router.push({ name: 'SportDetail', query: { data_id: item.data_id } });
};

const getScore = (scoreStr, index) => {
  if (!scoreStr || scoreStr === '-') return '0';
  const parts = scoreStr.split('-');
  return parts[index] || '0';
};

const translateSelection = (valStr) => valStr === undefined || valStr === null ? '' : String(valStr);

const syncFromStore = () => {
  const map = {};
  if (orderStore.selectOrders && orderStore.selectOrders.length) {
    orderStore.selectOrders.forEach(order => {
      if (order.uniqueKey) map[order.uniqueKey] = true;
    });
  }
  selectedMap.value = map;
};

watch(() => orderStore.selectOrders, () => {
  syncFromStore();
}, { deep: true, immediate: true });

const isSelected = (matchId, marketId, selection) => {
  const uniqueKey = getUniqueKey(matchId, marketId, selection);
  return !!selectedMap.value[uniqueKey];
};

const handleOddsClick = (item, market, selection) => {
  if (item.state !== 0 && item.state !== 1) return;
  if (item.is_locked || market.is_findLocked) return;
  if (!selection || !selection.odd || selection.odd === '-') return;
  if (selection.suspended) return;

  const uniqueKey = getUniqueKey(item.id, market.id, selection);

  if (selectedMap.value[uniqueKey]) {
    orderStore.removeOrderItemByKey(uniqueKey);
  } else {
    const betItem = {
      matchId: item.id,
      data_id: item.data_id,
      league: item.league,
      league_en: item.league_en,
      homeTeam: item.home_team,
      home_team_en: item.home_team_en,
      guestTeam: item.guest_team,
      guest_team_en: item.guest_team_en,
      betType: market.name,
      betTypeEn: market.name_en,
      betTypeName: selection.value_text,
      betTypeNameEn: selection.value,
      handicap: selection.handicap,
      handicap_text: selection.handicap_text,
      odds: selection.odd,
      score: item.score,
      state: item.state,
      uniqueKey: uniqueKey,
      optionValue: selection.value,
      marketId: market.id,
      selection: {
        ...selection
      }
    };

    orderStore.addOrderItem(betItem);

    if (market.values) {
      market.values.forEach(wsItem => {
        const otherKey = getUniqueKey(item.id, market.id, wsItem);
        if (selectedMap.value[otherKey] && otherKey !== uniqueKey) {
          orderStore.removeOrderItemByKey(otherKey);
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
$main-color: #f8b932;
$card-bg: var(--el-bg-color-overlay);
$border-color: var(--el-border-color-lighter);
$hover-bg: var(--el-fill-color-light);

.pc-sports-list-container {
  container-type: inline-size;
  container-name: sports-list;
  height: 100%;
  padding: 6px 8px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  overflow-x: hidden;
  overflow-y: auto;
  @container sports-list (max-width: 800px) { padding: 4px; }
}

.layout-column {
  display: flex;
  flex-direction: column;
  width: 100%;
  flex: 1;
  gap: 8px;
  background-color: transparent;
  @container sports-list (max-width: 550px) { gap: 6px; }
}

/* === 新版分段控制器样式 (暗色背景如截图) === */
.sticky-tabs {
  background-color: $card-bg;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.5);
  padding: 10px 12px;
  flex-shrink: 0;
  position: sticky;
  top: -10px;
  z-index: 10;
}

.segmented-control-wrapper {
  display: flex;
  align-items: center;
}

.segmented-control {
  display: inline-flex;
  background-color: #2c2d30; /* 暗色容器背景 */
  border-radius: 6px; 
  padding: 4px;
}

.segmented-item {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 6px 20px;
  border-radius: 4px; 
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  
  .tab-text {
    font-size: 14px;
    color: #a0a0a0; /* 暗色底下的浅灰色文字 */
    transition: all 0.2s;
    white-space: nowrap; 
  }

  &:hover .tab-text {
    color: #ffffff;
  }

  &.is-active {
    background-color: $main-color; 
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);

    .tab-text {
      color: #ffffff;
      font-weight: bold;
    }
  }
}
/* === 样式结束 === */

.right-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
  height: calc(100% - 80px);
  overflow-y: auto;
  overflow-x: hidden;
}
.right-content::-webkit-scrollbar {
    display: none;
}

.match-list-body {
  flex: 1; height: 100%; display: flex; flex-direction: column;
  @container sports-list (max-width: 550px) { gap: 6px; padding-right: 0; }
  
  :deep(.el-scrollbar) {
    height: 100%;
  }
}

.match-card {
  background-color: $card-bg; border-radius: 6px; border: 1px solid $border-color; box-shadow: 0 1px 3px rgba(0,0,0,0.05); overflow: hidden; flex-shrink: 0; transition: border-color 0.2s; margin-bottom: 8px;
  &:hover { border-color: var(--el-border-color); .team-info { text-decoration: underline; } }

  .match-card-header {
    display: flex; justify-content: space-between; align-items: center;
    padding: 6px 12px;
    background-color: var(--el-fill-color-lighter); border-bottom: 1px solid $border-color;
    @container sports-list (max-width: 550px) { padding: 6px 10px; flex-wrap: wrap; gap: 4px; }
    .league-info {
      display: flex; align-items: center;
      .decorate-bar { width: 3px; height: 12px; background-color: $main-color; border-radius: 2px; margin-right: 6px; }
      .league-name { font-size: 12px; font-weight: bold; color: var(--el-text-color-primary); }
    }
    .match-status-time {
      display: flex; align-items: center;
      .time-text { font-size: 11px; color: var(--el-text-color-regular); font-family: monospace; }
      .timer-text { font-size: 11px; color: var(--el-color-danger); font-weight: bold; display: flex; align-items: center; gap: 4px; .live-dot { width: 4px; height: 4px; background-color: var(--el-color-danger); border-radius: 50%; animation: pulse 1.5s infinite; } }
      .el-tag { height: 18px; line-height: 16px; padding: 0 4px; font-size: 11px; border-radius: 2px; }
    }
  }

  .match-card-main {
    display: flex; align-items: stretch; cursor: pointer; background-color: transparent; transition: background-color 0.2s;
    &:hover { background-color: $hover-bg; }
    @container sports-list (max-width: 550px) { flex-direction: column; }

    .match-teams {
      width: 180px;
      flex-shrink: 0; padding: 8px 12px; border-right: 1px dashed $border-color; display: flex; flex-direction: column; justify-content: center;
      @container sports-list (max-width: 550px) { width: 100%; border-right: none; border-bottom: 1px dashed $border-color; padding: 8px; flex-direction: row; align-items: center; gap: 16px; }
      .team-row {
        display: flex; justify-content: space-between; align-items: center;
        @container sports-list (max-width: 550px) { flex: 1; }
        &.mt-3 { margin-top: 6px !important; @container sports-list (max-width: 550px) { margin-top: 0 !important; } }
        .team-info {
          display: flex; align-items: center; gap: 6px; flex: 1; overflow: hidden;
          .team-logo { background-color: transparent; }
          .team-name { font-size: 12px; font-weight: 500; color: var(--el-text-color-primary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; width: 100%; text-align: left; @container sports-list (max-width: 800px) { font-size: 11px; } }
        }
        .team-score { font-size: 14px; font-weight: 800; color: var(--el-text-color-primary); padding-left: 6px; &.text-live { color: $main-color; } }
      }
    }

    .match-odds-grids {
      flex: 1;
      padding: 8px 12px;
      display: grid; grid-template-columns: repeat(3, minmax(0, 1fr));
      gap: 20px;
      @container sports-list (max-width: 1200px) { gap: 20px; }
      @container sports-list (max-width: 800px) { padding: 6px 8px; gap: 20px; }
      @container sports-list (max-width: 1350px) {
        grid-template-columns: repeat(2, minmax(0, 1fr));
        .market-col:nth-child(n+3) { display: none; }
      }
      @container sports-list (max-width: 992px) {
        grid-template-columns: repeat(1, minmax(0, 1fr));
        .market-col:nth-child(n+2) { display: none; }
      }

      .market-col {
        display: flex; flex-direction: column;
        .market-name { font-size: 11px; color: var(--el-text-color-secondary); margin-bottom: 4px; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        
        .preview-pair-headers {
          display: flex; gap: 4px; width: 100%; margin-bottom: 4px;
          min-height: 16px; 
          .preview-pair-item {
            flex: 1; text-align: center; font-size: 11px; color: var(--el-text-color-secondary); line-height: 16px;
          }
        }

        .market-values { 
          display: flex; gap: 4px; width: 100%; 
          position: relative;
        }
        .market-values-border-left::before{
          content: '';
          position: absolute;
          left: -10px;
          width: 1px;
          height: 80%;
          top: 10%;
          background-color: $main-color;
          opacity: 0.5;
        }
      }
      .empty-odds-tip { grid-column: 1 / -1; display: flex; align-items: center; justify-content: center; padding-left: 10px; .empty-text { color: var(--el-text-color-placeholder); font-size: 12px; } }
    }
  }
}

.odds-btn {
  flex: 1;
   min-width: 0; 
   background-color: var(--el-fill-color); 
   border: 1px solid var(--el-border-color);
    border-radius: 4px;
  display: flex;
   justify-content: space-between; 
   align-items: center;
    padding: 6px 8px; 
    box-sizing: border-box;
  transition: all 0.2s; cursor: pointer; 
  position: relative; 
  overflow: hidden; 
  min-height: 40px;

  &.is-centered-odds {
    justify-content: center;
  }

  .odds-name-wrapper {
    display: flex;  align-items: center; min-width: 0; flex: 1; margin-right: 6px; z-index: 1;
    .selection-name {
      font-size: 12px; color: var(--el-text-color-primary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-align: left;
    }
    .handicap-val {
      font-size: 12px; color: var(--el-text-color-primary); font-weight: bold; margin-top: 2px;
    }
  }

  .odds-val-wrapper {
    display: flex; align-items: center; justify-content: flex-end; flex-shrink: 0; z-index: 1; gap: 4px;
    .odds-val {
      display: flex;
      align-items: center;
      font-size: 13px; font-weight: bold; color: $main-color;
    }
  }

  &:hover { border-color: $main-color; background-color: var(--el-fill-color-light); }
  &.is-active { background-color: $main-color; border-color: $main-color; .odds-name-wrapper .selection-name, .odds-name-wrapper .handicap-val, .odds-val-wrapper .odds-val { color: #fff; font-weight: bold } }
  &.is-locked { cursor: not-allowed; border-color: transparent; .selection-name, .handicap-val, .odds-val { opacity: 0.3; } &::after { content: ''; position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0, 0, 0, 0.4); z-index: 2; } .lock-icon { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: #fff; font-size: 14px; z-index: 3; } }

  &.odds-up .odds-val { color: #4caf50 !important; transition: color 0.3s; }
  &.odds-down .odds-val { color: #f56c6c !important; transition: color 0.3s; }

  .change-icon {
    margin-left: 4px; font-weight: bold; font-size: 14px;
    display: flex; align-items: center;
    &.up { color: #4caf50; }
    &.down { color: #f56c6c; }
  }
}

.market-values {
  container-type: inline-size;
  container-name: odds-wrapper;
  display: flex; gap: 4px; width: 100%;
}

@container odds-wrapper (max-width: 400px) {
  .odds-name-wrapper { align-items: center!important; margin-right: 0!important; }
}

@keyframes pulse { 0% { opacity: 1; } 50% { opacity: 0.4; } 100% { opacity: 1; } }

:deep(.el-avatar) {
  width: 18px !important; height: 18px !important;
  @container sports-list (max-width: 800px) { width: 16px !important; height: 16px !important; }
}
</style>