<template>
  <div class="status-card hang-up">
    <div class="card-header">
      <img
        src="/icons/174061875626614.png"
        alt="挂机图标"
        class="status-icon"
      >
      <div class="status-info">
        <h3>挂机时间</h3>
        <p>已挂机：{{ formatTime(hangUp.elapsedTime) }}</p>
      </div>
      <div
        class="status-badge"
        :class="{ active: hangUp.isActive }"
      >
        <div class="status-dot" />
        <span>{{ hangUp.isActive ? '挂机中' : '已完成' }}</span>
      </div>
    </div>
    <div class="card-content">
      <div class="time-display">
        {{ formatTime(hangUp.remainingTime) }}
      </div>
      <div class="action-row">
        <button 
          class="action-button secondary" 
          :disabled="hangUp.isExtending"
          @click="extendHangUp"
        >
          <span
            v-if="hangUp.isExtending"
            class="loading-text"
          >
            <svg
              class="loading-icon"
              viewBox="0 0 24 24"
            >
              <path
                fill="currentColor"
                d="M12 22c5.421 0 10-4.579 10-10h-2c0 4.337-3.663 8-8 8s-8-3.663-8-8c0-4.336 3.663-8 8-8V2C6.579 2 2 6.58 2 12c0 5.421 4.579 10 10 10z"
              />
            </svg>
            加钟中...
          </span>
          <span v-else>加钟</span>
        </button>
        <button 
          class="action-button primary" 
          :disabled="hangUp.isClaiming"
          @click="claimHangUpReward"
        >
          <span
            v-if="hangUp.isClaiming"
            class="loading-text"
          >
            <svg
              class="loading-icon"
              viewBox="0 0 24 24"
            >
              <path
                fill="currentColor"
                d="M12 22c5.421 0 10-4.579 10-10h-2c0 4.337-3.663 8-8 8s-8-3.663-8-8c0-4.336 3.663-8 8-8V2C6.579 2 2 6.58 2 12c0 5.421 4.579 10 10 10z"
              />
            </svg>
            领取中...
          </span>
          <span v-else>领取奖励</span>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { useTokenStore } from '@/stores/tokenStore'
import { useMessage } from 'naive-ui'

const tokenStore = useTokenStore()
const message = useMessage()

// 响应式数据
const hangUp = ref({
  isActive: false,
  remainingTime: 0,
  elapsedTime: 0,
  lastTime: 0,
  hangUpTime: 0,
  isExtending: false,
  isClaiming: false
})

// 计算属性
const roleInfo = computed(() => {
  return tokenStore.gameData?.roleInfo || null
})

