<template>
  <div
    v-if="isVisible"
    ref="container"
    class="video-call-container"
    :class="{
        'minimized': isMinimized,
        'dark': themeStore.isDarkMode,
        'dragging': isDragging
      }"
    :style="containerStyle"
  >
    <!-- 拖拽头部 -->
    <div
      class="call-header"
      @mousedown="startDrag"
    >
      <div class="call-info">
        <div class="caller-avatar" :style="{ background: callerInfo.color }">
          {{ callerInfo.nick_name.charAt(0) }}
        </div>
        <div class="caller-details">
          <div class="caller-name">{{ callerInfo.nick_name }}</div>
          <div class="call-status">{{ connectionText }}</div>
        </div>
      </div>

      <div class="call-actions">
        <button class="action-btn minimize-btn" @click="toggleMinimize" @mousedown.stop>
          <i class="fas fa-minus"></i>
        </button>
        <button class="action-btn close-btn" @click="endCall" @mousedown.stop>
          <i class="fas fa-times"></i>
        </button>
      </div>
    </div>

    <!-- 最小化状态 -->
    <div
      v-if="isMinimized"
      class="minimized-content"
      @mousedown="startDrag"
      @dblclick="toggleMinimize"
    >
      <!-- 音频通话：显示头像和计时器 -->
      <template v-if="callType === 'audio'">
        <div class="audio-call-mini">
          <div class="mini-avatar" :style="{ background: callerInfo.color }">
            {{ callerInfo.nick_name.charAt(0) }}
          </div>
          <div class="mini-info">
            <div class="mini-name">{{ callerInfo.nick_name }}</div>
            <div class="mini-timer">{{ formattedDuration }}</div>
          </div>
          <button class="mini-expand-btn" @click="toggleMinimize" @mousedown.stop>
            <i class="fas fa-expand"></i>
          </button>
        </div>
      </template>

      <!-- 视频通话最小化时显示远程视频流 -->
      <template v-else>
        <div class="video-call-mini">
          <div class="remote-video-preview">
            <!-- 修复问题1: 确保视频元素始终存在 -->
            <video
              ref="remoteVideoPreview"
              class="remote-video"
              autoplay
              playsinline
              muted
              @loadedmetadata="handleVideoLoaded($event, 'preview')"
              @error="handleVideoError($event, 'preview')"
              @canplay="handleVideoCanPlay($event, 'preview')"
              @loadstart="handleVideoLoadStart($event, 'preview')"
              @waiting="handleVideoWaiting($event, 'preview')"
              @playing="handleVideoPlaying($event, 'preview')"
            ></video>
            <div v-if="!remoteStream" class="video-placeholder">
              <div class="placeholder-avatar" :style="{ background: callerInfo.color }">
                {{ callerInfo.nick_name.charAt(0) }}
              </div>
            </div>
          </div>
          <div class="mini-info">
            <div class="mini-name">{{ callerInfo.nick_name }}</div>
            <div class="mini-timer">{{ formattedDuration }}</div>
          </div>
          <button class="mini-expand-btn" @click="toggleMinimize" @mousedown.stop>
            <i class="fas fa-expand"></i>
          </button>
        </div>
      </template>
    </div>

    <!-- 视频区域 -->
    <div v-if="!isMinimized" class="video-area">
      <!-- 远程视频 -->
      <div class="remote-video-container">
        <!-- 修复问题1: 确保视频元素始终存在，移除v-if条件 -->
        <video
          ref="remoteVideo"
          class="remote-video"
          autoplay
          playsinline
          @loadedmetadata="handleVideoLoaded($event, 'main')"
          @error="handleVideoError($event, 'main')"
          @canplay="handleVideoCanPlay($event, 'main')"
          @loadstart="handleVideoLoadStart($event, 'main')"
          @waiting="handleVideoWaiting($event, 'main')"
          @playing="handleVideoPlaying($event, 'main')"
        ></video>
        <div v-if="!remoteStream" class="video-placeholder">
          <div class="placeholder-avatar" :style="{ background: callerInfo.color }">
            {{ callerInfo.nick_name.charAt(0) }}
          </div>
          <div class="placeholder-text">{{ callerInfo.nick_name }}</div>
          <div class="connection-status">{{ connectionText }}</div>
        </div>
      </div>

      <!-- 本地视频 -->
      <div
        class="local-video-container"
        v-if="callType === 'video' && localStream"
      >
        <video
          ref="localVideo"
          class="local-video"
          autoplay
          playsinline
          muted
          :srcObject="localStream"
          @error="handleVideoError($event, 'local')"
        ></video>
      </div>
      <div
        v-else-if="callType === 'video'"
        class="local-placeholder-container"
      >
        <div class="local-avatar" :style="{ background: userStore.currentUser?.color || '#666' }">
          {{ userStore.currentUser?.nick_name?.charAt(0) || 'U' }}
        </div>
      </div>

      <!-- 通话计时器显示 -->
      <div v-if="callStatus === 'ongoing'" class="call-timer-display">
        <i class="fas fa-clock"></i>
        <span>{{ formattedDuration }}</span>
      </div>

      <!-- 连接状态指示器 -->
      <div v-if="webrtc.isConnecting?.value" class="connection-indicator">
        <div class="spinner"></div>
        <span>正在连接...</span>
      </div>

      <!-- 视频重试指示器 -->
      <div v-if="videoRetryCount > 0" class="video-retry-indicator">
        <div class="retry-spinner"></div>
        <span>视频加载中... ({{ videoRetryCount }}/{{ maxVideoRetries }})</span>
      </div>

      <!-- 修复问题1: 视频调试信息 -->
      <div v-if="showDebugInfo" class="video-debug-info">
        <div>远程流: {{ remoteStream ? '✅' : '❌' }}</div>
        <div>主视频元素: {{ remoteVideo ? '✅' : '❌' }}</div>
        <div>预览视频元素: {{ remoteVideoPreview ? '✅' : '❌' }}</div>
        <div>回调数量: {{ videoCallbackCount }}</div>
        <div v-if="remoteStream">
          <div>流ID: {{ remoteStream.id }}</div>
          <div>轨道数: {{ remoteStream.getTracks().length }}</div>
          <div v-for="track in remoteStream.getTracks()" :key="track.id">
            {{ track.kind }}: {{ track.readyState }} - {{ track.enabled ? '启用' : '禁用' }}
          </div>
        </div>
      </div>
    </div>

    <!-- 控制栏 -->
    <div v-if="!isMinimized" class="call-controls">
      <!-- 来电时显示忙线状态 -->
      <div v-if="isIncoming && callStatus === 'busy'" class="busy-status-inline">
        <i class="fas fa-phone-slash"></i>
        <span>对方忙线中</span>
      </div>

      <!-- 正常控制按钮 -->
      <template v-else>
        <!-- 来电时显示接听和拒绝按钮 -->
        <template v-if="isIncoming && callStatus === 'ringing'">
          <button
            class="control-btn accept-btn-inline"
            @click="acceptCall"
            :disabled="isAccepting"
            :title="isAccepting ? '接听中...' : '接听'"
          >
            <i class="fas fa-phone"></i>
          </button>
          <button
            class="control-btn reject-btn-inline"
            @click="rejectCall"
            :disabled="isAccepting"
            title="拒绝"
          >
            <i class="fas fa-phone-slash"></i>
          </button>
        </template>

        <!-- 通话中的控制按钮 -->
        <template v-else>
          <button
            class="control-btn"
            :class="{ 'active': isMicOn, 'disabled': !isMicOn }"
            @click="toggleMic"
            :title="isMicOn ? '关闭麦克风' : '开启麦克风'"
          >
            <i class="fas" :class="isMicOn ? 'fa-microphone' : 'fa-microphone-slash'"></i>
          </button>

          <button
            v-if="callType === 'video'"
            class="control-btn"
            :class="{ 'active': isCameraOn, 'disabled': !isCameraOn }"
            @click="toggleCamera"
            :title="isCameraOn ? '关闭摄像头' : '开启摄像头'"
          >
            <i class="fas" :class="isCameraOn ? 'fa-video' : 'fa-video-slash'"></i>
          </button>

          <button
            class="control-btn speaker-btn"
            :class="{ 'active': isSpeakerOn }"
            @click="toggleSpeaker"
            :title="isSpeakerOn ? '关闭扬声器' : '开启扬声器'"
          >
            <i class="fas" :class="isSpeakerOn ? 'fa-volume-up' : 'fa-volume-mute'"></i>
          </button>

          <button
            class="control-btn end-call-btn"
            @click="endCall"
            title="结束通话"
          >
            <i class="fas fa-phone-slash"></i>
          </button>

          <!-- 修复问题1: 调试按钮 -->
          <button
            class="control-btn debug-btn"
            @click="toggleDebugInfo"
            title="调试信息"
          >
            <i class="fas fa-bug"></i>
          </button>
        </template>
      </template>
    </div>

    <!-- 通话结束提示 -->
    <div v-if="showEndingNotification" class="ending-notification">
      <div class="notification-content">
        <i class="fas fa-phone-slash"></i>
        <span>通话已结束</span>
        <div class="countdown">{{ endingCountdown }}秒后关闭</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, computed, onMounted, onUnmounted, watch, nextTick} from 'vue';
