<template>
  <div class="iptv-app">
    <!-- 调试信息面板 -->
    <div v-if="showDebug" class="debug-panel">
      <div class="debug-header">
        <span>调试信息</span>
        <button @click="showDebug = false">×</button>
      </div>
      <div class="debug-content">
        <p><strong>URL:</strong> {{ debugInfo.url }}</p>
        <p><strong>协议:</strong> {{ debugInfo.protocol }}</p>
        <p><strong>路径:</strong> {{ debugInfo.loadPath }}</p>
        <p><strong>状态:</strong> {{ debugInfo.status }}</p>
        <p><strong>错误:</strong> {{ debugInfo.error || '无' }}</p>
        <hr>
        <button @click="retryLoad">重新加载</button>
        <button @click="copyDebug">复制日志</button>
      </div>
    </div>
    
    <!-- 调试按钮 -->
    <button v-if="!showDebug" class="debug-toggle" @click="showDebug = true">🐛</button>
    
    <!-- 加载中 -->
    <div v-if="loading" class="loading-screen">
      <div class="spinner"></div>
      <p>{{ loadingText }}</p>
      <p class="debug-hint">长按屏幕显示调试信息</p>
    </div>
    
    <!-- 错误提示 -->
    <div v-else-if="error" class="error-screen">
      <div class="error-icon">⚠️</div>
      <h3>加载失败</h3>
      <p>{{ error }}</p>
      <button @click="loadChannels">重试</button>
    </div>
    
    <!-- 主界面 -->
    <template v-else>
      <!-- 三栏主布局 -->
      <div class="main-container">
        <!-- 左侧：频道分组 -->
        <aside class="sidebar-left">
          <div class="sidebar-header">
            <span class="icon">📡</span>
            <span>频道分组</span>
          </div>
          <div class="group-list">
            <div 
              v-for="group in groupList" 
              :key="group.id"
              class="group-item"
              :class="{ active: selectedGroup === group.id }"
              @click="selectGroup(group.id)"
            >
              <span class="group-icon">{{ group.icon }}</span>
              <span class="group-name">{{ group.name }}</span>
              <span class="group-count">{{ group.count }}</span>
              <span class="arrow">›</span>
            </div>
          </div>
        </aside>

        <!-- 中间：频道列表 -->
        <section class="channel-panel">
          <div class="panel-header">
            <span class="icon">⏱</span>
            <span>{{ currentGroupName }}</span>
          </div>
          <div class="channel-list">
            <div 
              v-for="channel in filteredChannels" 
              :key="channel.id"
              class="channel-item"
              :class="{ active: currentChannel?.id === channel.id }"
              @click="playChannel(channel)"
            >
              <div class="channel-icon">CC</div>
              <div class="channel-info">
                <div class="channel-name">{{ channel.name }}</div>
                <div class="channel-meta">{{ channel.sources?.length || 1 }}线路</div>
              </div>
              <span 
                class="star-icon"
                :class="{ favorited: isFavorite(channel.id) }"
                @click.stop="toggleFavorite(channel.id)"
              >★</span>
            </div>
          </div>
        </section>

        <!-- 右侧：节目表/播放器 -->
        <section class="epg-panel">
          <div class="panel-header">
            <span class="icon">📋</span>
            <span>节目表</span>
          </div>
          
          <!-- 节目列表 -->
          <div v-if="currentChannel && epgList.length > 0" class="epg-list">
            <div 
              v-for="(item, index) in epgList" 
              :key="index"
              class="epg-item"
              :class="{ current: isCurrentProgram(item) }"
            >
              <div class="epg-time">{{ item.time }}</div>
              <div class="epg-title">
                {{ item.title }}
                <span v-if="isCurrentProgram(item)" class="live-badge">直播</span>
              </div>
            </div>
          </div>
          
          <!-- 无节目信息 -->
          <div v-else-if="currentChannel" class="epg-empty">
            <p>暂无节目信息</p>
          </div>
          
          <!-- 未选择频道 -->
          <div v-else class="player-placeholder">
            <div class="placeholder-icon">📹</div>
            <p>请选择频道</p>
            <p class="hint">按菜单键打开频道列表</p>
          </div>
        </section>
      </div>

      <!-- 底部播放控制栏 -->
      <footer v-if="currentChannel" class="player-bar">
        <div class="bar-left">
          <div class="channel-logo">CC</div>
          <div class="program-info">
            <div class="channel-line">
              <span class="channel-name">{{ currentChannel.name }}</span>
              <span class="line-tag">线路 {{ currentLine }}/{{ currentChannel.sources?.length || 1 }}</span>
            </div>
            <div class="program-title">
              <span class="live-dot">●</span>
              {{ currentProgramTitle }}
            </div>
            <div class="progress-bar">
              <div class="progress-fill" :style="{ width: programProgress + '%' }"></div>
              <span class="time-label">{{ currentTime }} / {{ totalTime }}</span>
            </div>
            <div class="next-program">下一节目: {{ nextProgramTitle }}</div>
          </div>
        </div>
        
        <div class="bar-right">
          <button 
            class="bar-btn"
            :class="{ active: isFavorite(currentChannel.id) }"
            @click="toggleFavorite(currentChannel.id)"
          >
            <span class="icon">★</span>
            <span>{{ isFavorite(currentChannel.id) ? '已收藏' : '收藏' }}</span>
          </button>
          <button class="bar-btn" @click="showSourceSelector = true">
            <span class="icon">↻</span>
            <span>切换线路</span>
          </button>
          <button class="bar-btn" @click="showConfig = true">
            <span class="icon">⚙</span>
            <span>设置</span>
          </button>
        </div>
      </footer>

      <!-- 播放器区域（全屏或嵌入） -->
      <div v-if="currentChannel" class="video-container">
        <VideoPlayer 
          ref="playerRef"
          :url="currentUrl"
          :title="currentChannel.name"
        />
      </div>

      <!-- 设置弹窗 -->
      <ConfigPanel 
        :show="showConfig" 
        @close="showConfig = false"
        @reload="loadChannels"
      />

      <!-- 线路选择弹窗 -->
      <div v-if="showSourceSelector" class="modal-overlay" @click="showSourceSelector = false">
        <div class="modal-content source-modal" @click.stop>
          <h3>切换线路</h3>
          <div class="source-list">
            <div 
              v-for="(src, index) in currentChannel?.sources" 
              :key="index"
              class="source-item"
              :class="{ active: currentUrl === src.url, online: src.status === 'online' }"
              @click="switchSource(src)"
            >
              <span class="source-name">线路 {{ index + 1 }}</span>
              <span v-if="src.status === 'online'" class="source-status online">● {{ src.delay }}ms</span>
              <span v-else-if="src.status === 'offline'" class="source-status offline">● 离线</span>
              <span v-else class="source-status">● 未检测</span>
            </div>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useStore } from './stores/useStore.js'
