<template>
    <div class="page-scroll-container">
  <!--      <div v-if="skeletonLoading && !gamblingList.length" class="flex flex-col items-center justify-center py-6">-->
  <!--        <div class="refresh-spinner mb-2"></div>-->
  <!--        <span class="text-xs tmc">{{ t('正在更新内容...') }}</span>-->
  <!--      </div>-->

      <div style="padding: 5px 10px; box-sizing: border-box;">

        <div class="banner1-scroll pc-scroll-view">
          <div class="banner1-flex">
            <template v-if="skeletonLoading">
              <div class="banner1-item" v-for="i in 3" :key="'skeleton-banner-'+i">
                <div class="square-wrapper" style="display: flex; align-items: center; justify-content: center; background-color: #141414;">
                  <div class="skeleton-box"></div>
                </div>
              </div>
            </template>
            <template v-else>
              <div class="banner1-item" v-for="(item, i) in banners2" :key="i" @click="handleSwiper(i)">
                <div class="square-wrapper">
                  <img :src="item.image" style="width: 100%; height: 100%; object-fit: cover;" />
                </div>
              </div>
            </template>
          </div>
        </div>

        <div style="display: flex;align-items: center;margin-top: 10px">
          <div class="pc-notice-bar">
            <span>F1bet国际官宣：请认准官网F1bet.cc 永久网址：F1bet.cc</span>
          </div>
          <div class="url-right-badge">
            <el-icon><ChromeFilled /></el-icon>
            <span class="url-text animated-text">{{ animatedUrl }}</span>
          </div>
        </div>

        <div class="game-category-container">
          <div class="category-scroll pc-scroll-view">
            <div class="category-flex">
              <div class="category-item" v-for="(item, index) in categoryList" :key="index" @click="handleCategoryClick(item)">
                <img :src="item.icon" style="width: 26px; height: 26px; object-fit: contain;" />
                <span class="category-text">{{ item.name }}</span>
              </div>
            </div>
          </div>
        </div>

        <div class="roll-ball-section">
          <div class="roll-ball-header">
            <div class="header-left">
              <img :src="iconTy" style="width: 20px; height: 20px;" />
              <span class="roll-ball-title">{{ t('体育') }}</span>
            </div>
            <div class="more-roll-btn" @click="toMoreRollBall('SportsBetting')">
              <span class="more-text">{{ t('更多') }} >></span>
            </div>
          </div>

          <div class="sports-ball-scroll pc-scroll-view">
            <div class="sports-ball-flex">
              <div class="sport-ball-item" v-for="(item, index) in sportsBalls" :key="index" @click="handleSportBallClick(item)">
                <div class="ball-icon-wrapper">
                  <img :src="item.icon" style="width: 38px; height: 38px; object-fit: contain;" />
                  <div v-if="item.count" class="badge-count">{{ item.count }}</div>
                </div>
              </div>
            </div>
          </div>

          <div class="roll-ball-scroll pc-scroll-view">
            <div class="roll-ball-flex">
              <template v-if="skeletonLoading">
                <div class="match-card" v-for="i in 3" :key="i">
                  <div class="skeleton-box" style="height: 100px;"></div>
                </div>
              </template>
              <template v-else>
                <div class="match-card" v-for="(item, i) in gamblingList" :key="item.id" @click="goDetail(item)">
                  <div class="match-card-header">
                    <div class="league-left">
                      <img :src="item.league_logo" style="width: 16px; height: 16px; border-radius: 50%;" />
                      <span class="league-name">{{ locale === 'zh' ? item.league : item.league_en }}</span>
                    </div>

                    <div class="match-more-btn" @click.stop="goLeagueDetail(item)">
                      <span class="more-count">{{ item.sport_count || 0}}</span>
                      <i class="icon-arrow-right" style="color: #fff; font-size: 10px;"></i>
                    </div>
                  </div>

                  <div class="match-teams-container">
                    <div class="team-block">
                      <img :src="item.home_team_logo" style="width: 32px; height: 32px; border-radius: 50%;" />
                      <div class="team-name-group">
                        <span class="team-name">{{ locale === 'zh' ? item.home_team : item.home_team_en }}</span>
                        <span class="tag-home">{{ t('主') }}</span>
                      </div>
                    </div>

                    <div class="vs-block">
                      <span class="vs-text">VS</span>
                      <span class="match-time">{{ item.game_time || '--:--' }}</span>
                    </div>

                    <div class="team-block">
                      <img :src="item.guest_team_logo" style="width: 32px; height: 32px; border-radius: 50%;" />
                      <div class="team-name-group">
                        <span class="team-name">{{ locale === 'zh' ? item.guest_team : item.guest_team_en }}</span>
                        <span class="tag-away">{{ t('客') }}</span>
                      </div>
                    </div>
                  </div>

                  <div class="odds-group" v-if="[0, 1].includes(item.state)">
                    <template v-if="item.odds && item.odds.length > 0 && item.odds[0].values">
                      <div class="odds-grid">
                        <div
                            class="odds-btn"
                            v-for="(opt, optIndex) in getVisibleValues(item.odds[0].values)"
                            :key="optIndex"
                            :class="{
                              'is-locked': isOptionLocked(item, opt),
                              'is-active': isSelected(item.id, item.odds[0].id, opt),
                              'odds-up': isOddsUp(getOddsKey(item.id, item.odds[0].id, opt)) && !isOptionLocked(item, opt),
                              'odds-down': isOddsDown(getOddsKey(item.id, item.odds[0].id, opt)) && !isOptionLocked(item, opt)
                            }"
                            @click.stop="handleOddsClick(item, opt)"
                        >
                          <div class="locked-overlay" v-if="isOptionLocked(item, opt)">
                            <i class="icon-lock" style="color: #e0e0e0; font-size: 24px;"></i>
                          </div>

                          <span class="selection-name">{{ locale === 'zh' ? opt.value_text : translateSelection(opt.value) }}</span>
                          <span class="odds-val">{{ opt.odd || '-' }}</span>
                        </div>
                      </div>
                    </template>
                  </div>

                  <div class="match-footer-tip" v-else>
                    <span>{{ getStatusText(item.state) }}</span>
                  </div>
                </div>
              </template>
            </div>
          </div>
        </div>

        <div class="roll-ball-section">
          <div class="roll-ball-header">
            <div class="header-left">
              <img :src="iconCp1" style="width: 20px; height: 20px;" />
              <span class="roll-ball-title">{{ t('彩票') }}</span>
            </div>
            <div class="more-roll-btn" @click="toLottery">
              <span class="more-text">{{ t('更多') }} >></span>
            </div>
          </div>

          <div class="lottery-games-scroll pc-scroll-view">
            <div class="lottery-games-flex">
              <div class="lottery-game-item" v-for="(item, index) in lotteryGames" :key="index" @click="handleLotteryGameClick(item)">
                <img :src="item.icon" style="width: 56px; height: 56px; object-fit: contain;" />
                <span class="lottery-game-name">{{ item.name }}</span>
              </div>
            </div>
          </div>

          <div class="lottery-scroll pc-scroll-view">
            <div class="lottery-flex">
              <template v-if="skeletonLoading">
                <div class="lottery-card" v-for="i in 3" :key="'lottery-skeleton-'+i">
                  <div class="skeleton-box" style="height: 80px;"></div>
                </div>
              </template>
              <template v-else>
                <div class="lottery-card" v-for="(item, index) in lotteryHistory" :key="index" @click="goToLotteryDetail(item)">
                  <div class="item-header">
                    <div class="header-left-col">
                      <span class="lottery-name">{{ item.name }}</span>
                      <span class="lottery-issue">{{ getIssue(item.lottery) }} {{ t('期') }}</span>
                    </div>
                    <div class="header-right-col">
                      <span class="lottery-time">{{ getTime(item.lottery) }}</span>
                    </div>
                  </div>

                  <div v-if="[1, 2].includes(item.type)" class="play-container">
                    <div class="equation-row">
                      <template v-for="(num, idx) in getNumbers(item.lottery)" :key="idx">
                        <div class="grey-ball">{{ num }}</div>
                        <span class="operator" v-if="idx < getNumbers(item.lottery).length - 1">+</span>
                      </template>
                      <span class="operator">=</span>
                      <div class="red-sum-ball">{{ getSum(getNumbers(item.lottery)) }}</div>
                    </div>
                    <div class="tags-row">
                      <div
                          class="combo-tag"
                          v-for="(tag, tagIdx) in getComboTags(item.lottery.combo)"
                          :key="tagIdx"
                          :class="getTagClass(tag)"
                      >
                        {{ tag }}
                      </div>
                    </div>
                  </div>

                  <div v-else-if="[3, 4, 5, 6].includes(item.type)" class="play-container">
                    <div class="lhc-row">
                      <template v-for="(num, idx) in getNumbers(item.lottery)" :key="idx">
                        <span class="operator" v-if="idx === getNumbers(item.lottery).length - 1">+</span>
                        <div class="lhc-col">
                          <div class="lhc-ball" :class="getMarkSixColor(num)">
                            {{ num }}
                          </div>
                          <span class="lhc-zodiac">{{ getMarkSixZodiac(num) }}</span>
                        </div>
                      </template>
                    </div>
                  </div>

                  <div v-else-if="[7, 9, 11].includes(item.type)" class="play-container">
                    <div class="blocks-row">
                      <div
                          class="square-block"
                          v-for="(num, idx) in getNumbers(item.lottery)"
                          :key="idx"
                          :style="{ backgroundColor: getNumColor(num) }"
                      >
                        {{ num }}
                      </div>
                    </div>
                    <div class="tags-row mt-tags" v-if="item.lottery.open_code_other">
                      <div class="combo-tag tag-blue" v-for="(tag, tagIdx) in getOtherTags(item.lottery.open_code_other)" :key="tagIdx">
                        {{ tag }}
                      </div>
                    </div>
                  </div>

                  <div v-else-if="[8, 10].includes(item.type)" class="play-container">
                    <div class="balls-row">
                      <div
                          class="ball"
                          v-for="(num, idx) in getNumbers(item.lottery)"
                          :key="idx"
                      >
                        {{ num }}
                      </div>
                    </div>
                    <div class="tags-row mt-tags" v-if="item.lottery.open_code_other">
                      <div class="combo-tag tag-blue" v-for="(tag, tagIdx) in getOtherTags(item.lottery.open_code_other)" :key="tagIdx">
                        {{ tag }}
                      </div>
                    </div>
                  </div>

                  <div v-else-if="[12, 13].includes(item.type)" class="play-container">
                    <div class="dice-row">
                      <div
                          class="dice"
                          v-for="(num, idx) in getNumbers(item.lottery)"
                          :key="idx"
                      >
                        <div
                            v-for="(show, dotIdx) in getDiceDots(num)"
                            :key="dotIdx"
                            class="dot"
                            :class="{ 'visible': show, 'red-dot': Number(num) === 1 || Number(num) === 4 }"
                        ></div>
                      </div>
                    </div>
                    <div class="tags-row mt-tags" v-if="item.lottery.open_code_other">
                      <div class="combo-tag tag-blue" v-for="(tag, tagIdx) in getOtherTags(item.lottery.open_code_other)" :key="tagIdx">
                        {{ tag }}
                      </div>
                    </div>
                  </div>

                  <div v-else class="play-container">
                    <div class="balls-row">
                      <div class="ball" v-for="(num, idx) in getNumbers(item.lottery)" :key="idx">
                        {{ num }}
                      </div>
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </div>
        </div>

        <div class="roll-ball-section" v-for="(gameSection, index) in otherGamesList" :key="'other-'+index">
          <div class="roll-ball-header">
            <div class="header-left">
              <img :src="gameSection.icon" style="width: 20px; height: 20px;" />
              <span class="roll-ball-title">{{ t(gameSection.title) }}</span>
            </div>
            <div class="more-roll-btn" @click="handleOtherGameClick(gameSection.morePath)">
              <span class="more-text">{{ t('更多') }} >></span>
            </div>
          </div>

          <div class="other-games-scroll pc-scroll-view">
            <div class="other-games-flex">
              <div
                  class="other-game-item"
                  v-for="(item, itemIndex) in gameSection.items"
                  :key="itemIndex"
                  @click="handleOtherGameClick(item.path)"
              >
                <img :src="item.image" style="width: 140px; height: 140px; border-radius: 8px; object-fit: cover;" />
              </div>
            </div>
          </div>
        </div>

      </div>
      <div style="height: 20px"></div>

      <appFooter />
      <div class="safe-hb"></div>
      <div class="safe-ht"></div>
      <div class="home-hb"></div>
    </div>

