<template>
  <div class="pc-page-container">
    <div class="pc-main-content">

      <div class="video-container">
        <video
            ref="videoRef"
            id="homeVideo"
            :src="videoSrc"
            autoplay
            loop
            muted
            playsinline
            class="pc-video"
            @loadedmetadata="onVideoLoaded"
            @play="onVideoLoaded"
        ></video>

        <div class="video-control-btn" @click="toggleVideo">
          <el-icon color="rgba(255,255,255,0.8)" :size="30">
            <VideoPlay v-if="isPaused" />
            <VideoPause v-else />
          </el-icon>
        </div>
      </div>

      <div class="notice-container">
        <el-alert
            title="F1bet国际官宣：请认准官网F1bet.cc 永久网址：F1bet.cc"
            type="warning"
            :closable="false"
        />
      </div>

      <div class="url-header-bar">
        <div class="brand-left">
          <el-icon color="#f8b932" :size="28"><StarFilled /></el-icon>
          <div class="brand-text-box">
            <span class="brand-title">F1BET</span>
            <span class="brand-subtitle">{{ PermanentURL }}</span>
          </div>
        </div>
        <div class="url-right-badge">
          <el-icon color="#f8b932" :size="16"><ChromeFilled /></el-icon>
          <span class="url-text">{{ t('永久网址') }}: {{ PermanentURL }}</span>
        </div>
      </div>

      <div class="banner-carousel-container">
        <template v-if="skeletonLoading">
          <el-carousel trigger="click" height="150px" :autoplay="false" arrow="always" indicator-position="none">
            <el-carousel-item>
              <div class="banner1-grid">
                <div class="banner1-item" v-for="i in 4" :key="'skeleton-banner-'+i">
                  <div class="square-wrapper flex items-center justify-center bg-dark">
                    <el-skeleton animated>
                      <template #template>
                        <el-skeleton-item variant="image" style="width: 100%; height: 100%; background-color: #2d2d2d;" />
                      </template>
                    </el-skeleton>
                  </div>
                </div>
              </div>
            </el-carousel-item>
          </el-carousel>
        </template>
        <template v-else>
          <el-carousel trigger="click" height="150px" :autoplay="false" arrow="always" indicator-position="none">
            <el-carousel-item v-for="pageIndex in Math.ceil(banners2.length / 4)" :key="pageIndex">
              <div class="banner1-grid">
                <div
                    class="banner1-item"
                    v-for="(item, i) in banners2.slice((pageIndex - 1) * 4, pageIndex * 4)"
                    :key="i"
                    @click="handleSwiper((pageIndex - 1) * 4 + i)"
                >
                  <div class="square-wrapper">
                    <img :src="item.image"  style="width: 100%">
<!--                    <el-image :src="item.image" fit="fill" style="aspect-ratio: 740 / 320"></el-image>-->
                  </div>
                </div>
              </div>
            </el-carousel-item>
          </el-carousel>
        </template>
      </div>

<!--      <div class="quick-tab-container">-->
<!--        <div-->
<!--            class="quick-tab-item"-->
<!--            v-for="(item, index) in quickTabs"-->
<!--            :key="index"-->
<!--            @click="handleQuickTabClick(item)"-->
<!--        >-->
<!--          <img :src="item.icon" class="quick-tab-icon" alt="" />-->
<!--        </div>-->
<!--      </div>-->

      <lotteryList show-more />

      <div style="height: 20px"></div>
      <pcFooter :notBg="true" />
      <div class="safe-hb"></div>
      <div class="safe-ht"></div>
      <div class="home-hb"></div>

    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onActivated } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter, useRoute } from "vue-router";
import { ElMessageBox } from 'element-plus';
import { StarFilled, ChromeFilled, VideoPlay, VideoPause } from '@element-plus/icons-vue';
import { getActivity, getBanner, getSportSchedule, getUserInfo } from "@/request/api.js";
import { useOrderStore } from "@/store/bettingSheet.js";
import pcFooter from '@/businessComponents/pcFooter/index.vue';
import lotteryList from './components/lotteryList/index.vue'

import homeVideo from '@/assets/video/home.mp4';
import rmIcon from '@/assets/image/Home/rm.png';
import cpIcon from '@/assets/image/Home/cp.png';
import zqIcon from '@/assets/image/Home/zq.png';
import sjbIcon from '@/assets/image/Home/sjb.png';

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

const PermanentURL = ref(window.global?.PermanentURL || 'F1bet.cc');

const videoSrc = ref('');
const playTrigger = ref(0);
const isPaused = ref(false);
const videoLoaded = ref(false);
const videoRef = ref(null);

