<template>
  <div class="lottery-page-layout">

    <div class="recent-sidebar-container" :class="{ 'is-collapsed': !isSidebarOpen }">
      <div class="sidebar-collapsed" v-if="!isSidebarOpen" @click="openSidebar">
        <div class="custom-icon">
          <el-icon size="24" class="icon-color">
            <Calendar />
          </el-icon>
        </div>
        <div class="vertical-text">{{ t('往期历史') }}</div>
      </div>

      <div class="sidebar-expanded" v-else>
        <div class="sidebar-header" @click="isSidebarOpen = false">
          <div class="header-left">
            <el-icon class="pointer" size="20">
              <Calendar />
            </el-icon>
            <span class="header-text">{{ t('往期开奖历史') }}</span>
          </div>
          <el-icon class="pointer close-icon" size="20">
            <ArrowLeft />
          </el-icon>
        </div>

        <div class="sidebar-body" v-infinite-scroll="loadMoreHistory"
          :infinite-scroll-disabled="historyLoading || noMoreHistory" :infinite-scroll-distance="20">

          <el-skeleton :loading="historyLoading && historyParams.page === 1" animated>
            <template #template>
              <div class="history-list">
                <div class="history-item" v-for="i in 8" :key="i">
                  <div class="item-header">
                    <el-skeleton-item variant="text" style="width: 40%;" />
                    <el-skeleton-item variant="text" style="width: 30%;" />
                  </div>
                  <div class="item-equation">
                    <el-skeleton-item variant="circle" class="circle" style="border: none;" />
                    <span class="op">+</span>
                    <el-skeleton-item variant="circle" class="circle" style="border: none;" />
                    <span class="op">+</span>
                    <el-skeleton-item variant="circle" class="circle" style="border: none;" />
                    <span class="op">=</span>
                    <el-skeleton-item variant="circle" class="circle result" />
                  </div>
                  <div class="item-tags">
                    <el-skeleton-item variant="rect" style="width: 24px; height: 20px; border-radius: 4px;" />
                    <el-skeleton-item variant="rect" style="width: 24px; height: 20px; border-radius: 4px;" />
                  </div>
                </div>
              </div>
            </template>

            <template #default>
              <el-empty class="dark-empty"
                v-if="validHistoryList.length === 0 && !historyLoading && historyParams.page === 1"
                :description="t('暂无历史记录')" />

              <div class="history-list" v-else>
                <div class="history-item" v-for="row in validHistoryList" :key="row.issue_no || row.section">
                  <div class="item-header">
                    <span class="issue-text">{{ row.issue_no || row.section }} {{ t('期') }}</span>
                    <span class="time-text">{{ row.day || row.open_time }}</span>
                  </div>

                  <div class="item-equation">
                    <template v-if="row.winning_array && row.winning_array.length >= 4">
                      <div class="circle">{{ row.winning_array[0] }}</div>
                      <span class="op">+</span>
                      <div class="circle">{{ row.winning_array[1] }}</div>
                      <span class="op">+</span>
                      <div class="circle">{{ row.winning_array[2] }}</div>
                      <span class="op">=</span>
                      <div class="circle result">{{ row.winning_array[3] }}</div>
                    </template>
                    <template v-else-if="row.openCode1 !== undefined">
                      <div class="circle">{{ row.openCode1 }}</div>
                      <span class="op">+</span>
                      <div class="circle">{{ row.openCode2 }}</div>
                      <span class="op">+</span>
                      <div class="circle">{{ row.openCode3 }}</div>
                      <span class="op">=</span>
                      <div class="circle result">{{ Number(row.openCode1) + Number(row.openCode2) + Number(row.openCode3) }}
                      </div>
                    </template>
                  </div>

                  <div class="item-tags" v-if="row.combo || row.award">
                    <template v-if="row.combo">
                      <el-tag v-for="(tag, i) in row.combo" :key="'c' + i" :type="getTagType(tag)" effect="dark"
                        size="small">
                        {{ tag }}
                      </el-tag>
                    </template>
                    <template v-else-if="row.award">
                      <el-tag v-for="(tag, i) in row.award.slice(0, 3)" :key="'a' + i" :type="getTagType(tag)" effect="dark"
                        size="small" v-show="tag">
                        {{ tag }}
                      </el-tag>
                    </template>
                  </div>
                </div>
              </div>
            </template>
          </el-skeleton>

          <div class="scroll-status">
            <div v-if="historyLoading && historyParams.page > 1" class="loading-text">
              <el-icon class="is-loading">
                <Loading />
              </el-icon> {{ t('加载中...') }}
            </div>
            <div v-if="noMoreHistory && validHistoryList.length > 0" class="no-more-text">
              {{ t('没有更多记录了') }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="pc-entertainment-container" ref="containerRef">

      <el-skeleton :loading="loading" animated>
        <template #template>
          <div class="lottery-dashboard entertainment-dashboard">
            <div class="dash-section dash-left">
              <div class="brand-issue-block">
                <el-skeleton-item variant="rect" style="width: 70px; height: 32px; border-radius: 6px;" />
                <div class="issue-details">
                  <el-skeleton-item variant="text" style="width: 40px; margin-bottom: 4px;" />
                  <el-skeleton-item variant="text" style="width: 80px;" />
                </div>
              </div>
              <div class="compact-equation" style="gap: 6px;">
                <el-skeleton-item variant="rect" style="width: 32px; height: 32px; border-radius: 4px;" v-for="i in 4" :key="i" />
              </div>
              <div class="action-links-horizontal">
                <el-skeleton-item variant="text" style="width: 60px; margin-right: 12px;" />
                <el-skeleton-item variant="text" style="width: 60px; margin-right: 12px;" />
                <el-skeleton-item variant="text" style="width: 60px;" />
              </div>
            </div>

            <div class="dash-section dash-center">
              <el-skeleton-item variant="text" style="width: 120px; margin-bottom: 8px;" />
              <div class="modern-timer giant-timer">
                <el-skeleton-item variant="rect" class="time-block" />
                <span class="colon">:</span>
                <el-skeleton-item variant="rect" class="time-block" />
              </div>
              <el-skeleton-item variant="text" style="width: 180px; margin-top: 10px;" />
            </div>

            <div class="dash-section dash-right">
              <el-skeleton-item variant="text" style="width: 160px; margin-bottom: 12px;" />
              <div class="keno-balls-grid" style="width: 100%;">
                <div class="ball-row">
                  <el-skeleton-item variant="circle" class="small-ball" v-for="i in 10" :key="'skel1_'+i" />
                </div>
                <div class="ball-row">
                  <el-skeleton-item variant="circle" class="small-ball" v-for="i in 10" :key="'skel2_'+i" />
                </div>
              </div>
            </div>
          </div>

          <div class="betting-items-section" style="margin-top: 15px;">
            <div class="rule-group-card" v-for="i in 3" :key="'group_'+i">
              <div class="group-header">
                <div class="header-left">
                  <div class="decorate-bar"></div>
                  <el-skeleton-item variant="text" style="width: 80px;" />
                </div>
              </div>
              <div class="odds-grid" :style="{ gridTemplateColumns: `repeat(${gridColumns}, minmax(0, 1fr))` }">
                <el-skeleton-item variant="button" class="odds-btn" style="height: 44px; border: none;" v-for="j in gridColumns" :key="'btn_'+j" />
              </div>
            </div>
          </div>
        </template>

        <template #default>
          <div class="lottery-dashboard entertainment-dashboard" v-if="latestDraw && countdownInfo">
            <div class="bg-glow"></div>

            <div class="dash-section dash-left">
              <div class="brand-issue-block">
                <div class="bclc-logo-badge">{{ t('极速28') }}</div>
                <div class="issue-details">
                  <span class="issue-text">{{ latestDraw.issue_no || latestDraw.section }}{{ t('期') }}</span>
                </div>
              </div>

              <div class="compact-equation">
                <span class="num">{{ latestDraw.openCode1 }}</span><span class="op">+</span>
                <span class="num">{{ latestDraw.openCode2 }}</span><span class="op">+</span>
                <span class="num">{{ latestDraw.openCode3 }}</span><span class="op">=</span>
                <span class="num res">{{ latestSum }}</span>

                <div class="winnings-tags" v-if="countdownInfo?.winnings">
                  <el-tag size="small" effect="dark" type="success" v-if="countdownInfo.winnings.size">
                    {{ countdownInfo.winnings.size }}
                  </el-tag>
                  <el-tag size="small" effect="dark" type="warning" v-if="countdownInfo.winnings.odd_or_even">
                    {{ countdownInfo.winnings.odd_or_even }}
                  </el-tag>
                </div>
              </div>

              <div class="action-links-horizontal">
                <el-button link class="meta-link" @click="showDetailPopup = true">
                  <el-icon>
                    <DataAnalysis />
                  </el-icon>{{ t('开奖详情') }}
                </el-button>
                <!-- <el-divider direction="vertical" />
                <el-button link class="meta-link" @click="router.push({ name: 'EntertainmentHistory' })">
                  <el-icon>
                    <Calendar />
                  </el-icon>{{ t('往期历史') }}
                </el-button> -->
                <el-divider direction="vertical" />
                <el-button link class="meta-link" @click="goRule">
                  <el-icon>
                    <Document />
                  </el-icon>{{ t('玩法规则') }}
                </el-button>
              </div>
            </div>

            <div class="dash-section dash-center" :class="{ 'is-urgent': timeLeft <= 30 && timeLeft > 0 && !isFengpan }">
              <div class="timer-title">{{ t('距下期封盘还剩') }}</div>

              <template v-if="!isFengpan">
                <div class="modern-timer giant-timer">
                  <template v-if="formatTime.h !== '00'">
                    <div class="time-block">
                      <span class="num">{{ formatTime.h }}</span>
                      <span class="label">{{ t('时') }}</span>
                    </div>
                    <span class="colon">:</span>
                  </template>

                  <div class="time-block">
                    <span class="num">{{ formatTime.m }}</span>
                    <span class="label">{{ t('分') }}</span>
                  </div>
                  <span class="colon">:</span>

                  <div class="time-block is-seconds">
                    <span class="num">{{ formatTime.s }}</span>
                    <span class="label">{{ t('秒') }}</span>
                  </div>
                </div>
              </template>
              <template v-else>
                <div class="fengpan-text" style="color: #f8b932; font-size: 24px; font-weight: bold; margin: 10px 0;">
                  {{ t('封盘中') }}
                </div>
              </template>

              <div class="current-bet-issue"
              >{{ t('第') }} <span class="highlight">{{ countdownInfo.issue_no }}</span> {{ t('期正在下注') }}</div>
            </div>

            <div class="dash-section dash-right">
              <div class="results-info-header">
                {{ t('第') }} <span class="highlight">{{ latestDraw.issue_no || latestDraw.section }}</span> 期 {{ t('开奖号码') }}
              </div>

              <div class="keno-balls-grid">
                <div class="ball-row">
                  <div class="small-ball" v-for="idx in 10" :key="'row1_' + idx"
                    :class="latestDraw.keno?.[idx - 1] ? getBallColor(latestDraw.keno[idx - 1]) : 'is-empty'">
                    <div class="ball-inner">{{ latestDraw.keno?.[idx - 1] || '' }}</div>
                  </div>
                </div>
                <div class="ball-row">
                  <div class="small-ball" v-for="idx in 10" :key="'row2_' + idx"
                    :class="latestDraw.keno?.[idx + 9] ? getBallColor(latestDraw.keno[idx + 9]) : 'is-empty'">
                    <div class="ball-inner">{{ latestDraw.keno?.[idx + 9] || '' }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="betting-items-section">
            <div v-for="(rules, groupName) in groupedRules" :key="groupName" class="rule-group-card">
              <div class="group-header">
                <div class="header-left">
                  <div class="decorate-bar"></div>
                  <span class="title">{{ groupName || t('其他玩法') }}</span>
                </div>
                <div class="header-right" v-if="hasMore(groupName, rules)">
                  <el-button link type="primary" @click="toggleExpand(groupName)">
                    {{ isExpanded(groupName) ? t('收起') : t('展开全部') }}
                    <el-icon class="ml-1">
                      <ArrowUp v-if="isExpanded(groupName)" />
                      <ArrowDown v-else />
                    </el-icon>
                  </el-button>
                </div>
              </div>

              <div class="odds-grid" :style="{ gridTemplateColumns: `repeat(${gridColumns}, minmax(0, 1fr))` }">
                <div class="odds-btn" v-for="item in getVisibleRules(groupName, rules)" :key="item.id" :class="{
                  'is-active': isSelected(item.id),
                  'is-disabled': Number(item.odds) <= 0 || isFengpan
                }" @click="!isFengpan && Number(item.odds) > 0 && handleToggleSelect(item)">
                  <div class="selection-info">
                    <span class="keyword" :title="item.keywords">{{ item.keywords }}</span>
                  </div>
                  <div class="odds-val-info">
                    <span class="odds-val" v-if="!isFengpan && Number(item.odds) > 0">{{ Number(item.odds).toFixed(2) }}</span>
                    <span class="odds-val" v-else>--</span>
                  </div>
                </div>
                <div class="odds-btn expand-btn" v-if="!isExpanded(groupName) && hasMore(groupName, rules)"
                  @click="toggleExpand(groupName)">
                  <span class="plus-icon">+</span>
                  <span class="remain-count">{{ getRemainCount(rules) }}</span>
                </div>
              </div>
            </div>
            <el-empty v-if="Object.keys(groupedRules).length === 0 && !loading" :description="t('暂无玩法数据')" />
          </div>
        </template>
      </el-skeleton>

      <el-dialog v-model="showDetailPopup" :title="`${latestDraw?.issue_no || latestDraw?.section} ${t('期 开奖详情')}`"
        width="700px" center custom-class="dark-dialog">
        <div class="dialog-equation" v-if="latestDraw">
          <div class="calc-circle">{{ latestDraw.openCode1 }}</div>
          <span class="op">+</span>
          <div class="calc-circle">{{ latestDraw.openCode2 }}</div>
          <span class="op">+</span>
          <div class="calc-circle">{{ latestDraw.openCode3 }}</div>
          <span class="op">=</span>
          <div class="calc-circle result">{{ latestSum }}</div>
        </div>
        <div class="eighty-grid">
          <div class="grid-ball" v-for="i in 80" :key="i" :class="getGridCellClass(i)">
            <div class="ball-inner-box">
              <div class="ball-inner">{{ i }}</div>
            </div>
          </div>
        </div>
      </el-dialog>
      <PlayingMethod v-model="playingMethodShow" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { DataAnalysis, Calendar, Document, ArrowUp, ArrowDown, ArrowLeft, Loading } from '@element-plus/icons-vue';
import { getGameRuleList, gameLotteryStatus } from "@/request/api.js";
import { useExtremeSpeed28CartStore } from "@/store/ExtremeSpeed28Cart.js";
import PlayingMethod from '@/businessComponents/PlayingMethod/index.vue'
import socket from '@/utils/websocket.js'
import { apiUrl } from "@/request/index";

const { t, locale } = useI18n();
const router = useRouter();
const cartStore = useExtremeSpeed28CartStore();

const loading = ref(true); // 将初始化改为true，便于首次呈现骨架屏
const latestDraw = ref(null);
const countdownInfo = ref(null);
const showDetailPopup = ref(false);
const playingMethodShow = ref(false);
const ruleList = ref([]);
const timeLeft = ref(0);
const isFengpan = ref(false); // 新增：是否处于封盘状态
let timer = null;
const apiBasePath = 'newPc';

/* ================= 动态列数监听逻辑 (修复版) ================= */
const containerRef = ref(null); // 绑定到右侧容器
const gridColumns = ref(12);
let resizeObserver = null;

const updateColumns = (width) => {
  // width 是右侧可用区域的实际宽度
  if (width >= 1600) {
    gridColumns.value = 12;
  } else if (width >= 1400) {
    gridColumns.value = 10;
  } else if (width >= 1200) {
    gridColumns.value = 8;
  } else if (width >= 992) {
    gridColumns.value = 6;
  } else {
    gridColumns.value = 4;
  }
};

// 获取可见的投注项列表
const getVisibleRules = (groupName, rules) => {
  if (groupName === '热门' || isExpanded(groupName)) return rules;
  if (rules.length > gridColumns.value) {
    return rules.slice(0, gridColumns.value - 1);
  }
  return rules;
};

// 判断是否还有更多需要展开
const hasMore = (groupName, rules) => {
  return groupName !== '热门' && rules.length > gridColumns.value;
};

// 获取剩余未展开数量
const getRemainCount = (rules) => {
  return rules.length - (gridColumns.value - 1);
};
/* ================= 结束 ================= */

/* ================= 无限滚动历史记录侧边栏逻辑 ================= */
const isSidebarOpen = ref(false);
const historyLoading = ref(false);
const historyList = ref([]);
const historyTotal = ref(0);

const historyParams = ref({
  page: 1,
  limit: 20
});

const validHistoryList = computed(() => {
  return historyList.value.filter(item => {
    return (item.winning_array && item.winning_array.length >= 4) ||
      (item.openCode1 !== undefined && item.openCode1 !== null);
  });
});

const noMoreHistory = computed(() => {
  return historyList.value.length >= historyTotal.value && historyTotal.value > 0;
});

const openSidebar = () => {
  isSidebarOpen.value = true;
  if (historyList.value.length === 0) {
    historyParams.value.page = 1;
    fetchHistoryData();
  }
};

const fetchHistoryData = async () => {
  if (historyLoading.value) return;
  historyLoading.value = true;
  try {
    const params = {
      page: historyParams.value.page,
      limit: historyParams.value.limit
    };

    // --- 修改点：获取 Token 并加入 headers ---
    const token = localStorage.getItem('token');
    const response = await fetch(`${apiUrl}${apiBasePath}?page=${params.page}&limit=${params.limit}`, {
      headers: {
        'lang': locale.value
      }
    });
    // ---------------------------------------

    const res = await response.json();
    if (res && res.code === 0 && res.data && res.data.data) {
      if (params.page === 1) {
        historyList.value = res.data.data;
      } else {
        historyList.value = [...historyList.value, ...res.data.data];
      }
      historyTotal.value = res.data.total || 0;
    } else {
      if (params.page === 1) historyList.value = [];
    }
  } catch (error) {
    console.error('获取历史记录失败', error);
  } finally {
    historyLoading.value = false;
  }
};

const loadMoreHistory = () => {
  if (historyLoading.value || noMoreHistory.value) return;
  historyParams.value.page += 1;
  fetchHistoryData();
};

const getTagType = (text) => {
  if (['大', '双', '极大'].includes(text)) return 'danger';
  if (['小', '单', '极小'].includes(text)) return 'success';
  return 'primary';
};
/* ================= 结束 ================= */

/* 原主页面逻辑 */
const getLatestYuanTou = async () => {
  try {
    const token = localStorage.getItem('token');
    const res = await fetch(`${apiUrl}${apiBasePath}/yuanTou`, {
      headers: {
        'lang': locale.value,
      }
    });
    return await res.json();
  } catch (e) { return { code: -1 }; }
};

const getCountdown = async () => {
  try {
    const token = localStorage.getItem('token');
    const res = await fetch(`${apiUrl}${apiBasePath}/countdown`, {
      headers: {
        'lang': locale.value,
      }
    });
    return await res.json();
  } catch (e) { return { code: -1 }; }
};

const initData = async () => {
  loading.value = true;

  gameLotteryStatus({ type: 2 }).then((res) => {
    if(res && res.data) {
      if(res.data.is_kaipan == 0) {
         isFengpan.value = true;
      } else if(res.data.is_kaipan == 1) {
         isFengpan.value = false;
      }
    }
  }).catch(e => console.error(e));

  await Promise.all([fetchTopData(), fetchRules()]);
  loading.value = false;
};

const fetchTopData = async () => {
  const [yuanTouRes, countRes] = await Promise.all([getLatestYuanTou(), getCountdown()]);
  if (yuanTouRes.code === 0 && yuanTouRes.data.length > 0) latestDraw.value = yuanTouRes.data[0];
  if (countRes.code === 0 && countRes.data) {
    countdownInfo.value = countRes.data;
    startCountdown(countRes.data.end_time, countRes.data.current_time);
  }
};

const fetchRules = async () => {
  try {
    const res = await getGameRuleList({ page: 1, limit: 999 });
    if (res.code === 1 && res.data && res.data.list) ruleList.value = res.data.list.reverse();
  } catch (e) { console.error(e); }
};

const startCountdown = (endTime, currentTime) => {
  clearInterval(timer);
  const diff = endTime - currentTime;
  timeLeft.value = Math.max(0, diff);
  if (diff > 0) {
    timer = setInterval(() => {
      if (timeLeft.value > 0) timeLeft.value--;
      else clearInterval(timer);
    }, 1000);
  }
};

const formatTime = computed(() => {
  const h = Math.floor(timeLeft.value / 3600).toString().padStart(2, '0');
  const m = Math.floor((timeLeft.value % 3600) / 60).toString().padStart(2, '0');
  const s = (timeLeft.value % 60).toString().padStart(2, '0');
  return { h, m, s };
});

const latestSum = computed(() => {
  if (!latestDraw.value) return 0;
  return Number(latestDraw.value.openCode1 || 0) + Number(latestDraw.value.openCode2 || 0) + Number(latestDraw.value.openCode3 || 0);
});

const getBallColor = (numStr) => parseInt(numStr, 10) % 2 === 0 ? 'red-ball' : 'blue-ball';

const getGridCellClass = (num) => {
  if (!latestDraw.value || !latestDraw.value.keno) return '';
  return latestDraw.value.keno.some(k => Number(k) === num) ? (num % 2 === 0 ? 'bg-red' : 'bg-blue') : '';
};

const groupedRules = computed(() => {
  const map = {};
  ruleList.value.forEach(rule => {
    let group = rule.groups || '其他';
    const idNum = Number(rule.id);
    // if (idNum >= 1 && idNum <= 8) group = '热门';
    if (!map[group]) map[group] = [];
    map[group].push(rule);
  });
  const sortedMap = {};
  if (map['热门']) { sortedMap['热门'] = map['热门']; delete map['热门']; }
  Object.keys(map).forEach(key => sortedMap[key] = map[key]);
  return sortedMap;
});

const expandedGroups = ref({});
const isExpanded = (groupName) => !!expandedGroups.value[groupName];
const toggleExpand = (groupName) => expandedGroups.value[groupName] = !expandedGroups.value[groupName];

const isSelected = (id) => cartStore.selectOrders.some(item => item.uniqueKey === id);
const handleToggleSelect = (rule) => cartStore.toggleOrderItem(rule);

const goRule = () => playingMethodShow.value = true;

const handleSocketMessage = (e) => {
  try {
    const res = e.detail;
    if (!res) return;
    if (res.type === 'new_jisu_issue') {
      const currentIssue = countdownInfo.value?.issue_no;
      if (currentIssue !== res.message) {
        fetchTopData();
        if (isSidebarOpen.value) {
          historyParams.value.page = 1;
          fetchHistoryData(); // 如果有新一期，则刷新侧边栏
        }

        gameLotteryStatus({ type: 2 }).then((res) => {
          if(res && res.data) {
            if(res.data.is_kaipan == 0) {
              isFengpan.value = true;
            } else if(res.data.is_kaipan == 1) {
              isFengpan.value = false;
            }
          }
        }).catch(e => console.error(e));
      }
    } else if (res.type === 'jisu_fengpan') {
      isFengpan.value = true;
    } else if (res.type === 'jisu_kaipan') {
      isFengpan.value = false;
    }
  } catch (err) { console.error('WS 解析失败', err); }
};

onMounted(() => {
  initData();
  socket.eventBus.addEventListener('onSocketMessage', handleSocketMessage);

  // 初始化容器宽度监听
  resizeObserver = new ResizeObserver((entries) => {
    for (let entry of entries) {
      updateColumns(entry.contentRect.width);
    }
  });
  if (containerRef.value) {
    resizeObserver.observe(containerRef.value);
  }
});

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

  if (resizeObserver && containerRef.value) {
    resizeObserver.unobserve(containerRef.value);
    resizeObserver.disconnect();
  }
});
</script>