</template>

<script setup>
import { ref, watch, onMounted, computed, onUnmounted, onActivated } from "vue";
import { useRouter, useRoute } from 'vue-router';
import { useI18n } from "vue-i18n";
import { getActivity, getBanner, getSportSchedule, getUserInfo, GetLastLottery, indexSportCount } from "@/request/api.js";
import { useOrderStore } from "@/store/bettingSheet.js";
import { formatRange } from "@/utils";
import appFooter from '@/businessComponents/pcFooter/index.vue'
import socket from '@/utils/websocket.js'
import { ChromeFilled } from '@element-plus/icons-vue'

import bgEnter from '@/assets/images/enter-bg.png'
import iconTy from '@/assets/images/Home/ty.png'
import iconCp1 from '@/assets/images/Home/cp1.png'
import iconDz from '@/assets/images/Home/dz.png'
import iconSx from '@/assets/images/Home/sx.png'
import iconQp from '@/assets/images/Home/qp.png'
import iconBy from '@/assets/images/Home/by.png'
import iconDj from '@/assets/images/Home/dj.png'

import JSSC from '@/assets/images/Home/JSSC.png'
import JSK3 from '@/assets/images/Home/JSK3.png'
import JSLHC from '@/assets/images/Home/JSLHC.png'
import AMLHC from '@/assets/images/Home/AMLHC.png'
import XGLHC from '@/assets/images/Home/XGLHC.png'