import VideoPlayer from './components/VideoPlayer.vue'
import ConfigPanel from './components/ConfigPanel.vue'
import { parseM3U } from './utils/m3uParser.js'
import { parseTXT } from './utils/txtParser.js'
import { mergeChannels } from './utils/channelOptimizer.js'
import { fetchEPG, getCurrentProgramme, getNextProgramme } from './utils/epgFetcher.js'
import { useMobile } from './composables/useMobile.js'

const store = useStore()
const { toggleFavorite, isFavorite, addToHistory, settings } = store
const { isMobile } = useMobile()

// ============ 状态 ============
const loading = ref(true)
const loadingText = ref('加载中...')
const error = ref(null)
const showDebug = ref(false)
const debugInfo = ref({
  url: '',
  protocol: '',
  loadPath: '',
  status: '',
  error: ''
})
const channels = ref([])
const currentChannel = ref(null)
const currentUrl = ref('')
const currentLine = ref(1)
const selectedGroup = ref('recent')
const playerRef = ref(null)
const showConfig = ref(false)
const showSourceSelector = ref(false)
const epgData = ref({})

// ============ 分组数据 ============
const groupList = computed(() => {
  const groups = [
    { id: 'recent', name: '最近播放', icon: '⏱', count: store.history.length },
    { id: 'favorite', name: '收藏频道', icon: '❤', count: store.favorites.size },
  ]
  
  // 动态添加实际分组
  const actualGroups = [...new Set(channels.value.map(c => c.group))]
  actualGroups.forEach((group, index) => {
    const count = channels.value.filter(c => c.group === group).length
    if (group === '央视频道') {
      groups.push({ id: group, name: group, icon: '📺', count })
    } else if (group === '卫视频道') {
      groups.push({ id: group, name: group, icon: '📡', count })
    } else if (group === '港澳台') {
      groups.push({ id: group, name: group, icon: '', count })
    } else if (group.includes('体育')) {
      groups.push({ id: group, name: group, icon: '⚽', count })
    } else {
      groups.push({ id: group, name: group, icon: '📺', count })
    }
  })
  
  return groups
})