<style scoped lang="scss">
$main-color: #f8b932;
$selected-color: #f2ba45;
$card-bg: var(--el-bg-color-overlay);
$border-color: var(--el-border-color-light);
$bg-dark: #141414;
$bg-sidebar: #1e1e1e;
$bg-sidebar-hover: #2a2a2a;

/* =======================================
   全局布局
   ======================================= */
.lottery-page-layout {
  display: flex;
  height: 100%;
  min-height: calc(100vh - 64px);
  background-color: $bg-dark;
  overflow: hidden;
}

/* =======================================
   左侧：折叠历史侧边栏
   ======================================= */
.recent-sidebar-container {
  height: 100%;
  background-color: $bg-sidebar;
  border-right: 1px solid rgba(255, 255, 255, 0.08);
  display: flex;
  flex-direction: column;
  transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  z-index: 100;
  box-shadow: 4px 0 20px rgba(0, 0, 0, 0.3);

  &.is-collapsed {
    width: 50px !important;
  }

  &:not(.is-collapsed) {
    width: 330px !important;
  }

  .sidebar-collapsed {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
    padding-top: 20px;
    transition: background 0.3s;

    &:hover {
      background-color: $bg-sidebar-hover;
    }

    .custom-icon {
      position: relative;
      margin-bottom: 20px;
      display: flex;
      justify-content: center;
      align-items: center;

      .icon-color {
        color: $main-color;
      }
    }

    .vertical-text {
      writing-mode: vertical-rl;
      letter-spacing: 4px;
      font-weight: bold;
      color: #e5e5e5;
    }
  }

  .sidebar-expanded {
    display: flex;
    flex-direction: column;
    height: 100%;

    /* 头部 */
    .sidebar-header {
      height: 60px;
      flex-shrink: 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 16px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.08);
      background-color: $bg-sidebar;
      cursor: pointer;
      transition: background 0.2s;

      &:hover {
        background-color: $bg-sidebar-hover;
      }

      .header-left {
        display: flex;
        align-items: center;
        gap: 8px;
        color: $main-color;

        .header-text {
          font-weight: bold;
          color: #e5e5e5;
          font-size: 15px;
        }
      }

      .close-icon {
        color: #999;
        transition: color 0.2s;

        &:hover {
          color: $main-color;
        }
      }
    }

    /* 列表主体 */
    .sidebar-body {
      flex: 1;
      overflow-y: auto;
      padding: 12px;
      background-color: $bg-dark;

      &::-webkit-scrollbar {
        width: 6px;
      }

      &::-webkit-scrollbar-track {
        background: transparent;
      }

      &::-webkit-scrollbar-thumb {
        background: #333;
        border-radius: 4px;
      }

      &::-webkit-scrollbar-thumb:hover {
        background: #555;
      }

      .history-list {
        display: flex;
        flex-direction: column;
        gap: 12px;
      }

      .history-item {
        background-color: $bg-sidebar;
        border-radius: 8px;
        padding: 12px;
        border: 1px solid rgba(255, 255, 255, 0.05);
        transition: transform 0.2s, border-color 0.2s;

        &:hover {
          border-color: rgba(248, 185, 50, 0.3);
          transform: translateY(-2px);
        }

        .item-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;

          .issue-text {
            color: var(--el-color-danger);
            font-size: 14px;
            font-weight: bold;
            font-family: DIN, monospace;
          }

          .time-text {
            color: #888;
            font-size: 12px;
          }
        }

        .item-equation {
          display: flex;
          align-items: center;
          gap: 6px;
          margin-bottom: 12px;

          .circle {
            width: 26px;
            height: 26px;
            border-radius: 50%;
            background-color: #2a2a2a;
            border: 1px solid #444;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 13px;
            font-weight: bold;
            color: #fff;

            &.result {
              background-color: var(--el-color-danger);
              border: none;
              font-size: 14px;
              box-shadow: 0 1px 4px rgba(245, 108, 108, 0.4);
            }
          }

          .op {
            color: #777;
            font-weight: bold;
            font-size: 16px;
          }
        }

        .item-tags {
          display: flex;
          flex-wrap: wrap;
          gap: 6px;
          padding-top: 10px;
          border-top: 1px dashed rgba(255, 255, 255, 0.05);
        }
      }

      /* 无限滚动状态提示 */
      .scroll-status {
        text-align: center;
        padding: 15px 0;
        font-size: 12px;
        color: #888;

        .loading-text {
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 6px;
        }
      }
    }
  }
}