import ball10001 from '@/assets/images/Home/10001.avif'
import ball10006 from '@/assets/images/Home/10006.avif'
import ball10002 from '@/assets/images/Home/10002.avif'
import ball10003 from '@/assets/images/Home/10003.avif'
import ball10004 from '@/assets/images/Home/10004.avif'
import ball10005 from '@/assets/images/Home/10005.avif'

import sx1 from '@/assets/images/Home/sx1.png'
import sx2 from '@/assets/images/Home/sx2.png'
import sx3 from '@/assets/images/Home/sx3.png'
import dz1 from '@/assets/images/Home/dz1.png'
import dz2 from '@/assets/images/Home/dz2.png'
import by1 from '@/assets/images/Home/by1.png'
import qp1 from '@/assets/images/Home/qp1.png'
import dj1 from '@/assets/images/Home/dj1.png'

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

const baseDomain = 'F1bet';
const suffixList = ['.cc', '.vip', '.com', '.net'];
const currentSuffixIndex = ref(0);
const animatedUrl = computed(() => `${baseDomain}${suffixList[currentSuffixIndex.value]}`);
let suffixTimer = null;

onMounted(() => {
  suffixTimer = setInterval(() => {
    currentSuffixIndex.value = (currentSuffixIndex.value + 1) % suffixList.length;
  }, 1000);

  syncFromStore();
  socket.eventBus.addEventListener('onSocketMessage', handleSocketMessage);
});

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

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

const banners1 = ref([]);
const banners2 = ref([]);
const gamblingList = ref([]);
const gamblingCount = ref(0);
const limit = ref(10);
const selectedMap = ref({});
const skeletonLoading = ref(true);

const lotteryHistory = ref([]);