const currentGroupName = computed(() => {
  const group = groupList.value.find(g => g.id === selectedGroup.value)
  return group?.name || '频道列表'
})

// ============ 频道过滤 ============
const filteredChannels = computed(() => {
  if (selectedGroup.value === 'recent') {
    // 最近播放
    const recentIds = store.history.slice(0, 20).map(h => h.id)
    return channels.value.filter(c => recentIds.includes(c.id))
      .sort((a, b) => recentIds.indexOf(a.id) - recentIds.indexOf(b.id))
  } else if (selectedGroup.value === 'favorite') {
    // 收藏频道
    return channels.value.filter(c => store.isFavorite(c.id))
  } else {
    // 普通分组
    return channels.value.filter(c => c.group === selectedGroup.value)
  }
})

// ============ EPG 相关 ============
const epgList = computed(() => {
  if (!currentChannel.value) return []
  const channelEpg = epgData.value[currentChannel.value.id] || []
  return channelEpg.slice(0, 10).map(p => ({
    time: new Date(p.start).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
    title: p.title,
    start: p.start,
    stop: p.stop
  }))
})

const currentProgramTitle = computed(() => {
  if (!currentChannel.value) return ''
  const current = getCurrentProgramme(epgData.value[currentChannel.value.id] || [])
  return current?.title || '精彩节目'
})

const nextProgramTitle = computed(() => {
  if (!currentChannel.value) return ''
  const next = getNextProgramme(epgData.value[currentChannel.value.id] || [])
  return next?.title || '暂无预告'
})

const programProgress = computed(() => {
  if (!currentChannel.value) return 0
  const current = getCurrentProgramme(epgData.value[currentChannel.value.id] || [])
  if (!current) return 0
  const now = new Date()
  const total = current.stop - current.start
  const elapsed = now - current.start
  return Math.min(100, Math.max(0, (elapsed / total) * 100))
})

const currentTime = computed(() => {
  const now = new Date()
  return now.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
})

const totalTime = computed(() => {
  if (!currentChannel.value) return '--:--'
  const current = getCurrentProgramme(epgData.value[currentChannel.value.id] || [])
  if (!current) return '--:--'
  return new Date(current.stop).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
})

function isCurrentProgram(item) {
  const now = new Date()
  return now >= item.start && now < item.stop
}

// ============ 方法 ============
function selectGroup(groupId) {
  selectedGroup.value = groupId
}

function playChannel(channel) {
  currentChannel.value = channel
  currentUrl.value = channel.url
  currentLine.value = 1
  addToHistory(channel)
  
  // 加载EPG
  if (!epgData.value[channel.id]) {
    loadEPGForChannel(channel)
  }
}

function switchSource(source) {
  currentUrl.value = source.url
  const index = currentChannel.value.sources.findIndex(s => s.url === source.url)
  currentLine.value = index + 1
  showSourceSelector.value = false
  playerRef.value?.play(source.url)
}

async function loadEPGForChannel(channel) {
  // 模拟加载EPG，实际应从文件加载
  epgData.value[channel.id] = generateMockEPG(channel.id)
}