import {useThemeStore} from '../stores/theme.ts';
import {useWebRTC} from '../composables/useWebRTC.ts';
import {useChatStore} from '../stores/chat.ts';
import {useUserStore} from '../stores/user.ts';

const themeStore = useThemeStore();
const chatStore = useChatStore();
const webrtc = useWebRTC();
const userStore = useUserStore();

const props = defineProps({
  callerInfo: {
    type: Object,
    required: true
  },
  callType: {
    type: String,
    default: 'video',
    validator: (value) => ['video', 'audio'].includes(value)
  },
  isIncoming: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['end-call', 'accept-call', 'reject-call']);

// 时间戳日志函数
const logWithTime = (level, message, ...args) => {
  const timestamp = new Date().toLocaleTimeString('zh-CN', {
    hour12: false,
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    fractionalSecondDigits: 3
  });

  switch (level) {
    case 'log':
      console.log(`[${timestamp}] ${message}`, ...args);
      break;
    case 'error':
      console.error(`[${timestamp}] ${message}`, ...args);
      break;
    case 'warn':
      console.warn(`[${timestamp}] ${message}`, ...args);
      break;
    default:
      console.log(`[${timestamp}] ${message}`, ...args);
  }
};

// 状态管理
const isVisible = ref(true);
const isMinimized = ref(false);
const isMicOn = ref(true);
const isCameraOn = ref(props.callType === 'video');
const isSpeakerOn = ref(true);
const callDuration = ref(0);
const callTimer = ref(null);
const isDragging = ref(false);
const isAccepting = ref(false);

// 结束通话提示相关状态
const showEndingNotification = ref(false);
const endingCountdown = ref(3);
const endingTimer = ref(null);

// 视频重试相关状态
const videoRetryCount = ref(0);
const maxVideoRetries = 3;
const videoRetryTimers = ref(new Map());

// 修复问题1: 调试相关状态
const showDebugInfo = ref(false);
const videoCallbackCount = ref(0);

// 元素引用
const localVideo = ref(null);
const remoteVideo = ref(null);
const remoteVideoPreview = ref(null);

// 修复问题1: 视频回调取消注册函数
const unregisterVideoCallback = ref(null);

// 创建本地和远程流的引用
const localStream = computed(() => webrtc.localStream?.value);
const remoteStream = computed(() => webrtc.remoteStream?.value);

// 获取当前通话状态
const callStatus = computed(() => {
  return chatStore.callStatus;
});

// 连接状态文本
const connectionText = computed(() => {
  if (chatStore.callConnectionStatus) {
    return chatStore.callConnectionStatus;
  }

  if (callStatus.value === "busy") {
    return '对方忙线中';
  }

  if (callStatus.value === "hangup") {
    return '对方已挂断';
  }

  if (callStatus.value === "disconnected") {
    return '网络连接已断开';
  }

  if (callStatus.value === "failed") {
    return '连接失败，请检查网络';
  }

  if (props.isIncoming && callStatus.value !== "ongoing") {
    return '来电中...';
  }

  if (callStatus.value === "ongoing") {
    return `通话中`;
  }

  if (callStatus.value === "connecting") {
    return '正在连接...';
  }

  return '正在连接...';
});

// 修复问题1: 安全的视频元素更新函数
const safeUpdateVideoElement = (videoElement, stream, type) => {
  if (!videoElement) {
    logWithTime('warn', `⚠️ ${type}视频元素不存在，跳过更新`);
    return false;
  }

  try {
    logWithTime('log', `🔄 安全更新${type}视频元素`, {
      hasStream: !!stream,
      elementExists: !!videoElement,
      currentSrc: !!videoElement.srcObject,
      streamId: stream?.id
    });

    if (stream) {
      // 检查流的有效性
      if (!stream.active) {
        logWithTime('warn', `⚠️ ${type}流不是活跃状态`);
      }

      const tracks = stream.getTracks();
      if (tracks.length === 0) {
        logWithTime('warn', `⚠️ ${type}流没有轨道`);
        return false;
      }

      // 检查视频轨道
      const videoTracks = tracks.filter(t => t.kind === 'video');
      if (videoTracks.length === 0 && type !== 'local') {
        logWithTime('warn', `⚠️ ${type}流没有视频轨道`);
      }

      // 设置srcObject
      if (videoElement.srcObject !== stream) {
        videoElement.srcObject = stream;
        logWithTime('log', `✅ ${type}视频srcObject已设置`);

        // 强制加载
        videoElement.load();

        // 尝试播放
        videoElement.play().catch(error => {
          logWithTime('error', `❌ ${type}视频播放失败:`, error);
          // 启动重试
          retryVideoPlay(videoElement, type, 1);
        });
      }
    } else {
      // 清理视频元素
      if (videoElement.srcObject) {
        videoElement.srcObject = null;
        logWithTime('log', `🔄 ${type}视频srcObject已清理`);
      }
    }

    return true;
  } catch (error) {
    logWithTime('error', `❌ 安全更新${type}视频元素失败:`, error);
    return false;
  }
};

// 修复问题1: 视频元素更新回调函数
const handleVideoElementUpdate = (stream) => {
  logWithTime('log', '📹 收到视频元素更新回调', {
    hasStream: !!stream,
    streamId: stream?.id,
    hasMainVideo: !!remoteVideo.value,
    hasPreviewVideo: !!remoteVideoPreview.value
  });

  // 更新主视频元素
  if (remoteVideo.value) {
    safeUpdateVideoElement(remoteVideo.value, stream, 'main');
  } else {
    logWithTime('warn', '⚠️ 主视频元素不存在');
  }

  // 更新预览视频元素
  if (remoteVideoPreview.value) {
    safeUpdateVideoElement(remoteVideoPreview.value, stream, 'preview');
  } else {
    logWithTime('warn', '⚠️ 预览视频元素不存在');
  }
};

// 修复问题3: 视频重试机制
const retryVideoPlay = async (videoElement, type, attempt = 1) => {
  if (attempt > maxVideoRetries) {
    logWithTime('error', `❌ ${type}视频重试失败，已达到最大重试次数`);
    videoRetryCount.value = 0;
    return false;
  }

  videoRetryCount.value = attempt;
  logWithTime('log', `🔄 ${type}视频播放重试 ${attempt}/${maxVideoRetries}`);

  try {
    // 等待递增的延迟时间
    await new Promise(resolve => setTimeout(resolve, 1000 * attempt));

    if (!videoElement || !videoElement.srcObject) {
      logWithTime('warn', `⚠️ ${type}视频元素或流已不存在，停止重试`);
      return false;
    }

    // 检查视频状态
    if (videoElement.readyState >= 2) {
      await videoElement.play();
      logWithTime('log', `✅ ${type}视频重试播放成功`);
      videoRetryCount.value = 0;
      return true;
    } else {
      // 强制重新加载
      const currentStream = videoElement.srcObject;
      videoElement.srcObject = null;
      setTimeout(() => {
        videoElement.srcObject = currentStream;
        videoElement.load();
      }, 100);

      // 递归重试
      setTimeout(() => {
        retryVideoPlay(videoElement, type, attempt + 1);
      }, 1000);
    }
  } catch (error) {
    logWithTime('error', `❌ ${type}视频重试播放失败:`, error);

    // 继续重试
    setTimeout(() => {
      retryVideoPlay(videoElement, type, attempt + 1);
    }, 1000 * attempt);
  }
};

// 改进视频加载处理
const handleVideoLoaded = async (event, type) => {
  const video = event.target;
  logWithTime('log', `📹 ${type} 视频元数据已加载`, {
    readyState: video.readyState,
    videoWidth: video.videoWidth,
    videoHeight: video.videoHeight,
    duration: video.duration,
    paused: video.paused,
    currentTime: video.currentTime
  });

  try {
    if (video && video.readyState >= 2) {
      await video.play();
      logWithTime('log', `✅ ${type} 视频开始播放`);
      videoRetryCount.value = 0; // 重置重试计数

      // 检查视频尺寸和轨道状态
      if (type === 'main' || type === 'preview') {
        setTimeout(() => {
          if (video.videoWidth === 0 && video.videoHeight === 0) {
            logWithTime('warn', `⚠️ ${type} 视频尺寸为0，可能存在问题，尝试重新设置`);
            const currentStream = video.srcObject;
            if (currentStream) {
              safeUpdateVideoElement(video, currentStream, type);
            }
          } else {
            logWithTime('log', `✅ ${type} 视频尺寸正常: ${video.videoWidth}x${video.videoHeight}`);
          }
        }, 2000);
      }
    }
  } catch (error) {
    logWithTime('error', `❌ ${type} 视频播放失败:`, error);

    // 启动重试机制
    retryVideoPlay(video, type, 1);
  }
};

const handleVideoLoadStart = (event, type) => {
  const video = event.target;
  logWithTime('log', `📹 ${type} 视频开始加载`);
};

const handleVideoWaiting = (event, type) => {
  const video = event.target;
  logWithTime('log', `📹 ${type} 视频等待数据`);
};

const handleVideoPlaying = (event, type) => {
  const video = event.target;
  logWithTime('log', `📹 ${type} 视频正在播放`);
  videoRetryCount.value = 0; // 重置重试计数
};

const handleVideoCanPlay = (event, type) => {
  const video = event.target;
  logWithTime('log', `📹 ${type} 视频可以播放`, {
    readyState: video.readyState,
    buffered: video.buffered.length
  });
};

const handleVideoError = (event, type) => {
  const video = event.target;
  logWithTime('error', `❌ ${type} 视频错误:`, {
    error: video.error,
    networkState: video.networkState,
    readyState: video.readyState
  });

  // 视频错误时启动重试
  if (video.srcObject) {
    retryVideoPlay(video, type, 1);
  }
};

// 通话计时器
const startCallTimer = () => {
  logWithTime('log', "⏰ 开始通话计时");
  if (callTimer.value) clearInterval(callTimer.value);
  callDuration.value = 0;
  callTimer.value = setInterval(() => {
    callDuration.value += 1;
  }, 1000);
};

const stopCallTimer = () => {
  logWithTime('log', "⏰ 停止通话计时");
  if (callTimer.value) {
    clearInterval(callTimer.value);
    callTimer.value = null;
  }
};

const formattedDuration = computed(() => {
  const minutes = Math.floor(callDuration.value / 60);
  const seconds = callDuration.value % 60;
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
});

const containerStyle = computed(() => {
  const width = isMinimized.value ? (props.callType === 'audio' ? '250px' : '200px') : '500px';
  const height = isMinimized.value ? '60px' : '380px';

  return {
    left: `${position.x}px`,
    top: `${position.y}px`,
    width: width,
    height: height
  };
});

// 初始化媒体设备
const initializeMedia = async () => {
  try {
    logWithTime('log', "🎥 初始化媒体设备");
    const constraints = {
      audio: true,
      video: props.callType === 'video'
    };

    await webrtc.getLocalMedia(constraints);
    logWithTime('log', "✅ 媒体设备初始化成功");
    return true;
  } catch (error) {
    logWithTime('error', '❌ 无法访问媒体设备:', error);
    return false;
  }
};

// 控制功能
const toggleMic = () => {
  isMicOn.value = !isMicOn.value;
  webrtc.toggleMicrophone(isMicOn.value);
  logWithTime('log', `🎤 麦克风${isMicOn.value ? '开启' : '关闭'}`);
};

const toggleCamera = () => {
  if (props.callType === 'video') {
    isCameraOn.value = !isCameraOn.value;
    webrtc.toggleCamera(isCameraOn.value);
    logWithTime('log', `📹 摄像头${isCameraOn.value ? '开启' : '关闭'}`);
  }
};

const toggleSpeaker = () => {
  isSpeakerOn.value = !isSpeakerOn.value;
  logWithTime('log', `🔊 扬声器${isSpeakerOn.value ? '开启' : '关闭'}`);
};

const toggleMinimize = () => {
  isMinimized.value = !isMinimized.value;
  logWithTime('log', `${isMinimized.value ? '最小化' : '展开'}通话窗口`);

  const width = isMinimized.value ? (props.callType === 'audio' ? 250 : 200) : 500;
  const height = isMinimized.value ? 60 : 380;

  position.x = Math.max(0, Math.min(position.x, window.innerWidth - width));
  position.y = Math.max(0, Math.min(position.y, window.innerHeight - height));
};

// 修复问题1: 调试信息切换
const toggleDebugInfo = () => {
  showDebugInfo.value = !showDebugInfo.value;
  logWithTime('log', `🐛 调试信息${showDebugInfo.value ? '开启' : '关闭'}`);
};

// 结束通话逻辑
const endCall = () => {
  logWithTime('log', "📞 开始结束通话流程");

  // 清理视频重试定时器
  videoRetryTimers.value.forEach(timer => clearTimeout(timer));
  videoRetryTimers.value.clear();
  videoRetryCount.value = 0;

  // 取消注册视频回调
  if (unregisterVideoCallback.value) {
    unregisterVideoCallback.value();
    unregisterVideoCallback.value = null;
  }

  // 立即释放媒体资源
  webrtc.releaseMediaResources();

  // 显示结束提示
  showEndingNotification.value = true;
  endingCountdown.value = 3;

  // 开始倒计时
  endingTimer.value = setInterval(() => {
    endingCountdown.value--;
    if (endingCountdown.value <= 0) {
      clearInterval(endingTimer.value);
      endingTimer.value = null;
      performEndCall();
    }
  }, 1000);

  // 关闭WebRTC连接
  webrtc.closeConnection();
  stopCallTimer();
  chatStore.endCall();
};

const performEndCall = () => {
  logWithTime('log', "📞 执行结束通话操作");
  showEndingNotification.value = false;
  isVisible.value = false;
  emit('end-call');
};

// 接听通话
const acceptCall = async () => {
  if (isAccepting.value) return;

  logWithTime('log', "📞 开始接听通话");
  isAccepting.value = true;

  try {
    const mediaSuccess = await initializeMedia();
    if (mediaSuccess) {
      await chatStore.acceptCall();
      emit('accept-call');
      logWithTime('log', "✅ 通话接听成功");
    } else {
      logWithTime('error', "❌ 媒体设备初始化失败，无法接听");
    }
  } catch (error) {
    logWithTime('error', "❌ 接听失败:", error);
  } finally {
    setTimeout(() => {
      isAccepting.value = false;
    }, 3000);
  }
};

// 拒绝通话
const rejectCall = () => {
  logWithTime('log', "📞 拒绝通话");

  // 清理视频重试定时器
  videoRetryTimers.value.forEach(timer => clearTimeout(timer));
  videoRetryTimers.value.clear();
  videoRetryCount.value = 0;

  // 取消注册视频回调
  if (unregisterVideoCallback.value) {
    unregisterVideoCallback.value();
    unregisterVideoCallback.value = null;
  }

  webrtc.forceCleanup();
  isVisible.value = false;
  chatStore.rejectCall();
  emit('reject-call');
};

// 拖拽相关
const position = reactive({x: 0, y: 0});
const startPosition = reactive({x: 0, y: 0});
const container = ref(null);

const startDrag = (event) => {
  if (event.target.closest('.action-btn') ||
    event.target.closest('.control-btn') ||
    event.target.closest('.mini-expand-btn')) {
    return;
  }

  isDragging.value = true;
  startPosition.x = event.clientX;
  startPosition.y = event.clientY;

  document.addEventListener('mousemove', handleDrag);
  document.addEventListener('mouseup', stopDrag);
};

const handleDrag = (event) => {
  if (!isDragging.value) return;

  const deltaX = event.clientX - startPosition.x;
  const deltaY = event.clientY - startPosition.y;

  position.x += deltaX;
  position.y += deltaY;

  startPosition.x = event.clientX;
  startPosition.y = event.clientY;

  const width = isMinimized.value ? (props.callType === 'audio' ? 250 : 200) : 500;
  const height = isMinimized.value ? 60 : 380;

  position.x = Math.max(0, Math.min(position.x, window.innerWidth - width));
  position.y = Math.max(0, Math.min(position.y, window.innerHeight - height));
};

const stopDrag = () => {
  isDragging.value = false;
  document.removeEventListener('mousemove', handleDrag);
  document.removeEventListener('mouseup', stopDrag);
};

const handleWindowResize = () => {
  const width = isMinimized.value ? (props.callType === 'audio' ? 250 : 200) : 500;
  const height = isMinimized.value ? 60 : 380;

  position.x = Math.max(0, Math.min(position.x, window.innerWidth - width));
  position.y = Math.max(0, Math.min(position.y, window.innerHeight - height));
};

// 修复问题4: 监听ICE连接失败事件
const handleIceConnectionFailed = (event) => {
  const {callId, peerId} = event.detail;
  logWithTime('log', '🧊 收到ICE连接失败事件，尝试重新协商');

  // 通知chat store重新发送offer
  if (chatStore.currentCall?.value?.callId === callId) {
    setTimeout(() => {
      chatStore.handleCallAccepted({
        call_id: callId,
        sender_user_id: peerId
      });
    }, 1000);
  }
};

// 监听本地流变化
watch(localStream, (newStream) => {
  logWithTime('log', "📹 本地流状态变化", {
    hasStream: !!newStream,
    tracks: newStream?.getTracks().map(t => `${t.kind}:${t.id}`)
  });

  if (newStream && localVideo.value) {
    nextTick(() => {
      if (localVideo.value.srcObject !== newStream) {
        logWithTime('log', "📹 更新本地视频");
        localVideo.value.srcObject = newStream;
      }
    });
  }
});

// 监听通话状态变化
watch(() => chatStore.callStatus, async (status, oldStatus) => {
  logWithTime('log', "📞 通话状态变化:", {from: oldStatus, to: status});

  try {
    switch (status) {
      case "calling":
      case "connecting":
        logWithTime('log', "🔄 准备通话，初始化媒体");
        await initializeMedia();
        break;

      case "ongoing":
        logWithTime('log', "✅ 通话进行中");
        if (!callTimer.value) {
          startCallTimer();
        }
        break;

      case "ended":
      case "idle":
        logWithTime('log', "📞 通话结束，释放资源");
        webrtc.releaseMediaResources();
        stopCallTimer();
        setTimeout(() => {
          if (chatStore.callStatus === status) {
            endCall();
          }
        }, 1000);
        break;

      case "failed":
        logWithTime('log', "❌ 通话失败，释放资源");
        webrtc.releaseMediaResources();
        setTimeout(() => {
          if (chatStore.callStatus === status) {
            endCall();
          }
        }, 3000);
        break;

      case "hangup":
        logWithTime('log', "📞 对方挂断，释放资源");
        webrtc.releaseMediaResources();
        setTimeout(() => {
          if (chatStore.callStatus === status) {
            endCall();
          }
        }, 3000);
        break;

      case "disconnected":
        logWithTime('log', "🔌 连接断开，释放资源");
        webrtc.releaseMediaResources();
        setTimeout(() => {
          if (chatStore.callStatus === status) {
            endCall();
          }
        }, 3000);
        break;
    }
  } catch (error) {
    logWithTime('error', '❌ 处理通话状态变化失败:', error);
    webrtc.forceCleanup();
  }
});

onMounted(async () => {
  logWithTime('log', "🚀 VideoCallComponent 组件挂载");

  position.x = Math.max(0, (window.innerWidth - 500) / 2);
  position.y = Math.max(0, (window.innerHeight - 380) / 2);

  window.addEventListener('resize', handleWindowResize);

  // 修复问题4: 监听ICE连接失败事件
  window.addEventListener('iceConnectionFailed', handleIceConnectionFailed);

  // 修复问题1: 注册视频元素更新回调
  unregisterVideoCallback.value = webrtc.registerVideoCallback(handleVideoElementUpdate);

  // 更新回调计数
  videoCallbackCount.value = webrtc.videoElementCallbacks?.value?.size || 0;

  const handleBeforeUnload = () => {
    logWithTime('log', "🔄 页面即将卸载，释放WebRTC资源");

    // 清理视频重试定时器
    videoRetryTimers.value.forEach(timer => clearTimeout(timer));
    videoRetryTimers.value.clear();

    // 取消注册视频回调
    if (unregisterVideoCallback.value) {
      unregisterVideoCallback.value();
      unregisterVideoCallback.value = null;
    }

    webrtc.forceCleanup();
  };

  window.addEventListener('beforeunload', handleBeforeUnload);

  onUnmounted(() => {
    window.removeEventListener('beforeunload', handleBeforeUnload);
    window.removeEventListener('iceConnectionFailed', handleIceConnectionFailed);
  });

  if (['calling', 'connecting', 'ongoing'].includes(chatStore.callStatus)) {
    logWithTime('log', "🎥 当前状态需要媒体，立即初始化");
    await initializeMedia();
  }
});

onUnmounted(() => {
  logWithTime('log', "🔄 VideoCallComponent 组件卸载");

  if (endingTimer.value) {
    clearInterval(endingTimer.value);
    endingTimer.value = null;
  }

  // 清理视频重试定时器
  videoRetryTimers.value.forEach(timer => clearTimeout(timer));
  videoRetryTimers.value.clear();
  videoRetryCount.value = 0;

  // 取消注册视频回调
  if (unregisterVideoCallback.value) {
    unregisterVideoCallback.value();
    unregisterVideoCallback.value = null;
  }

  webrtc.forceCleanup();
  stopCallTimer();

  document.removeEventListener('mousemove', handleDrag);
  document.removeEventListener('mouseup', stopDrag);
  window.removeEventListener('resize', handleWindowResize);

  logWithTime('log', "✅ 组件卸载完成，所有资源已释放");
});
</script>

<style scoped>
/* 保持原有样式，添加新的指示器样式 */
.video-call-container {
  position: fixed;
  z-index: 9999;
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: default;
}

.video-call-container.dragging {
  opacity: 0.9;
  cursor: grabbing;
  box-shadow: 0 25px 70px rgba(0, 0, 0, 0.5);
  transition: none;
}

.video-call-container.dark {
  background: #2d2d2d;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6);
}

.video-call-container.minimized {
  cursor: move;
}

.call-header {
  background: linear-gradient(135deg, #4361ee, #3f37c9);
  color: white;
  padding: 12px 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 56px;
  cursor: move;
}

.call-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.caller-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  font-size: 14px;
}

.caller-details {
  display: flex;
  flex-direction: column;
}

.caller-name {
  font-size: 14px;
  font-weight: 600;
}

.call-status {
  font-size: 12px;
  opacity: 0.8;
}

.call-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  width: 28px;
  height: 28px;
  border: none;
  border-radius: 6px;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.action-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.close-btn:hover {
  background: #ff6b6b;
}

.minimized-content {
  display: flex;
  align-items: center;
  height: 100%;
  background: linear-gradient(135deg, #4361ee, #3f37c9);
  color: white;
  cursor: move;
}

.audio-call-mini {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 0 12px;
  gap: 10px;
}

.video-call-mini {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 0 10px;
  gap: 8px;
}

.mini-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: white;
  font-size: 16px;
  flex-shrink: 0;
}

.remote-video-preview {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
  position: relative;
}

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

.video-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.3);
  position: absolute;
  top: 0;
  left: 0;
}