const lotteryGames = ref([
  { name: '极速赛车', icon: JSSC,  route: { name: 'Lottery', query: { type: 1, title: '极速赛车', game_type: 7 } } },
  { name: '极速快3', icon: JSK3, route: { name: 'Lottery', query: { type: 7, title: 'SG快3', game_type: 13 } } },
  { name: '极速六合彩', icon: JSLHC,  route: { name: 'SpeedDigital' } },
  { name: '澳门六合彩', icon: AMLHC, route: { name: 'Digital' }  },
  { name: '香港六合彩', icon: XGLHC, route: { name: 'HKDigital' } }
]);

const handleLotteryGameClick = (item) => {
  if (item.route) {
    router.push(item.route);
  }
};

const otherGamesList = ref([
  {
    title: '视讯',
    icon: iconSx,
    morePath: '',
    items: [
      { image: sx1, path: '' },
      { image: sx2, path: '' },
      { image: sx3, path: '' }
    ]
  },
  {
    title: '电子',
    icon: iconDz,
    morePath: '',
    items: [
      { image: dz1, path: '' },
      { image: dz2, path: '' }
    ]
  },
  {
    title: '捕鱼',
    icon: iconBy,
    morePath: '',
    items: [
      { image: by1, path: '' }
    ]
  },
  {
    title: '棋牌',
    icon: iconQp,
    morePath: '',
    items: [
      { image: qp1, path: '' }
    ]
  },
  {
    title: '电竞',
    icon: iconDj,
    morePath: '',
    items: [
      { image: dj1, path: '' }
    ]
  }
]);

const handleOtherGameClick = (path) => {
  if (path) {
    router.push({ path });
  }
};

const categoryList = ref([
  { name: '彩票', icon: iconCp1, path: '/EntertainmentList' },
  { name: '电子', icon: iconDz, path: '' },
  { name: '视讯', icon: iconSx, path: '' },
  { name: '体育', icon: iconTy, path: '/SportsBetting' },
  { name: '棋牌', icon: iconQp, path: '' },
  { name: '捕鱼', icon: iconBy, path: '' },
  { name: '电竞', icon: iconDj, path: '' }
]);

const handleCategoryClick = (item) => {
  if (item.path) {
    router.push({ path: item.path });
  }
};

const sportsBalls = ref([
  { id: 2, name: '足球', icon: ball10001, count: 11, path: '/pages/Tabbar/SportsBetting/index' },
  { id: 1, name: '乒乓球', icon: ball10006, count: 11, path: '/pages/Tabbar/Sports/index' },
  { id: 3, name: '篮球', icon: ball10002, count: 11, path: '/pages/Tabbar/Sports/index' },
  { id: 4, name: '排球', icon: ball10003, count: 8, path: '/pages/Tabbar/Sports/index' },
  { id: 5, name: '板球', icon: ball10004, count: 21, path: '/pages/Tabbar/Sports/index' },
  { id: 6, name: '网球', icon: ball10005, count: 11, path: '/pages/Tabbar/Sports/index' }
]);

const handleSportBallClick = (item) => {
  if (item.path) {
    router.push({ path: item.path });
  }
};

function handleSwiper(item) {
  router.push({ name: 'PromotionDetail', query: { id: banners2.value[item].link } });
}

const getIssue = (lottery) => {
  return lottery.issue || lottery.issue_no || '';
};

const getTime = (lottery) => {
  const timeStr = lottery.open_time || lottery.start_time || '';
  if (timeStr && timeStr.length >= 16) {
    return timeStr.substring(5, 16);
  }
  return timeStr;
};

const getNumbers = (lottery) => {
  const str = lottery.winning_numbers || lottery.open_code || '';
  return str ? str.split(',') : [];
};

const getOtherTags = (otherStr) => {
  return otherStr ? otherStr.split(',') : [];
};

const getSum = (numbers) => {
  return numbers.reduce((sum, num) => sum + Number(num), 0);
};

const getComboTags = (combo) => {
  if(Array.isArray(combo)) {
    return combo.filter(Boolean);
  } else {
    return combo ? combo.split(' ').filter(Boolean) : [];
  }
};

const getTagClass = (tag) => {
  if (['大', '双', '极大'].includes(tag)) return 'tag-red';
  if (['小', '单', '极小'].includes(tag)) return 'tag-green';
  if (tag.includes('尾')) return 'tag-yellow';
  return 'tag-default';
};

const getMarkSixZodiac = (num) => {
  const n = Number(num);
  const zodiacs = ['马', '蛇', '龙', '兔', '虎', '牛', '鼠', '猪', '狗', '鸡', '猴', '羊'];
  return zodiacs[(n - 1) % 12];
};

const getMarkSixColor = (num) => {
  const n = Number(num);
  const red = [1, 2, 7, 8, 12, 13, 18, 19, 23, 24, 29, 30, 34, 35, 40, 45, 46];
  const blue = [3, 4, 9, 10, 14, 15, 20, 21, 25, 26, 31, 32, 36, 37, 41, 42, 47, 48];
  const green = [5, 6, 11, 16, 17, 22, 27, 28, 33, 38, 39, 43, 44, 49];
  if (red.includes(n)) return 'color-red';
  if (blue.includes(n)) return 'color-blue';
  if (green.includes(n)) return 'color-green';
  return '';
};