function generateMockEPG(channelId) {
  const programs = []
  const now = new Date()
  const baseTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0)
  
  const titles = ['新闻联播', '天气预报', '焦点访谈', '电视剧场', '综艺大观', '体育世界', '经济半小时', '今日说法']
  
  for (let i = 0; i < 24; i++) {
    const start = new Date(baseTime.getTime() + i * 60 * 60 * 1000)
    const stop = new Date(start.getTime() + 60 * 60 * 1000)
    programs.push({
      channel: channelId,
      start,
      stop,
      title: titles[i % titles.length]
    })
  }
  
  return programs
}

// ============ 加载频道 ============
async function loadChannels() {
  loading.value = true
  error.value = null
  loadingText.value = '加载中...'
  
  // 更新调试信息
  debugInfo.value.url = window.location.href
  debugInfo.value.protocol = window.location.protocol
  debugInfo.value.status = '开始加载...'
  debugInfo.value.error = ''
  
  try {
    let text = null
    
    // 检测是否在 Android WebView 本地环境
    const isAndroidLocal = window.location.protocol === 'file:' || 
                           window.location.href.includes('android_asset')
    
    // 检测是否有 Android 接口
    const hasAndroidInterface = typeof window.AndroidAsset !== 'undefined'
    
    if (isAndroidLocal && hasAndroidInterface) {
      // Android 本地环境：使用 JS 接口
      debugInfo.value.loadPath = 'AndroidAsset.readChannelData()'
      try {
        const result = window.AndroidAsset.readChannelData()
        if (result && !result.startsWith('ERROR:')) {
          text = result
          debugInfo.value.status = 'Android 接口加载成功'
          console.log('[IPTV] 从 Android 接口加载数据成功')
        } else {
          throw new Error(result)
        }
      } catch (e) {
        debugInfo.value.error = `接口加载失败: ${e.message}`
        console.log('[IPTV] Android 接口加载失败:', e.message)
      }
    } else if (isAndroidLocal) {
      // Android 但没有接口：尝试 fetch（会失败）
      debugInfo.value.loadPath = 'api/result.txt (fetch)'
      debugInfo.value.error = 'Android 接口未找到'
    } else {
      // 正常网络环境
      debugInfo.value.loadPath = '/api/result.txt (网络)'
      try {
        const response = await fetch('/api/result.txt')
        debugInfo.value.status = `响应状态: ${response.status}`
        if (response.ok) {
          text = await response.text()
          debugInfo.value.status = '网络加载成功'
          console.log('[IPTV] 从网络加载数据成功')
        } else {
          throw new Error(`HTTP ${response.status}`)
        }
      } catch (e) {
        debugInfo.value.error = `网络加载失败: ${e.message}`
        console.log('[IPTV] 网络加载失败:', e.message)
      }
    }
    
    // 如果都失败，使用模拟数据
    if (!text) {
      debugInfo.value.status = '使用模拟数据'
      console.log('[IPTV] 使用模拟数据')
      text = generateMockData()
    }
    
    const rawChannels = parseTXT(text)
    channels.value = mergeChannels(rawChannels)
    console.log(`[IPTV] 加载了 ${channels.value.length} 个频道`)
    
    // 默认选中第一个分组
    if (channels.value.length > 0) {
      const groups = [...new Set(channels.value.map(c => c.group))]
      if (groups.length > 0) {
        selectedGroup.value = groups[0]
      }
    }
  } catch (e) {
    console.error('加载频道失败:', e)
    error.value = e.message || '加载失败'
  } finally {
    loading.value = false
  }
}

// 生成模拟数据（用于测试或离线模式）
function generateMockData() {
  return `
央视频道,#genre#
CCTV1,http://example.com/cctv1
CCTV2,http://example.com/cctv2
CCTV3,http://example.com/cctv3

卫视频道,#genre#
湖南卫视,http://example.com/hunan
浙江卫视,http://example.com/zhejiang
东方卫视,http://example.com/dongfang
  `.trim()
}

function retryLoad() {
  loadChannels()
}

function copyDebug() {
  const info = JSON.stringify(debugInfo.value, null, 2)
  navigator.clipboard?.writeText(info)
  alert('调试信息已复制到剪贴板')
}