const onVideoLoaded = () => {
  videoLoaded.value = true;
};

onMounted(() => {
  videoSrc.value = homeVideo;
});

const toggleVideo = () => {
  isPaused.value = !isPaused.value;
  if (videoRef.value) {
    if (isPaused.value) {
      videoRef.value.pause();
    } else {
      videoRef.value.play().catch(e => console.error('Video play rejected:', e));
    }
  }
};

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

const skeletonLoading = ref(true);

const quickTabs = ref([
  { icon: rmIcon, pageName: 'EntertainmentList', query: { type: 1 } },
  { icon: cpIcon, pageName: 'EntertainmentList', },
  { icon: zqIcon, pageName: 'SportsBetting', },
  { icon: sjbIcon, pageName: 'WorldCup',  }
]);

function handleQuickTabClick(item) {
  if (item.pageName) {
    router.push({ name: item.pageName, query: item.query ? item.query : {} });
  }
}

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

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 goDetail = (item) => {
  router.push({ name: 'sportDetail', query: { data_id: item.data_id } });
};
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);
  }
};
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;
    const [resB1, resB2, resGambling] = await Promise.all([
      getActivity({ type: 2 }),
      getBanner({ type: 'app' }),
      fetchGamblingDataWithFallback()
    ]);
    banners1.value = resB1.data.list;
    banners2.value = resB2.data.list;
    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;
  }
}

onActivated(() => {
  syncFromStore();
  if (!isPaused.value && videoRef.value) {
    videoRef.value.play().catch(e => console.error('Video force play rejected:', e));
  }
});

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) {
      ElMessageBox.confirm(
          '您的账号信息尚未完善，为保证功能的正常使用，请前往补充填写。',
          '温馨提示',
          {
            confirmButtonText: '去填写',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(() => {
        router.push({ path: '/setAccount' });
      }).catch(() => {});
    }
  })
}

onQuery();
</script>

<style scoped lang="scss">
.pc-page-container {
  width: 100%;
  display: flex;
  justify-content: center;
  //background-color: #141414;
  //background: url('@/assets/image/layout/footer-bg.png') no-repeat;
  //background-size: cover;
  //background-position: center;
}

.pc-main-content {
  width: 100%;
  max-width: 1200px;
  //background-color: #212121;
  padding: 20px;
  box-sizing: border-box;
}

.video-container {
  position: relative;
  width: 100%;
  border-radius: 8px;
  height: 300px;
  overflow: hidden;
  margin-top: 15px;
  background-color: #000;
}

.pc-video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-control-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  z-index: 10;
  padding: 5px;
  cursor: pointer;
  transition: opacity 0.2s;

  &:hover {
    opacity: 0.8;
  }
  &:active {
    opacity: 0.6;
  }
}

.notice-container {
  margin-top: 15px;
}

.url-header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 0 10px;
}
.brand-left {
  display: flex;
  align-items: center;
  gap: 12px;
}
.brand-text-box {
  display: flex;
  flex-direction: column;
}
.brand-title {
  font-size: 18px;
  font-weight: 700;
  color: #ffffff;
  line-height: 1.2;
}
.brand-subtitle {
  font-size: 12px;
  color: #8e9cae;
  letter-spacing: 1px;
}
.url-right-badge {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #212121;
  border-radius: 20px;
  padding: 8px 16px;
  border: 1px solid #3f3f46;
}
.url-text {
  font-size: 14px;
  color: #cbd5e1;
  font-weight: 500;
}

.quick-tab-container {
  background-color: #212121;
  border-radius: 8px;
  padding: 16px 20px;
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 24px;
}
.quick-tab-item {
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  cursor: pointer;

  &:hover {
    transform: translateY(-2px);
  }
  &:active {
    opacity: 0.75;
    transform: scale(0.95);
  }
}
.quick-tab-icon {
  width: 56px;
  height: 56px;
  object-fit: contain;
}

.banner-carousel-container {
  margin-top: 20px;
}
.banner1-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
  width: 100%;
  height: 100%;
}
.banner1-item {
  background: #2d2d2d;
  border-radius: 8px;
  box-sizing: border-box;
  overflow: hidden;
  cursor: pointer;
  transition: box-shadow 0.3s;
  width: 100%;
  aspect-ratio: 740 / 320;

  &:hover {
    box-shadow: 0 4px 12px rgba(0,0,0,0.5);
  }
}
.square-wrapper {
  position: relative;
  border-radius: 4px;
  overflow: hidden;
}

.flex { display: flex; }
.items-center { align-items: center; }
.justify-center { justify-content: center; }
.bg-dark { background-color: #2d2d2d; }

</style>