const getNumColor = (num) => {
  const colors = {
    0: '#f9a826', 1: '#e2d230', 2: '#2881e1', 3: '#4a4a4a', 4: '#ff7e00',
    5: '#10e2e5', 6: '#5134ff', 7: '#bfbfbf', 8: '#ff2600', 9: '#780b00', 10: '#07bf00'
  };
  return colors[Number(num)] || '#e54d42';
};

const getDiceDots = (num) => {
  const n = Number(num);
  const layouts = {
    1: [0, 0, 0,  0, 1, 0,  0, 0, 0],
    2: [1, 0, 0,  0, 0, 0,  0, 0, 1],
    3: [1, 0, 0,  0, 1, 0,  0, 0, 1],
    4: [1, 0, 1,  0, 0, 0,  1, 0, 1],
    5: [1, 0, 1,  0, 1, 0,  1, 0, 1],
    6: [1, 0, 1,  1, 0, 1,  1, 0, 1]
  };
  return layouts[n] || layouts[1];
};

const toLottery = () => {
  router.push({ path: '/EntertainmentList' });
};

const goToLotteryDetail = (item) => {
  let list = [
    { type: 1, name: '加拿大28', route: { name: 'PC28' } },
    { type: 2, name: '极速28', route: { name: 'ExtremeSpeed28' } },
    { type: 3, name: '澳门六合彩', route: { name: 'Digital' } },
    { type: 4, name: '新澳门六合彩', route: { name: 'NewDigital' } },
    { type: 5, name: '极速六合彩', route: { name: 'SpeedDigital' } },
    { type: 6, name: '香港六合彩', route: { name: 'HKDigital' } },
    { type: 7, name: '极速赛车', route: { name: 'Lottery', query: { type: 1, title: '极速赛车', game_type: 7 } } },
    { type: 8, name: '极速时时彩', route: { name: 'Lottery', query: { type: 2, title: '极速时时彩', game_type: 8 } } },
    { type: 9, name: '极速飞艇', route: { name: 'Lottery', query: { type: 3, title: '极速飞艇', game_type: 9 } } },
    { type: 13, name: '极速快3', route: { name: 'Lottery', query: { type: 6, title: '极速快3', game_type: 12 } } },
    { type: 10, name: 'SG时时彩', route: { name: 'Lottery', query: { type: 4, title: 'SG时时彩', game_type: 10 } } },
    { type: 11, name: 'SG飞艇', route: { name: 'Lottery', query: { type: 5, title: 'SG飞艇', game_type: 11 } } },
    { type: 12, name: 'SG快3', route: { name: 'Lottery', query: { type: 7, title: 'SG快3', game_type: 13 } } }
  ]

  const res = list.find(trim => trim.type === item.type)
  if(res) {
    router.push(res.route)
  }
};

const oddsChangeMap = ref(new Map())
const getOddsKey = (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 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 getVisibleValues = (values) => {
  if (!values) return [];
  if (values.length <= 3) return values;
  return values.slice(0, 2);
};
const hasMore = (values) => {
  if (!values) return false;
  return values.length > 3;
};
const getRemainCount = (values) => {
  if (!values) return 0;
  return values.length - 2;
};
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 checkIsLocked = (item) => {
  if (!item) return true;
  if (Number(item.is_locked) === 1) return true;
  if (item.status !== undefined && Number(item.status) !== 1) return true;
  if (item.state !== undefined) {
    const state = Number(item.state);
    if (state !== 0 && state !== 1) return true;
  }
  return false;
};
const isOptionLocked = (item, opt) => {
  if (checkIsLocked(item)) return true;
  if (!opt) return true;
  if (!opt.odd || opt.odd === '-' || Number(opt.odd) === 0) return true;
  if (opt.suspended === true || String(opt.suspended).toLowerCase() === 'true') return true;
  if (item.odds && item.odds[0] && item.odds[0].is_findLocked) return true;
  return false;
};
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 handleSocketMessage = (e) => {
  const data = e.detail;
  try {
    const res = typeof data === 'string' ? JSON.parse(data) : data;
    if (res.type === 'sport_list' && Array.isArray(res.message)) {
      res.message.forEach((newMatch) => {
        let idx = gamblingList.value.findIndex(item => item.data_id === newMatch.data_id);
        if (idx !== -1) {
          const oldMatch = gamblingList.value[idx];
          let parsedNewOdds = newMatch.odds;
          if (typeof parsedNewOdds === 'string') {
            try { parsedNewOdds = JSON.parse(parsedNewOdds); } catch(e) { parsedNewOdds = []; }
          }
          if (oldMatch.odds?.[0] && parsedNewOdds?.[0]) {
            const oldMarket = oldMatch.odds[0];
            const newMarket = parsedNewOdds[0];
            if (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?.odd && newOpt?.odd) {
                  const oldNum = parseFloat(oldOpt.odd);
                  const newNum = parseFloat(newOpt.odd);
                  if (!isNaN(oldNum) && !isNaN(newNum) && oldNum !== newNum) {
                    const key = getOddsKey(oldMatch.id, newMarket.id, newOpt);
                    const direction = newNum > oldNum ? 'up' : 'down';
                    oddsChangeMap.value.set(key, { direction, timestamp: Date.now() });
                    setTimeout(() => oddsChangeMap.value.delete(key), 3100);
                  }
                }
              });
            }
          }
          let parsedOdds = newMatch.odds;
          if (typeof parsedOdds === 'string') {
            try { parsedOdds = JSON.parse(parsedOdds); } catch(e) { parsedOdds = []; }
          } else if (!parsedOdds) {
            parsedOdds = gamblingList.value[idx].odds;
          }
          gamblingList.value[idx] = { ...gamblingList.value[idx], ...newMatch, odds: parsedOdds };
          orderStore.updateMatchStatus(newMatch.data_id, gamblingList.value[idx]);
        }
      });
    }
  } catch (error) {}
}