// 长按显示调试
let pressTimer = null
function startPress() {
  pressTimer = setTimeout(() => {
    showDebug.value = true
  }, 1000)
}
function endPress() {
  clearTimeout(pressTimer)
}

onMounted(() => {
  loadChannels()
  
  // 添加长按事件
  document.addEventListener('touchstart', startPress)
  document.addEventListener('touchend', endPress)
  document.addEventListener('mousedown', startPress)
  document.addEventListener('mouseup', endPress)
})
</script>

<style scoped>
.iptv-app {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #000;
  color: #fff;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 调试面板 */
.debug-panel {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #1a1a1a;
  border: 2px solid #ff6b6b;
  border-radius: 12px;
  padding: 16px;
  z-index: 9999;
  min-width: 300px;
  max-width: 90vw;
  box-shadow: 0 4px 20px rgba(0,0,0,0.8);
}

.debug-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #333;
}

.debug-header span {
  font-weight: bold;
  color: #ff6b6b;
}

.debug-header button {
  background: #333;
  border: none;
  color: #fff;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  cursor: pointer;
  font-size: 18px;
}

.debug-content {
  font-size: 13px;
  line-height: 1.6;
}

.debug-content p {
  margin-bottom: 6px;
  word-break: break-all;
}

.debug-content strong {
  color: #888;
}

.debug-content hr {
  border: none;
  border-top: 1px solid #333;
  margin: 12px 0;
}

.debug-content button {
  margin-right: 8px;
  margin-top: 8px;
  padding: 8px 16px;
  background: #333;
  border: 1px solid #555;
  color: #fff;
  border-radius: 4px;
  cursor: pointer;
}

.debug-content button:hover {
  background: #444;
}

.debug-toggle {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 44px;
  height: 44px;
  border-radius: 50%;
  background: #333;
  border: 1px solid #555;
  font-size: 20px;
  cursor: pointer;
  z-index: 9998;
  opacity: 0.7;
}

.debug-hint {
  font-size: 12px;
  color: #666;
  margin-top: 16px;
}

/* 加载中 */
.loading-screen, .error-screen {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #0a0a0a;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #333;
  border-top-color: #fff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.loading-screen p, .error-screen p {
  color: #888;
  margin-bottom: 16px;
}

.error-screen .error-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.error-screen h3 {
  color: #fff;
  margin-bottom: 8px;
}

.error-screen button {
  padding: 10px 24px;
  background: #fff;
  color: #000;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

/* ========== 三栏布局 ========== */
.main-container {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* ========== 左侧分组栏 ========== */
.sidebar-left {
  width: 200px;
  background: #0a0a0a;
  border-right: 1px solid #1a1a1a;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #888;
  border-bottom: 1px solid #1a1a1a;
}

.sidebar-header .icon {
  font-size: 16px;
}

.group-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
}

.group-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.2s;
  gap: 10px;
}

.group-item:hover {
  background: #1a1a1a;
}

.group-item.active {
  background: #fff;
  color: #000;
}

.group-item.active .arrow {
  color: #000;
}

.group-icon {
  font-size: 16px;
  width: 24px;
  text-align: center;
}

.group-name {
  flex: 1;
  font-size: 14px;
}

.group-count {
  font-size: 12px;
  color: #666;
  min-width: 20px;
  text-align: right;
}

.group-item.active .group-count {
  color: #666;
}

.arrow {
  font-size: 14px;
  color: #444;
}

/* ========== 中间频道栏 ========== */
.channel-panel {
  width: 280px;
  background: #0f0f0f;
  border-right: 1px solid #1a1a1a;
  display: flex;
  flex-direction: column;
}

.panel-header {
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #888;
  border-bottom: 1px solid #1a1a1a;
}

.panel-header .icon {
  font-size: 16px;
}

.channel-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.channel-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  gap: 12px;
  margin-bottom: 4px;
}

.channel-item:hover {
  background: #1a1a1a;
}

.channel-item.active {
  background: #2a2a2a;
  border: 1px solid #3a3a3a;
}

.channel-icon {
  width: 36px;
  height: 36px;
  background: #2a2a2a;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #888;
  font-weight: bold;
}

