<script setup>
import { computed, ref, onMounted, onBeforeUnmount, watch } from 'vue'
import { useProductTour } from '@/Composables/useProductTour'
import { ChevronLeftIcon, ChevronRightIcon, XMarkIcon } from '@heroicons/vue/24/outline'

const tour = useProductTour()
const tooltipStyle = ref({})

const stepData = computed(() => tour.currentStepData())
const isFirst = computed(() => tour.currentStep.value === 0)
const isLast = computed(() => {
    const steps = tour.currentTour.value?.steps
    return steps && tour.currentStep.value === steps.length - 1
})

function positionTooltip() {
    if (!stepData.value) return

    const target = document.querySelector(stepData.value.selector)
    if (!target) return

    const rect = target.getBoundingClientRect()
    const position = stepData.value.position || 'bottom'

    const tooltipWidth = 360
    const tooltipHeight = 200
    const gap = 12

    let top, left

    switch (position) {
        case 'top':
            top = rect.top - tooltipHeight - gap + window.scrollY
            left = rect.left + (rect.width - tooltipWidth) / 2
            break
        case 'bottom':
            top = rect.bottom + gap + window.scrollY
            left = rect.left + (rect.width - tooltipWidth) / 2
            break
        case 'left':
            top = rect.top + (rect.height - tooltipHeight) / 2 + window.scrollY
            left = rect.left - tooltipWidth - gap
            break
        case 'right':
        default:
            top = rect.top + (rect.height - tooltipHeight) / 2 + window.scrollY
            left = rect.right + gap
            break
    }

    // Keep within viewport
    left = Math.max(16, Math.min(left, window.innerWidth - tooltipWidth - 16))
    top = Math.max(16 + window.scrollY, top)

    tooltipStyle.value = {
        position: 'absolute',
        top: `${top}px`,
        left: `${left}px`,
        width: `${tooltipWidth}px`,
    }
}

function targetMaskStyle() {
    if (!stepData.value) return {}

    const target = document.querySelector(stepData.value.selector)
    if (!target) return {}

    const rect = target.getBoundingClientRect()
    const pad = 8

    return {
        position: 'absolute',
        top: `${rect.top + window.scrollY - pad}px`,
        left: `${rect.left - pad}px`,
        width: `${rect.width + pad * 2}px`,
        height: `${rect.height + pad * 2}px`,
        boxShadow: '0 0 0 9999px rgba(15, 23, 42, 0.65)',
        borderRadius: '8px',
        pointerEvents: 'none',
        zIndex: 9998,
        transition: 'all 0.3s ease',
    }
}

let mutationObserver
onMounted(() => {
    window.addEventListener('resize', positionTooltip)
    window.addEventListener('scroll', positionTooltip)
    mutationObserver = new MutationObserver(positionTooltip)
    mutationObserver.observe(document.body, { childList: true, subtree: true })
})
onBeforeUnmount(() => {
    window.removeEventListener('resize', positionTooltip)
    window.removeEventListener('scroll', positionTooltip)
    mutationObserver?.disconnect()
})

watch(stepData, () => setTimeout(positionTooltip, 100))
</script>

<template>
    <Teleport to="body">
        <Transition name="tour">
            <div v-if="tour.isActive.value && stepData" class="tour-overlay">
                <!-- Dimmed mask with highlight cutout (box-shadow trick) -->
                <div :style="targetMaskStyle()"></div>

                <!-- Tooltip card -->
                <div :style="tooltipStyle" class="z-[9999] rounded-2xl bg-white shadow-2xl p-5 dark:bg-slate-800">
                    <div class="flex items-start justify-between mb-3">
                        <div>
                            <p class="text-xs uppercase tracking-wide text-indigo-600 font-semibold">
                                {{ tour.currentStep.value + 1 }} / {{ tour.currentTour.value.steps.length }}
                                &middot; {{ tour.currentTour.value.name }}
                            </p>
                            <h3 class="text-lg font-semibold text-slate-900 dark:text-slate-100 mt-1">
                                {{ stepData.title }}
                            </h3>
                        </div>
                        <button
                            @click="tour.skipTour()"
                            class="ml-4 shrink-0 text-slate-400 hover:text-slate-600 dark:hover:text-slate-300"
                            title="Kapat"
                        >
                            <XMarkIcon class="h-5 w-5" />
                        </button>
                    </div>

                    <!-- eslint-disable-next-line vue/no-v-html -->
                    <p class="text-sm text-slate-700 dark:text-slate-300 mb-4 leading-relaxed" v-html="stepData.content"></p>

                    <!-- Step dots -->
                    <div class="flex justify-center gap-1.5 mb-3">
                        <span
                            v-for="(_, i) in tour.currentTour.value.steps"
                            :key="i"
                            :class="[
                                'inline-block h-1.5 rounded-full transition-all',
                                i === tour.currentStep.value ? 'w-4 bg-indigo-600' : 'w-1.5 bg-slate-300 dark:bg-slate-600',
                            ]"
                        ></span>
                    </div>

                    <div class="flex justify-between items-center">
                        <button
                            @click="tour.skipTour()"
                            class="text-xs text-slate-500 hover:text-slate-700 dark:hover:text-slate-300"
                        >
                            Turu Atla
                        </button>
                        <div class="flex gap-2">
                            <button
                                v-if="!isFirst"
                                @click="tour.prevStep()"
                                class="inline-flex items-center gap-1 rounded-lg border border-slate-300 px-3 py-1.5 text-sm font-medium text-slate-700 hover:bg-slate-50 dark:border-slate-600 dark:text-slate-300 dark:hover:bg-slate-700"
                            >
                                <ChevronLeftIcon class="h-4 w-4" /> Geri
                            </button>
                            <button
                                @click="tour.nextStep()"
                                class="inline-flex items-center gap-1 rounded-lg bg-indigo-600 px-4 py-1.5 text-sm font-medium text-white hover:bg-indigo-700"
                            >
                                {{ isLast ? 'Tamamla' : 'İleri' }}
                                <ChevronRightIcon v-if="!isLast" class="h-4 w-4" />
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </Transition>
    </Teleport>
</template>

<style scoped>
.tour-enter-active,
.tour-leave-active {
    transition: opacity 0.3s ease;
}
.tour-enter-from,
.tour-leave-to {
    opacity: 0;
}
</style>