const goDetail = (item) => {
  router.push({ name: 'SportDetail', query: { data_id: item.data_id } });
};
const goLeagueDetail = (item) => {
  router.push({ name: 'SportsBetting', query: { league: item.league } });
}
const toMoreRollBall = (name) => {
  router.push({ name });
};
const getStatusText = (state) => {
  const states = { 0: t("未开始"), 1: t("进行中"), 2: t("已完场"), 3: t("延期"), 4: t("取消") };
  return states[state] || "";
};
const getStatusType = (state) => {
  const types = { 0: 'info', 1: 'primary', 2: 'success', 3: 'warning', 4: 'error' };
  return types[state] || 'info';
};
const translateSelection = (valStr) => {
  if (valStr === undefined || valStr === null) return '';
  return String(valStr);
};
const isSelected = (matchId, marketId, selection) => {
  if (!selection) return false;
  const uniqueKey = getUniqueKey(matchId, marketId, selection);
  return !!selectedMap.value[uniqueKey];
}
const handleOddsClick = (item, selection) => {
  if (isOptionLocked(item, selection)) return;
  if (!item.odds || item.odds.length === 0) return;
  const market = item.odds[0];
  const uniqueKey = getUniqueKey(item.id, market.id, selection);
  if (selectedMap.value[uniqueKey]) {
    orderStore.removeOrderItemByKey(uniqueKey);
  } else {
    if (market.values) {
      market.values.forEach(wsItem => {
        const otherKey = getUniqueKey(item.id, market.id, wsItem);
        if (selectedMap.value[otherKey]) {
          orderStore.removeOrderItemByKey(otherKey);
        }
      })
    }
    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,
      status: item.status,
      is_roll: item.is_roll,
      is_locked: item.is_locked,
      uniqueKey: uniqueKey,
      optionValue: selection.value,
      submit_value: selection.submit_value,
      marketId: market.id,
      mininum: market.mininum,
      maxinum: market.maxinum,
      selection: {
        ...selection
      }
    };
    orderStore.addOrderItem(betItem);
    if (navigator.vibrate) {
      navigator.vibrate(50);
    }
  }
};
const fetchGamblingDataWithFallback = async () => {
  let res = await getSportSchedule({ page: 1, limit: limit.value, state: 1, is_rec: 1  });
  if (res.code === 1 && (!res.data || !res.data.list || res.data.list.length === 0)) {
    res = await getSportSchedule({ page: 1, limit: limit.value, state: 0, is_rec: 1 });
  }
  return res;
};
async function onQuery() {
  try {
    skeletonLoading.value = true;
    indexSportCount().then(res => {
      sportsBalls.value.forEach((sports) => {
        if(sports.id === 2) {
          sports.count = res.data.count
        }
      })
    })
    const [resB1, resB2, resGambling, resLottery] = await Promise.all([
      getActivity({ type: 2 }),
      getBanner({ type: 'app' }),
      fetchGamblingDataWithFallback(),
      GetLastLottery()
    ]);
    banners1.value = resB1.data.list;
    banners2.value = resB2.data.list;

    lotteryHistory.value = resLottery.data || [];

    const formatData = (list) => {
      return (list || []).map(item => {
        if (typeof item.odds === 'string') {
          try { item.odds = JSON.parse(item.odds); } catch(e) { item.odds = []; }
        }
        return item;
      });
    };
    gamblingList.value = formatData(resGambling?.data?.list || []);
    gamblingList.value = gamblingList.value.map((item) => {
      if (item.odds) {
        item.odds.forEach(jtem => {
          if (item.odd_ids_locked && item.odd_ids_locked.find(trim => jtem.id === trim)) {
            jtem.is_findLocked = true
          }
        })
      }
      return item
    })
    gamblingCount.value = resGambling?.data?.count || 0;
    skeletonLoading.value = false;
  } catch (error) {
    skeletonLoading.value = false;
  }
}

if(route.query.token) {
  localStorage.setItem('token', route.query.token);
}

if(route.query.token && (!route.query.is_bind || route.query.is_bind == 0)) {
  getUserInfo().then((res) => {
    if(!res.data.account) {
      if(window.confirm('您的账号信息尚未完善，为保证功能的正常使用，请前往补充填写。')) {
        router.push({ path: '/pages/setAccount/index' });
      }
    }
  })
}

onQuery();
</script>

<style scoped lang="scss">
.page-scroll-container {
  width: 1200px;
  height: 100%;
  overflow-y: auto;
  margin: 0 auto;
}

.pc-scroll-view {
  width: 100%;
  white-space: nowrap;
  overflow-x: auto;
}

.pc-scroll-view::-webkit-scrollbar {
  display: none;
}

.skeleton-box {
  background: #212121;
  width: 100%;
  height: 100%;
  border-radius: 4px;
  animation: skeleton-blink 1.2s ease-in-out infinite;
}