// 格式化时间
const formatTime = (seconds) => {
  const totalSeconds = Math.floor(Number(seconds) || 0)
  
  if (totalSeconds <= 0) return '00:00:00'
  
  const hours = Math.floor(totalSeconds / 3600)
  const minutes = Math.floor((totalSeconds % 3600) / 60)
  const secs = totalSeconds % 60
  
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 更新挂机状态
const updateHangUpStatus = () => {
  if (!roleInfo.value) return

  const role = roleInfo.value.role

  if (role.hangUp) {
    const now = Date.now() / 1000
    hangUp.value.lastTime = role.hangUp.lastTime
    hangUp.value.hangUpTime = role.hangUp.hangUpTime
    
    const elapsed = now - hangUp.value.lastTime
    if (elapsed <= hangUp.value.hangUpTime) {
      hangUp.value.remainingTime = Math.floor(hangUp.value.hangUpTime - elapsed)
      hangUp.value.isActive = true
    } else {
      hangUp.value.remainingTime = 0
      hangUp.value.isActive = false
    }
    hangUp.value.elapsedTime = Math.floor(hangUp.value.hangUpTime - hangUp.value.remainingTime)
    
    console.log('⏰ 挂机状态更新:', {
      lastTime: hangUp.value.lastTime,
      hangUpTime: hangUp.value.hangUpTime,
      elapsed: elapsed,
      remainingTime: hangUp.value.remainingTime,
      elapsedTime: hangUp.value.elapsedTime,
      isActive: hangUp.value.isActive
    })
  }
}

// 定时器
let timer = null
const startTimer = () => {
  if (timer) clearInterval(timer)
  timer = setInterval(() => {
    if (hangUp.value.isActive && hangUp.value.remainingTime > 0) {
      hangUp.value.remainingTime = Math.max(0, hangUp.value.remainingTime - 1)
      hangUp.value.elapsedTime = hangUp.value.elapsedTime + 1
      if (hangUp.value.remainingTime <= 0) {
        hangUp.value.isActive = false
      }
    }
  }, 1000)
}

// 加钟操作
const extendHangUp = async () => {
  if (!tokenStore.selectedToken) {
    message.warning('请先选择Token')
    return
  }
  
  const tokenId = tokenStore.selectedToken.id
  
  try {
    console.log('🕐 开始加钟操作...')
    hangUp.value.isExtending = true
    message.info('正在加钟...')
    
    const promises = []
    for (let i = 0; i < 4; i++) {
      const promise = new Promise((resolve) => {
        setTimeout(() => {
          console.log(`🕐 发送第${i+1}次加钟请求`)
          const result = tokenStore.sendMessage(tokenId, 'system_mysharecallback', {
            isSkipShareCard: true,
            type: 2
          })
          resolve(result)
        }, i * 300)
      })
      promises.push(promise)
    }
    
    await Promise.all(promises)
    
    console.log('🕐 所有加钟请求已发送')
    
    setTimeout(() => {
      console.log('🕐 加钟后获取最新角色信息')
      tokenStore.sendMessage(tokenId, 'role_getroleinfo')
    }, 1500)
    
    setTimeout(() => {
      message.success('加钟操作已完成，请查看挂机剩余时间')
      hangUp.value.isExtending = false
    }, 2500)
    
  } catch (error) {
    console.error('🕐 加钟操作失败:', error)
    message.error('加钟操作失败: ' + (error.message || '未知错误'))
    hangUp.value.isExtending = false
  }
}

// 领取挂机奖励
const claimHangUpReward = async () => {
  if (!tokenStore.selectedToken) {
    message.warning('请先选择Token')
    return
  }
  
  const tokenId = tokenStore.selectedToken.id
  
  try {
    console.log('🎁 开始领取挂机奖励...')
    hangUp.value.isClaiming = true
    message.info('正在领取挂机奖励...')
    
    tokenStore.sendMessage(tokenId, 'system_mysharecallback')
    
    setTimeout(() => {
      tokenStore.sendMessage(tokenId, 'system_claimhangupreward')
    }, 200)
    
    setTimeout(() => {
      tokenStore.sendMessage(tokenId, 'system_mysharecallback', {
        isSkipShareCard: true,
        type: 2
      })
    }, 400)
    
    setTimeout(() => {
      tokenStore.sendMessage(tokenId, 'role_getroleinfo')
    }, 600)
    
    setTimeout(() => {
      message.success('挂机奖励领取完成')
      hangUp.value.isClaiming = false
    }, 1200)
    
    console.log('🎁 挂机奖励领取操作序列已启动')
    
  } catch (error) {
    console.error('🎁 领取挂机奖励失败:', error)
    message.error('领取挂机奖励失败: ' + (error.message || '未知错误'))
    hangUp.value.isClaiming = false
  }
}

// 监听角色信息变化
watch(roleInfo, (newValue) => {
  if (newValue) {
    updateHangUpStatus()
  }
}, { deep: true, immediate: true })

// 生命周期
onMounted(() => {
  updateHangUpStatus()
  startTimer()
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped lang="scss">
.status-card {
  background: var(--bg-primary);
  border-radius: var(--border-radius-xl);
  padding: var(--spacing-lg);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08), 0 1px 3px rgba(0, 0, 0, 0.02);
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, var(--primary-color), var(--primary-color-light));
    opacity: 0.8;
    transition: opacity 0.3s ease;
  }
  
  &:hover {
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12), 0 2px 8px rgba(0, 0, 0, 0.04);
    transform: translateY(-4px);
    
    &::before {
      opacity: 1;
    }
  }
  
  &.hang-up {
    &::before { background: linear-gradient(90deg, #d03050, #de576d); }
    
    &:hover {
      box-shadow: 0 12px 40px rgba(208, 48, 80, 0.2), 0 4px 12px rgba(0, 0, 0, 0.08);
      transform: translateY(-6px);
      
      &::before {
        opacity: 1;
        box-shadow: 0 0 20px rgba(208, 48, 80, 0.4);
      }
    }
    
    .status-icon {
      background: linear-gradient(135deg, rgba(208, 48, 80, 0.15), rgba(222, 87, 109, 0.1));
      box-shadow: 0 4px 12px rgba(208, 48, 80, 0.2);
      
      &:hover {
        transform: scale(1.1);
        box-shadow: 0 8px 24px rgba(208, 48, 80, 0.3);
      }
    }
    
    .status-badge.active {
      background: rgba(208, 48, 80, 0.15);
      color: #d03050;
      box-shadow: 0 0 12px rgba(208, 48, 80, 0.2);
    }
    
    .action-button {
      background: linear-gradient(135deg, #d03050, #de576d);
      box-shadow: 0 4px 12px rgba(208, 48, 80, 0.3);
      
      &:hover:not(:disabled) {
        background: linear-gradient(135deg, #d83050, #e6577d);
        box-shadow: 0 6px 16px rgba(208, 48, 80, 0.4);
      }
      
      &.secondary {
        background: linear-gradient(135deg, #8b5cf6, #a78bfa);
        box-shadow: 0 4px 12px rgba(139, 92, 246, 0.3);
        
        &:hover:not(:disabled) {
          background: linear-gradient(135deg, #936cf6, #b19bfa);
          box-shadow: 0 6px 16px rgba(139, 92, 246, 0.4);
        }
      }
    }
  }
}

.card-header {
  display: flex;
  align-items: flex-start;
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-lg);
  position: relative;
}

.status-icon {
  width: 32px;
  height: 32px;
  object-fit: contain;
  flex-shrink: 0;
  border-radius: var(--border-radius-lg);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.05));
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  
  &:hover {
    transform: scale(1.05);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
  }
}

.status-info {
  flex: 1;

  h3 {
    font-size: var(--font-size-md);
    font-weight: var(--font-weight-semibold);
    color: var(--text-primary);
    margin: 0 0 var(--spacing-xs) 0;
  }

  p {
    font-size: var(--font-size-sm);
    color: var(--text-secondary);
    margin: 0;
  }
}

.status-badge {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--border-radius-full);
  font-size: var(--font-size-sm);
  font-weight: var(--font-weight-medium);
  background: rgba(156, 163, 175, 0.1);
  color: var(--text-secondary);

  &.active {
    background: rgba(34, 197, 94, 0.1);
    color: var(--success-color);
  }
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: currentColor;
}

.card-content {
  .time-display {
    font-size: 1.5rem;
    font-weight: 700;
    color: var(--text-primary);
    text-align: center;
    margin-bottom: var(--spacing-md);
    font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Roboto Mono', 'Consolas', monospace;
    letter-spacing: 0.1em;
    text-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
    background: var(--bg-tertiary);
    padding: 0.75rem 1rem;
    border-radius: 0.5rem;
    border: 1px solid var(--border-light);
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1), 0 1px 2px rgba(0, 0, 0, 0.06);
    transition: all 0.2s ease-in-out;
    
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 2px 4px rgba(0, 0, 0, 0.06);
    }
  }
}