/* =======================================
   右侧：主内容区
   ======================================= */
.pc-entertainment-container {
  flex: 1;
  container-type: inline-size;
  container-name: entertainment-container;
  min-height: 100%;
  padding: 10px 15px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 15px;
  overflow-y: auto;
}

/* 仪表盘 */
.lottery-dashboard {
  position: relative;
  background: linear-gradient(180deg, #1f1f1f 0%, #111111 100%);
  border-radius: 10px;
  border: 1px solid rgba(255, 255, 255, 0.08);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.2);
  padding: 24px 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  @container entertainment-container (max-width: 700px) {
    flex-direction: column;

    .dash-right {
      margin-top: 20px;
      align-items: center !important;
    }

    .dash-left,
    .dash-right,
    .dash-center {
      width: 100%;
      align-items: center;
      justify-content: center;
      text-align: center;
    }
  }

  @container entertainment-container (max-width: 1100px) {
    padding: 20px;
    flex-wrap: wrap;
    gap: 15px;
  }

  .bg-glow {
    position: absolute;
    top: -100px;
    left: 50%;
    transform: translateX(-50%);
    width: 500px;
    height: 300px;
    background: radial-gradient(circle, rgba(242, 186, 69, 0.1) 0%, transparent 70%);
    pointer-events: none;
    z-index: 0;
  }

  .dash-section {
    position: relative;
    z-index: 2;
    flex: 1;
    min-width: 310px;
  }

  .dash-left {
    display: flex;
    flex-direction: column;
    gap: 15px;
    flex: none;
    width: 220px;

    @container entertainment-container (max-width: 900px) {
      width: auto;
      flex: 1;
      order: 1;
    }

    .brand-issue-block {
      display: flex;
      align-items: center;
      gap: 12px;

      .bclc-logo-badge {
        font-size: 18px;
        font-weight: 900;
        color: #fff;
        background: linear-gradient(135deg, #d32f2f 0%, #ff1744 100%);
        padding: 6px 12px;
        border-radius: 6px;
        font-family: 'Arial Black', sans-serif;
        box-shadow: 0 4px 10px rgba(211, 47, 47, 0.3);
      }

      .issue-details {
        display: flex;
        flex-direction: column;
        gap: 2px;

        .label {
          font-size: 13px;
          color: #888;
        }

        .issue-text {
          font-size: 13px;
          font-weight: bold;
          color: var(--el-color-danger);
        }
      }
    }

    .action-links-horizontal {
      display: flex;
      align-items: center;
      gap: 2px;

      .meta-link {
        font-size: 12px;
        color: #aaa;
        padding: 0;

        .el-icon {
          margin-right: 3px;
        }

        &:hover {
          color: $main-color;
        }
      }

      .el-divider {
        border-color: rgba(255, 255, 255, 0.1);
        margin: 0 6px;
      }
    }
  }

  .dash-center {
    flex: none;
    width: 300px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 8px;
    border-radius: 10px;
    padding: 15px;

    @container entertainment-container (max-width: 1100px) {
      order: 3;
      width: 100%;
    }

    .timer-title {
      font-size: 13px;
      color: #888;
      text-transform: uppercase;
      letter-spacing: 1px;
    }

    .giant-timer {
      gap: 12px;

      .time-block {
        width: 60px;
        height: 75px;
        border-radius: 8px;
        box-shadow: 0 6px 16px rgba(0, 0, 0, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.05);

        .num {
          font-size: 38px;
        }

        .label {
          font-size: 12px;
          margin-top: 5px;
        }
      }

      .colon {
        font-size: 32px;
        margin-bottom: 20px;
      }
    }

    .current-bet-issue {

      font-size: 18px;
      color: #fff;
      font-weight: bold;
      padding: 10px 20px;

      .highlight {
        color: #67c23a;
        font-weight: 900;
        font-family: DIN, monospace;
        font-size: 22px;
      }
    }

    &.is-urgent {

      .modern-timer .time-block .num,
      .modern-timer .colon {
        color: #f56c6c !important;
        text-shadow: 0 0 10px rgba(245, 108, 108, 0.5) !important;
      }
    }
  }

  .dash-right {
    flex: none;
    width: 320px;
    display: flex;
    flex-direction: column;
    gap: 12px;
    align-items: flex-end;

    @container entertainment-container (max-width: 1100px) {
      order: 2;
      flex: 1;
      align-items: flex-end;
    }

    .results-info-header {
      font-size: 16px;
      color: #ccc;

      .highlight {
        color: $main-color;
        font-weight: bold;
        font-family: DIN, monospace;
      }
    }

    .keno-balls-grid {
      display: flex;
      flex-direction: column;
      gap: 8px;
      background: rgba(0, 0, 0, 0.3);
      padding: 12px;
      border-radius: 8px;
      border: 1px solid rgba(255, 255, 255, 0.05);

      .ball-row {
        display: flex;
        gap: 6px;
        justify-content: space-between;

        .small-ball {
          width: 32px;
          height: 32px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 13px;
          font-weight: bold;
          color: #fff;
          flex-shrink: 0;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);

          .ball-inner {
            width: 80%;
            height: 80%;
            line-height: 1;
            background: #fff;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 15px;
            font-weight: bold;
            color: #333;
          }

          &.blue-ball {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
          }

          &.red-ball {
            background: linear-gradient(135deg, #ff416c 0%, #ff4b2b 100%);
          }

          &.is-empty {
            background: #333;
            color: transparent;
            box-shadow: none;
            border: 1px solid #444;
          }
        }
      }
    }
  }
}

.compact-equation {
  display: flex;
  align-items: center;
  gap: 0;
  border-radius: 20px;
  font-size: 16px;

  .num {
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #2a2a2a;
    border-radius: 4px;
    color: #fff;
    font-size: 18px;
    font-weight: bold;
    box-sizing: border-box;
    flex-shrink: 0;

    &.res {
      background: var(--el-color-danger);
      box-shadow: 0 0 8px rgba(245, 108, 108, 0.4);
    }
  }

  .op {
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #666;
    font-weight: bold;
    font-size: 20px;
    box-sizing: border-box;
    flex-shrink: 0;
  }

  .winnings-tags {
    display: flex;
    gap: 4px;
    margin-left: 6px;

    .el-tag {
      width: 32px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0;
      font-size: 13px;
      box-sizing: border-box;
      flex-shrink: 0;
    }
  }
}

.modern-timer {
  display: flex;
  align-items: center;

  .time-block {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: linear-gradient(180deg, #2a2a2a 0%, #1a1a1a 100%);
    border: 1px solid #333;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.1);

    .num {
      font-weight: bold;
      color: #fff;
      line-height: 1;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
      transition: color 0.3s;
    }

    .label {
      color: #777;
      transition: color 0.3s;
    }

    &.is-seconds .num {
      color: $selected-color;
      text-shadow: 0 0 10px rgba(242, 186, 69, 0.4);
    }
  }

  .colon {
    font-weight: bold;
    color: #666;
    animation: colon-blink 1s infinite ease-in-out;
    transition: color 0.3s;
  }
}

@keyframes colon-blink {

  0%,
  100% {
    opacity: 1;
  }

  50% {
    opacity: 0.2;
  }
}

.betting-items-section {
  display: flex;
  flex-direction: column;
  gap: 8px;

  .rule-group-card {
    background-color: $card-bg;
    border-radius: 6px;
    border: 1px solid var(--el-border-color-light);
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02);

    .group-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 6px 12px;
      background-color: var(--el-fill-color-light);
      border-bottom: 1px solid var(--el-border-color-lighter);

      @container entertainment-container (max-width: 550px) {
        padding: 4px 8px;
      }

      .header-left {
        display: flex;
        align-items: center;

        .decorate-bar {
          width: 3px;
          height: 10px;
          background-color: $main-color;
          border-radius: 2px;
          margin-right: 6px;
        }

        .title {
          font-size: 12px;
          font-weight: bold;
          color: var(--el-text-color-primary);
        }
      }

      .el-button {
        height: 18px;
        font-size: 11px;
        padding: 0;
      }
    }

    .odds-grid {
      padding: 8px 12px;
      display: grid;
      gap: 6px;

      @container entertainment-container (max-width: 550px) {
        padding: 6px 8px;
        gap: 4px;
      }

      /* 【已经清除了原来的 auto-fill css】 */

      .odds-btn {
        background-color: var(--el-bg-color);
        border: 1px solid var(--el-border-color);
        border-radius: 4px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 8px;
        cursor: pointer;
        transition: all 0.2s;
        min-width: 0;

        @container entertainment-container (max-width: 996px) {
            padding: 10px 6px;
        }
        @container entertainment-container (max-width: 550px) {
          flex-direction: column;
          justify-content: center;
          gap: 0px;
        }

        .selection-info {
          display: flex;
          align-items: center;
          min-width: 0;
          flex: 1;
          margin-right: 4px;

          @container entertainment-container (max-width: 550px) {
            margin-right: 0;
            flex: none;
          }

          .keyword {
            font-size: 14px;
            color: var(--el-text-color-regular);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            @container entertainment-container (max-width: 1200px) {
              font-size: 13px;
            }

            @container entertainment-container (max-width: 550px) {
              font-size: 12px;
            }
          }
        }

        .odds-val-info {
          display: flex;
          align-items: center;
          gap: 2px;
          flex-shrink: 0;

          .odds-val {
            font-size: 13px;
            font-weight: bold;
            color: #f8b932;

            @container entertainment-container (max-width: 550px) {
              font-size: 12px;
              color: $main-color;
            }
          }
        }

        &:hover {
          border-color: $main-color;
          background-color: var(--el-color-primary-light-9);
        }

        &.is-active {
          background-color: $selected-color;
          border-color: $selected-color;

          .selection-info .keyword,
          .odds-val-info .odds-val {
            color: #f2f2f2;
            font-weight: 900;
          }
        }

        &.is-disabled {
          opacity: 0.5;
          background-color: var(--el-fill-color-darker);
          cursor: not-allowed;

          &:hover {
            border-color: var(--el-border-color);
            background-color: var(--el-fill-color-darker);
          }

          .odds-val-info .odds-val {
            color: var(--el-text-color-placeholder);
          }
        }

        &.expand-btn {
          justify-content: center;
          background-color: transparent;
          border: 1px dashed var(--el-border-color-darker);

          @container entertainment-container (max-width: 550px) {
            flex-direction: row;
            height: 32px;
          }

          .plus-icon {
            font-size: 13px;
            color: var(--el-text-color-secondary);
            margin-right: 2px;
          }

          .remain-count {
            font-size: 11px;
            font-weight: bold;
            color: var(--el-text-color-secondary);
          }

          &:hover {
            border-color: $main-color;

            .plus-icon,
            .remain-count {
              color: $main-color;
            }
          }
        }
      }
    }
  }
}