@keyframes skeleton-blink {
  0% { opacity: 1; }
  50% { opacity: 0.6; }
  100% { opacity: 1; }
}

.pc-notice-bar {
  background: #212121;
  color: #f8b932;
  border-radius: 12px;
  padding: 6px 12px;
  font-size: 13px;
  flex: 1;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.url-header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
  padding: 0 5px;
}
.brand-left {
  display: flex;
  align-items: center;
  gap: 8px;
}
.brand-text-box {
  display: flex;
  flex-direction: column;
}
.brand-title {
  font-size: 15px;
  font-weight: 700;
  color: #e0e0e0;
  line-height: 1.2;
}
.brand-subtitle {
  font-size: 10px;
  color: #999;
  letter-spacing: 1px;
}
.url-right-badge {
  display: flex;
  align-items: center;
  gap: 6px;
  min-width: 110px;
  background: #212121;
  border-radius: 30px;
  padding: 0 12px;
  height: 30px;
  border: 1px solid #333;
  box-sizing: border-box;
  margin-left: 10px;
}
.url-text {
  font-size: 12px;
  color: #e0e0e0;
  font-weight: 500;
}
.animated-text {
  transition: opacity 0.3s ease;
}

.game-category-container {
  background-color: #212121;
  border-radius: 12px;
  margin-top: 15px;
  padding: 12px 0;
}
.category-flex {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  padding: 0 14px;
  box-sizing: border-box;
  gap: 20px;
}
.category-item {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  gap: 6px;
  min-width: 44px;
  cursor: pointer;
}
.category-text {
  font-size: 13px;
  color: #e0e0e0;
}

