<template>
	<div class="border transition-all border-bottom-1px border-b-solid border-gray-200">
		<!-- 分支头部 -->
		<div
			class="flex items-center justify-between px-4 py-3 cursor-pointer bg-white"
			style="border-bottom: 1px solid #eee"
			@click="toggleExpanded"
		>
			<div class="flex items-center gap-3">
				<!-- 分支类型标签 -->
				<div class="px-2.5 py-1 rounded text-xs font-bold" :class="branchTypeClass">
					{{ branchTypeLabel }}
				</div>

				<!-- 分支标题 -->
				<div class="flex flex-col">
					<span class="text-sm font-medium text-gray-900">{{ branch.label }}</span>
					<span v-if="branch.description" class="text-xs text-gray-500">
						{{ branch.description }}
					</span>
				</div>
			</div>

			<div class="flex items-center gap-2">
				<!-- 删除按钮 (只有 ELIF 可以删除) -->
				<el-tooltip :content="t('common.nodeBase.branchCard.deleteCondition')" placement="top">
					<Icon
						v-if="branch.type === 'elif'"
						@click.stop="handleRemove"
						class="p-1.5 hover:bg-red-50 rounded transition-colors"
						icon="lucide:trash-2"
					/>
				</el-tooltip>

				<!-- 展开/收起图标 -->
				<Icon
					:icon="isExpanded ? 'lucide:chevron-up' : 'lucide:chevron-down'"
					class="text-gray-400"
				/>
			</div>
		</div>

		<!-- 分支内容 -->
		<div
			v-show="isExpanded"
			class="px-4 pb-4 space-y-3 border-t border-gray-100 bg-orange-50"
			:class="{ '!bg-gray-100': branch.type === 'else' }"
		>
			<!-- IF 和 ELIF 的条件配置 -->
			<div v-if="branch.type !== 'else'" class="pt-3">
				<slot name="condition"></slot>
			</div>
			<div v-else-if="branch.type === 'else'" class="pt-3">
				<slot name="else"></slot>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { Icon } from '@repo/ui'
import { useI18n } from '@/composables/useI18n'

interface Branch {
	id: string
	type: 'if' | 'elif' | 'else'
	label: string
	description?: string
	conditions?: any[]
}

interface Props {
	branch: Branch
	isActive?: boolean
	isDragging?: boolean
}

interface Emits {
	(e: 'remove'): void
	(e: 'toggle'): void
}

const props = withDefaults(defineProps<Props>(), {
	isActive: false,
	isDragging: false
})

const emit = defineEmits<Emits>()
const { t } = useI18n()

const isExpanded = ref(true)

const branchTypeLabel = computed(() => {
	const labels: Record<string, string> = {
		if: t('common.nodeBase.branchCard.ifBranch'),
		elif: t('common.nodeBase.branchCard.elseIfBranch'),
		else: t('common.nodeBase.branchCard.elseBranch')
	}
	return labels[props.branch.type] || t('common.nodeBase.branchCard.ifBranch')
})

const branchTypeClass = computed(() => {
	const classes: Record<string, string> = {
		if: 'bg-orange-500 text-white',
		elif: 'bg-orange-500 text-white',
		else: 'bg-gray-900 text-white'
	}
	return classes[props.branch.type] || 'bg-blue-100 text-blue-700'
})

const toggleExpanded = () => {
	isExpanded.value = !isExpanded.value
	emit('toggle')
}

const handleRemove = () => {
	emit('remove')
}
</script>