.dialog-equation {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 8px;

  .calc-circle {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    border: 2px solid var(--el-border-color-darker);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    font-weight: bold;
    color: var(--el-text-color-primary);
    background-color: var(--el-fill-color-darker);

    @media screen and (max-width: 550px) {
      width: 30px;
      height: 30px;
      font-size: 13px;
    }

    &.result {
      background-color: var(--el-color-danger);
      border: none;
      color: #fff;
      box-shadow: 0 2px 8px rgba(245, 108, 108, 0.5);
    }
  }

  .op {
    font-size: 18px;
    color: var(--el-text-color-regular);
    font-weight: bold;
    margin: 0;

    @media screen and (max-width: 550px) {
      font-size: 14px;
    }
  }
}

.eighty-grid {
  display: grid;
  grid-template-columns: repeat(10, 1fr);
  gap: 6px;
  background-color: var(--el-fill-color-darker);
  padding: 12px;
  border-radius: 6px;
  box-shadow: inset 0 1px 6px rgba(0, 0, 0, 0.1);

  @media screen and (max-width: 550px) {
    padding: 8px;
    gap: 4px;
    border-radius: 4px;
  }

  .grid-ball {
    aspect-ratio: 1;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: var(--el-fill-color);
    border: 1px solid var(--el-border-color-darker);
    box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.1);

    .ball-inner {
      width: 80%;
      height: 80%;
      background: #424243;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 13px;
      font-weight: bold;
      color: #e5eaf3;

      &-box {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }

    &.bg-red {
      background: linear-gradient(135deg, #ff416c 0%, #ff4b2b 100%);
      border: none;
      box-shadow: 0 1px 4px rgba(255, 65, 108, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.3);

      .ball-inner {
        // color: #fff;
        text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
      }
    }

    &.bg-blue {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      border: none;
      box-shadow: 0 1px 4px rgba(79, 172, 254, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.3);

      .ball-inner {
        // color: #fff;
        text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
      }
    }
  }
}
</style>