.refresh-spinner { width: 24px; height: 24px; border: 2px solid #f8b932; border-top-color: var(--tmc); border-radius: 50%; animation: spin 0.8s linear infinite; }
@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
.flex { display: flex; }
.flex-col { flex-direction: column; }
.items-center { align-items: center; }
.justify-center { justify-content: center; }
.py-6 { padding-top: 24px; padding-bottom: 24px; }
.mb-2 { margin-bottom: 8px; }
.text-xs { font-size: 12px; }
.tmc { color: #e0e0e0; }
.banner1-flex { display: flex; flex-direction: row; gap: 10px; }
.banner1-item { width: 240px; background: #141414; border-radius: 6px; flex-shrink: 0; box-sizing: border-box; display: inline-block; overflow: hidden; cursor: pointer;}
.banner1-item-title { height: calc(100% - 150px); display: flex; flex-direction: column; justify-content: center; align-items: center; font-size: 14px; color: #e0e0e0; white-space: normal; }
.square-wrapper { width: 100%; aspect-ratio: 740 / 320;  position: relative; border-radius: 4px; }

.roll-ball-section {
  background-color: #212121;
  border-radius: 12px;
  margin-top: 15px;
  padding: 12px;
}
.roll-ball-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.header-left {
  display: flex;
  align-items: center;
  gap: 6px;
}
.roll-ball-title {
  font-size: 16px;
  font-weight: 700;
  color: #fff;
}
.more-roll-btn { cursor: pointer; }
.more-text {
  font-size: 13px;
  color: #e0e0e0;
}

.sports-ball-scroll {
  margin-bottom: 14px;
}
.sports-ball-flex {
  display: flex;
  flex-direction: row;
  gap: 20px;
}
.sport-ball-item {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  flex-shrink: 0;
  cursor: pointer;
}
.ball-icon-wrapper {
  position: relative;
  width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.badge-count {
  position: absolute;
  top: 0px;
  right: -8px;
  background-color: #ff3b30;
  color: #fff;
  font-size: 10px;
  font-weight: bold;
  border-radius: 10px;
  padding: 1px 4px;
  min-width: 14px;
  text-align: center;
  line-height: 1.2;
}

.roll-ball-flex { display: flex; flex-direction: row; gap: 12px; padding-bottom: 4px; flex-wrap: wrap }
.match-card {
  width: 32%;
  flex-shrink: 0;
  display: inline-block;
  background: #141414;
  border-radius: 10px;
  padding: 10px;
  box-sizing: border-box;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  cursor: pointer;
}
.match-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10px;
  border-bottom: 1px dashed #333;
  margin-bottom: 12px;
}
.league-left {
  display: flex;
  align-items: center;
  gap: 4px;
  flex: 1;
}
.league-name {
  font-size: 12px;
  color: #e0e0e0;
  white-space: normal;
  word-break: break-word;
  line-height: 1.3;
}
.match-time {
  font-size: 10px;
  min-width: 90px;
  text-align: center;
  color: #999;
}
.match-more-btn {
  background-color: #ffc107;
  border-radius: 10px;
  padding: 2px 6px;
  display: flex;
  align-items: center;
  gap: 2px;
  margin-left: 6px;
}
.more-count {
  font-size: 10px;
  color: #fff;
  font-weight: bold;
}
.match-teams-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.team-block {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 40%;
  gap: 6px;
}
.team-name-group {
  display: flex;
  align-items: center;
  gap: 4px;
}
.team-name {
  font-size: 11px;
  color: #e0e0e0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 65px;
}
.tag-home {
  font-size: 9px;
  color: #4caf50;
  border: 1px solid #4caf50;
  border-radius: 2px;
  padding: 0 2px;
}
.tag-away {
  font-size: 9px;
  color: #f56c6c;
  border: 1px solid #f56c6c;
  border-radius: 2px;
  padding: 0 2px;
}
.vs-block {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.vs-text {
  font-size: 16px;
  font-weight: 900;
  color: #fff;
}
.vs-sub {
  font-size: 10px;
  color: #999;
  margin-top: 2px;
}

.odds-group { margin-top: 8px; }
.odds-grid {
  display: flex;
  flex-wrap: nowrap;
  gap: 8px;
  width: 100%;
}
.odds-btn {
  flex: 1;
  background: #212121;
  border: 1px solid #333;
  border-radius: 6px;
  padding: 8px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  position: relative;
  overflow: hidden;
  cursor: pointer;

  .locked-overlay { position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(20, 20, 20, 0.75); z-index: 10; display: flex; align-items: center; justify-content: center; backdrop-filter: blur(1px); }
  .selection-name { font-size: 11px; color: #aaa; margin-bottom: 2px; }
  .odds-val { font-size: 12px; font-weight: bold; color: #f8b932; }

  &:active { background-color: #333; }
  &.is-active { background-color: #f8b932; border-color: #f8b932; box-shadow: 0 4px 10px rgba(248, 185, 50, 0.3); .selection-name, .odds-val { color: #ffffff; } }
  &.is-locked { pointer-events: none; }
  &.odds-up .odds-val { color: #4caf50 !important; transition: color 0.3s; }
  &.odds-down .odds-val { color: #f56c6c !important; transition: color 0.3s; }
}

.lottery-games-scroll {
  margin-bottom: 12px;
}
.lottery-games-flex {
  display: flex;
  flex-direction: row;
  gap: 16px;
  padding: 4px 0;
}
.lottery-game-item {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  flex-shrink: 0;
  gap: 6px;
  cursor: pointer;
}
.lottery-game-name {
  font-size: 12px;
  color: #e0e0e0;
}

.lottery-flex { display: flex; flex-direction: row; gap: 12px; padding-bottom: 4px; flex-wrap: wrap;  }
.lottery-card {
  width: 24%;
  flex-shrink: 0;
  display: inline-block;
  white-space: normal;
  background: #141414;
  border-radius: 10px;
  padding: 12px;
  box-sizing: border-box;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  cursor: pointer;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}
.header-left-col {
  display: flex;
  align-items: center;
  gap: 8px;
}
.lottery-name { font-size: 14px; font-weight: bold; color: #e0e0e0; }
.lottery-issue { font-size: 11px; color: #e54d42; font-weight: 500; }
.header-right-col .lottery-time { font-size: 11px; color: #999; }

.play-container { margin-top: 10px; }

.equation-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}
.grey-ball {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background-color: #212121;
  color: #e0e0e0;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 13px;
  font-weight: bold;
  border: 1px solid #333;
}
.red-sum-ball {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background-color: #f75b5b;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 13px;
  font-weight: bold;
  box-shadow: 0 2px 4px rgba(247, 91, 91, 0.3);
}

.lhc-row { display: flex; align-items: center; gap: 6px; }
.lhc-col { display: flex; flex-direction: column; align-items: center; gap: 4px; }
.lhc-ball {
  width: 26px;
  height: 26px;
  border-radius: 50%;
  background-color: #141414;
  color: #e0e0e0;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
  font-weight: bold;
  border: 2px solid transparent;
  box-sizing: border-box;
}
.color-red { border-color: #f75b5b; }
.color-blue { border-color: #49b3ff; }
.color-green { border-color: #40b17b; }
.lhc-zodiac { font-size: 10px; color: #999; }

.blocks-row { display: flex; flex-wrap: wrap; gap: 4px; }
.square-block {
  width: 22px;
  height: 22px;
  border-radius: 4px;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
  font-weight: bold;
}

.balls-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.ball {
  width: 26px;
  height: 26px;
  border-radius: 50%;
  background-color: #e54d42;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
  font-weight: 500;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.dice-row { display: flex; flex-wrap: wrap; gap: 8px; }
.dice {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  width: 28px;
  height: 28px;
  background-color: #141414;
  border: 1px solid #333;
  border-radius: 6px;
  padding: 2px;
  box-shadow: inset 0 -2px 0 rgba(0, 0, 0, 0.05), 0 2px 4px rgba(0, 0, 0, 0.05);
  box-sizing: border-box;
}
.dot {
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background-color: transparent;
  place-self: center;
}
.dot.visible { background-color: #e0e0e0; }
.dot.visible.red-dot { background-color: #e54d42; }

.operator {
  color: #999;
  font-size: 14px;
  margin: 0 2px;
  font-weight: 500;
  align-self: flex-start;
  margin-top: 4px;
}

.tags-row { display: flex; flex-wrap: wrap; gap: 6px; }
.mt-tags { margin-top: 8px; }
.combo-tag {
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 10px;
  font-weight: bold;
  color: #fff;
}
.tag-red { background-color: #f07474; }
.tag-green { background-color: #79c55b; }
.tag-yellow { background-color: #eebb4d; }
.tag-blue { background-color: #5b9cf7; }
.tag-default { background-color: #333; color: #aaa; }

.other-games-flex {
  display: flex;
  flex-direction: row;
  gap: 12px;
  padding-bottom: 4px;
}
.other-game-item {
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
  width: 140px;
  height: 140px;
  cursor: pointer;
}
</style>