<template>
	<div class="chart-ai-analysis" @mouseenter="handleMouseEnter" @mouseleave="handleMouseLeave">
		<!-- 触发按钮 -->
		<div class="ai-button-wrapper">
			<AiButton />
		</div>

		<!-- AI 内容面板 -->
		<transition name="ai-fade">
			<div v-if="isVisible" class="ai-pane-wrapper">
				<div class="ai-pane-content">
					<!-- 1. Loading 状态 -->
					<div v-if="hookInstance.loading" class="ai-loading-text">智能总结生成中...</div>

					<!-- 2. 错误状态 -->
					<div v-else-if="hookInstance.error" class="ai-error-text">
						{{ hookInstance.error }}
					</div>

					<!-- 3. 成功状态 -->
					<div v-else-if="hookInstance.interpretation" class="ai-success-content">
						<AiPane :aiContent="hookInstance.interpretation" />
					</div>

					<!-- 4. 初始空状态 (可选，防止闪烁) -->
					<div v-else class="ai-empty-text">暂无数据</div>
				</div>
			</div>
		</transition>
	</div>
</template>

<script setup>
import { ref } from "vue";
import AiButton from "@/components/base/Ai/AiButton/index.vue";
import AiPane from "@/components/base/Ai/AiPane/index.vue";

const props = defineProps({
	// 接收由 useChartInterpretation() 创建的实例对象
	hookInstance: {
		type: Object,
		required: true
	},
	// 图表数据 Payload，用于首次请求
	payload: {
		type: Object,
		required: true
	}
});

const isVisible = ref(false);
const hasRequested = ref(false);

const handleMouseEnter = () => {
	isVisible.value = true;

	// 如果还没有请求过数据，则发起请求
	if (!hasRequested.value && !props.hookInstance.loading) {
		hasRequested.value = true;
		// 调用 Hook 中的 interpret 方法
		props.hookInstance.interpret(props.payload);
	}
};

const handleMouseLeave = () => {
	isVisible.value = false;
};
</script>

<style lang="scss" scoped>
.chart-ai-analysis {
	position: absolute;
	right: 0px;
	bottom: 15px;
	z-index: 999;
	width: auto;
	height: auto;

	.ai-button-wrapper {
		display: flex;
		justify-content: flex-end;
	}

	.ai-pane-wrapper {
		position: absolute;
		bottom: 0;
		right: 0;
		width: 100%;
		// 确保面板出现在按钮上方或覆盖区域，根据原有 CSS 调整
		// 原有 .ai-pane:hover 逻辑是宽度变宽，这里我们直接显示完整面板
		background: #fff;
		border-radius: 4px;
		box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.1);
		padding: 10px;
		box-sizing: border-box;

		.ai-pane-content {
			min-height: 40px;

			.ai-loading-text,
			.ai-error-text,
			.ai-empty-text {
				font-size: 14px;
				color: var(--text-primary-50-color);
				display: flex;
				align-items: center;
				justify-content: center;
				min-height: 40px;
			}

			.ai-error-text {
				color: var(--color-red-100);
			}
		}
	}
}

// 复用原有的淡入淡出动画
.ai-fade-enter-active,
.ai-fade-leave-active {
	transition: opacity 0.3s ease;
}

.ai-fade-enter-from,
.ai-fade-leave-to {
	opacity: 0;
}
</style>
