import { ref, computed } from 'vue'
import { usePage, router } from '@inertiajs/vue3'

/**
 * Lightweight product tour — no external library.
 * Uses position:absolute overlays + Tailwind animations.
 */
export function useProductTour() {
    const page = usePage()
    const currentStep = ref(0)
    const isActive = ref(false)
    const currentTour = ref(null)

    const onboarding = computed(() => page.props.onboarding ?? {})

    /**
     * Tour definition shape:
     * {
     *   id: 'customer-intro',
     *   name: 'Müşteri Paneli Tanıtımı',
     *   steps: [
     *     { selector: 'aside', title: 'Sol Menü', content: '...', position: 'right' },
     *   ]
     * }
     */
    function startTour(tour) {
        if (hasCompleted(tour.id)) return

        currentTour.value = tour
        currentStep.value = 0
        isActive.value = true

        // Wait for DOM settle
        setTimeout(() => highlightStep(), 100)
    }

    function nextStep() {
        if (!currentTour.value) return

        if (currentStep.value < currentTour.value.steps.length - 1) {
            currentStep.value++
            highlightStep()
        } else {
            completeTour()
        }
    }

    function prevStep() {
        if (currentStep.value > 0) {
            currentStep.value--
            highlightStep()
        }
    }

    function skipTour() {
        completeTour()
    }

    async function completeTour() {
        const tourId = currentTour.value?.id
        isActive.value = false
        currentTour.value = null
        currentStep.value = 0

        if (!tourId) return

        // Persist to backend
        try {
            await fetch('/api/onboarding/complete-tour', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '',
                },
                body: JSON.stringify({ tour_id: tourId }),
            })
        } catch (e) {
            console.warn('Tour completion persist failed', e)
        }

        // Refresh onboarding shared prop
        router.reload({ only: ['onboarding'] })
    }

    function hasCompleted(tourId) {
        return (onboarding.value?.completed_tours ?? []).includes(tourId)
    }

    function currentStepData() {
        if (!isActive.value || !currentTour.value) return null
        return currentTour.value.steps[currentStep.value] ?? null
    }

    function highlightStep() {
        const step = currentStepData()
        if (!step) return

        const target = document.querySelector(step.selector)
        if (!target) {
            console.warn(`[Tour] selector not found: ${step.selector}`)
            return
        }

        target.scrollIntoView({ behavior: 'smooth', block: 'center' })
    }

    return {
        startTour,
        nextStep,
        prevStep,
        skipTour,
        completeTour,
        hasCompleted,
        isActive,
        currentStep,
        currentTour,
        currentStepData,
    }
}