.channel-info {
  flex: 1;
  min-width: 0;
}

.channel-name {
  font-size: 14px;
  color: #fff;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.channel-meta {
  font-size: 12px;
  color: #666;
}

.star-icon {
  font-size: 18px;
  color: #333;
  cursor: pointer;
  transition: color 0.2s;
}

.star-icon.favorited {
  color: #ffd700;
}

/* ========== 右侧节目栏 ========== */
.epg-panel {
  flex: 1;
  background: #0a0a0a;
  display: flex;
  flex-direction: column;
}

.epg-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px 16px;
}

.epg-item {
  display: flex;
  padding: 14px 0;
  border-bottom: 1px solid #1a1a1a;
  gap: 16px;
  align-items: center;
}

.epg-time {
  font-size: 13px;
  color: #666;
  min-width: 40px;
  font-family: monospace;
}

.epg-title {
  font-size: 14px;
  color: #aaa;
  display: flex;
  align-items: center;
  gap: 8px;
}

.epg-item.current .epg-time {
  color: #fff;
}

.epg-item.current .epg-title {
  color: #fff;
}

.live-badge {
  background: #ff4444;
  color: #fff;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 4px;
  font-weight: bold;
}

.epg-empty {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
  font-size: 14px;
}

.player-placeholder {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #666;
}

.placeholder-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.3;
}

.player-placeholder p {
  font-size: 14px;
  margin-bottom: 8px;
}

.player-placeholder .hint {
  font-size: 12px;
  color: #444;
}

/* ========== 底部播放栏 ========== */
.player-bar {
  height: 80px;
  background: #0f0f0f;
  border-top: 1px solid #1a1a1a;
  display: flex;
  align-items: center;
  padding: 0 20px;
  gap: 20px;
}

.bar-left {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 16px;
  min-width: 0;
}

.channel-logo {
  width: 48px;
  height: 48px;
  background: #2a2a2a;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #888;
  font-weight: bold;
  flex-shrink: 0;
}

.program-info {
  flex: 1;
  min-width: 0;
}

.channel-line {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 6px;
}

.channel-line .channel-name {
  font-size: 15px;
  font-weight: 500;
  color: #fff;
}

.line-tag {
  font-size: 11px;
  color: #888;
  background: #2a2a2a;
  padding: 2px 8px;
  border-radius: 4px;
}

.program-title {
  font-size: 13px;
  color: #aaa;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.live-dot {
  color: #ff4444;
  font-size: 10px;
}

.progress-bar {
  height: 4px;
  background: #2a2a2a;
  border-radius: 2px;
  position: relative;
  margin-bottom: 6px;
}

.progress-fill {
  height: 100%;
  background: #fff;
  border-radius: 2px;
  transition: width 1s linear;
}

.time-label {
  position: absolute;
  right: 0;
  top: -18px;
  font-size: 11px;
  color: #666;
}

.next-program {
  font-size: 12px;
  color: #666;
}

.bar-right {
  display: flex;
  gap: 8px;
}

.bar-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background: transparent;
  border: none;
  color: #888;
  font-size: 13px;
  cursor: pointer;
  border-radius: 6px;
  transition: all 0.2s;
}

.bar-btn:hover {
  background: #1a1a1a;
  color: #fff;
}

.bar-btn.active {
  color: #ffd700;
}

.bar-btn .icon {
  font-size: 14px;
}

/* ========== 视频容器 ========== */
.video-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 80px;
  z-index: 100;
  background: #000;
}

/* ========== 弹窗 ========== */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 200;
}

.modal-content {
  background: #1a1a1a;
  border-radius: 12px;
  padding: 20px;
  min-width: 300px;
  max-width: 400px;
}

.source-modal h3 {
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 500;
}

.source-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.source-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #2a2a2a;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.source-item:hover {
  background: #3a3a3a;
}

.source-item.active {
  background: #fff;
  color: #000;
}

.source-status {
  font-size: 12px;
  color: #666;
}

.source-status.online {
  color: #00ff88;
}

.source-status.offline {
  color: #ff4444;
}
</style>