.placeholder-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: white;
  font-size: 14px;
}

.mini-info {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.mini-name {
  font-size: 13px;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.mini-timer {
  font-size: 12px;
  opacity: 0.9;
  font-family: 'Courier New', monospace;
}

.mini-expand-btn {
  width: 24px;
  height: 24px;
  border: none;
  border-radius: 4px;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  transition: all 0.2s ease;
  flex-shrink: 0;
}

.mini-expand-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.video-area {
  position: relative;
  height: calc(100% - 116px);
  background: #000;
  overflow: hidden;
}

.remote-video-container {
  width: 100%;
  height: 100%;
  position: relative;
}

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

.video-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  text-align: center;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
}

.placeholder-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  font-weight: bold;
  color: white;
  margin-bottom: 15px;
}

.placeholder-text {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 8px;
}

.connection-status {
  font-size: 14px;
  opacity: 0.8;
}

.call-timer-display {
  position: absolute;
  top: 16px;
  left: 16px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 8px 12px;
  border-radius: 20px;
  font-size: 14px;
  font-family: 'Courier New', monospace;
  display: flex;
  align-items: center;
  gap: 6px;
  backdrop-filter: blur(10px);
  z-index: 10;
}

/* 连接状态指示器 */
.connection-indicator {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 16px 24px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  gap: 12px;
  backdrop-filter: blur(10px);
  z-index: 10;
}