.action-button {
  width: 100%;
  padding: var(--spacing-sm) var(--spacing-md);
  border: none;
  border-radius: var(--border-radius-medium);
  font-size: var(--font-size-sm);
  font-weight: var(--font-weight-medium);
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  background: linear-gradient(135deg, var(--primary-color), var(--primary-color-light));
  color: white;
  box-shadow: 0 4px 12px rgba(var(--primary-color-rgb, 24, 160, 88), 0.3);
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
    transition: left 0.5s;
  }
  
  &:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(var(--primary-color-rgb, 24, 160, 88), 0.4);
    
    &::before {
      left: 100%;
    }
  }
  
  &:active {
    transform: translateY(0);
    box-shadow: 0 2px 8px rgba(var(--primary-color-rgb, 24, 160, 88), 0.3);
  }
  
  &:disabled {
    background: var(--bg-tertiary);
    color: var(--text-tertiary);
    cursor: not-allowed;
    transform: none;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    
    &::before {
      display: none;
    }
  }
}

.action-row {
  display: flex;
  gap: var(--spacing-sm);

  .action-button {
    flex: 1;
  }
}

.loading-text {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-xs);
}

.loading-icon {
  width: 16px;
  height: 16px;
  animation: spin 1s linear infinite;
}

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

@media (max-width: 768px) {
  .status-card {
    padding: var(--spacing-md);
  }

  .card-header {
    flex-direction: column;
    text-align: center;
    gap: var(--spacing-sm);
  }
}
</style>

