<template>
  <div class="pop-container">
    <!-- 触发按钮 -->
    <div 
      ref="buttonRef"
      class="trigger-button" 
      @click="handleClick" 
      :style="[bgColorStyle, positionStyle]"
      :class="{ 'dragging': isDragging }"
    >
      <div class="chat-icon">
        <SmileOutlined/>
      </div>
      <span class="button-text">AI 助手</span>
    </div>

    <!-- 聊天面板 -->
    <div v-if="isChatVisible" class="chat-panel" :class="{ 'panel-visible': isChatVisible }" :style="panelPositionStyle">
      <div class="panel-header" :style="bgColorStyle">
        <h3>AI 智能助手</h3>
        <button class="close-btn" @click="closeChat">
          <CloseOutlined/>
        </button>
      </div>
      <div class="panel-content">
        <AiChat :bgColorStyle="bgColorStyle" :themeColorStyle="themeColorStyle" :pollingInterval="parsedPollingInterval"/>
      </div>
    </div>

    <!-- 遮罩层 -->
    <div v-if="isChatVisible" class="overlay" @click="closeChat"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import AiChat from './content.vue'
import { useDrag } from './hooks/useDragFixed'
import { usePanelPosition } from './hooks/usePanelPosition'
import { CloseOutlined, SmileOutlined } from '@ant-design/icons-vue'

const props = defineProps({
  themeColor: {
    type: [String, Array],
    default: () => ['#667eea']
  },
  position: {
    type: [String, Object],
    default: () => ({
      top: 'auto',
      right: '20px',
      bottom: '20px',
      left: 'auto'
    })
  },
  draggable: {
    type: [Boolean, String],
    default: true
  },
  pollingInterval: {
    type: Number,
    default: 500
  }
})

const emit = defineEmits(['position-change'])

// 解析Web Components属性
const parsedThemeColor = computed(() => {
  if (typeof props.themeColor === 'string') {
    try {
      return JSON.parse(props.themeColor)
    } catch {
      return [props.themeColor]
    }
  }
  return props.themeColor
})

const parsedPosition = computed(() => {
  if (typeof props.position === 'string') {
    try {
      return JSON.parse(props.position)
    } catch {
      return {
        top: 'auto',
        right: '20px',
        bottom: '20px',
        left: 'auto'
      }
    }
  }
  return props.position
})

const parsedDraggable = computed(() => {
  if (typeof props.draggable === 'string') {
    return props.draggable === 'true'
  }
  return props.draggable
})

const parsedPollingInterval = computed(() => {
  if (typeof props.pollingInterval === 'string') {
    return parseInt(props.pollingInterval, 10) || 500
  }
  return props.pollingInterval
})

// 模板引用
const buttonRef = ref<HTMLElement>()

const themeColorStyle = computed(() => {
  if (Array.isArray(parsedThemeColor.value)) {
    return parsedThemeColor.value?.length === 1 ? [...parsedThemeColor.value, ...parsedThemeColor.value] : parsedThemeColor.value
  }
  return [parsedThemeColor.value, parsedThemeColor.value]
})

const bgColorStyle: any = computed(() => {
  return {
    background: `linear-gradient(135deg, ${themeColorStyle.value[0]} 0%, ${themeColorStyle.value[1]} 100%)`,
    'box-shadow': `0 4px 12px ${themeColorStyle.value[0]}66`,
    color: 'white'
  }
})

const positionStyle: any = computed(() => {
  return {
    position: 'fixed',
    top: parsedPosition.value.top || 'auto',
    right: parsedPosition.value.right || 'auto',
    bottom: parsedPosition.value.bottom || 'auto',
    left: parsedPosition.value.left || 'auto'
  }
})

// 响应式数据
const isChatVisible = ref(false)

// 使用拖拽 hook
const { isDragging, position: dragPosition } = useDrag(buttonRef, {
  draggable: parsedDraggable.value,
  inertia: true,
  autoScroll: true,
  restrictToViewport: true
})

// 使用面板位置计算 hook
const { panelPositionStyle } = usePanelPosition(
  buttonRef,
  dragPosition,
  positionStyle,
  {
    panelWidth: 400,
    panelHeight: 600,
    margin: 10,
    safeMargin: 10
  }
)

// 切换聊天面板显示状态
const toggleChat = () => {
  isChatVisible.value = !isChatVisible.value
}

// 关闭聊天面板
const closeChat = () => {
  isChatVisible.value = false
}

// 处理点击事件（避免拖拽时触发点击）
const handleClick = () => {
  if (!isDragging.value) {
    toggleChat()
  }
}
</script>

<style scoped>
.pop-container {
  position: relative;
}

/* 触发按钮样式 */
.trigger-button {
  position: fixed;
  z-index: 1001;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  color: white;
  border-radius: 25px;
  cursor: pointer;
  transition: all 0.3s ease;
  user-select: none;
  touch-action: none; /* 禁用浏览器默认触摸手势 */
}

.trigger-button:hover {
  transform: translateY(-2px);
}

.trigger-button.dragging {
  opacity: 0.8;
  transform: scale(1.05);
  cursor: grabbing;
  z-index: 1003;
  transition: none; /* 拖拽时禁用过渡动画 */
}

.chat-icon {
  display: flex;
  align-items: center;
  justify-content: center;
}

.button-text {
  font-size: 14px;
  font-weight: 500;
}

/* 聊天面板样式 */
.chat-panel {
  position: fixed;
  z-index: 1002;
  width: 400px;
  height: 600px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  transform: translateY(20px) scale(0.95);
  opacity: 0;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.chat-panel.panel-visible {
  transform: translateY(0) scale(1);
  opacity: 1;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  color: white;
  border-radius: 12px 12px 0 0;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: background-color 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.panel-content {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 遮罩层 */
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  z-index: 1001;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

/* 确保 AiChat 组件在面板中正确显示 */
.panel-content :deep(.ai-chat-container) {
  position: relative;
  bottom: auto;
  right: auto;
  width: 100%;
  height: 100%;
  margin: 0;
  border-radius: 0;
}
</style>