.spinner {
  width: 20px;
  height: 20px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

/* 视频重试指示器 */
.video-retry-indicator {
  position: absolute;
  top: 60px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(255, 152, 0, 0.9);
  color: white;
  padding: 8px 16px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  backdrop-filter: blur(10px);
  z-index: 10;
}

.retry-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

/* 修复问题1: 视频调试信息样式 */
.video-debug-info {
  position: absolute;
  top: 16px;
  right: 16px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 8px 12px;
  border-radius: 8px;
  font-size: 11px;
  font-family: 'Courier New', monospace;
  max-width: 200px;
  backdrop-filter: blur(10px);
  z-index: 10;
}

.video-debug-info div {
  margin-bottom: 2px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.local-video-container {
  position: absolute;
  bottom: 16px;
  right: 16px;
  width: 120px;
  height: 90px;
  border-radius: 8px;
  overflow: hidden;
  border: 2px solid white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  z-index: 5;
}

.local-placeholder-container {
  position: absolute;
  bottom: 16px;
  right: 16px;
  width: 120px;
  height: 90px;
  border-radius: 8px;
  overflow: hidden;
  border: 2px solid white;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 5;
}

.local-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: bold;
  color: white;
}

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

.call-controls {
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(10px);
  padding: 12px;
  display: flex;
  justify-content: center;
  gap: 16px;
  height: 60px;
}

.control-btn {
  width: 44px;
  height: 44px;
  border: none;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  transition: all 0.3s ease;
}

.control-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.1);
}

.control-btn.active {
  background: #4caf50;
}

.control-btn.disabled {
  background: #ff6b6b;
}

.end-call-btn {
  background: #ff6b6b;
}

.end-call-btn:hover {
  background: #ff5252;
}

.accept-btn-inline {
  background: #4CAF50;
}

.accept-btn-inline:hover {
  background: #45a049;
}

.reject-btn-inline {
  background: #F44336;
}

.reject-btn-inline:hover {
  background: #da190b;
}

.debug-btn {
  background: #9c27b0;
}

.debug-btn:hover {
  background: #7b1fa2;
}

.busy-status-inline {
  background: rgba(255, 107, 107, 0.2);
  color: #ff6b6b;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
  backdrop-filter: blur(10px);
}

.busy-status-inline i {
  font-size: 16px;
}

.ending-notification {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.notification-content {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 24px;
  text-align: center;
  color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.notification-content i {
  font-size: 32px;
  color: #ff6b6b;
}

.notification-content span {
  font-size: 18px;
  font-weight: 500;
}

.countdown {
  font-size: 14px;
  opacity: 0.8;
  font-family: 'Courier New', monospace;
}

@media (max-width: 600px) {
  .video-call-container:not(.minimized) {
    width: 95vw !important;
    height: 75vh !important;
    max-width: 95vw;
    max-height: 75vh;
  }

  .call-header,
  .call-controls {
    padding: 8px;
  }

  .control-btn {
    width: 36px;
    height: 36px;
    font-size: 14px;
  }

  .local-video-container,
  .local-placeholder-container {
    width: 80px;
    height: 60px;
  }

  .video-debug-info {
    font-size: 10px;
    max-width: 150px;
  }
}

@media (max-height: 500px) {
  .video-call-container:not(.minimized) {
    height: 95vh !important;
  }
}
</style>
