<script setup>
import { ref, onMounted, computed } from 'vue'
import { ArrowDownTrayIcon, XMarkIcon } from '@heroicons/vue/24/outline'

const installEvent = ref(null)
const visible = ref(false)
const dismissed = ref(false)
const isIos = ref(false)
const showIosInstructions = ref(false)

const STORAGE_KEY = 'onox-pwa-dismissed'
const VISIT_KEY   = 'onox-pwa-visits'

/** Increment visit count and return the new value */
function trackVisit() {
    const count = parseInt(localStorage.getItem(VISIT_KEY) || '0', 10) + 1
    localStorage.setItem(VISIT_KEY, String(count))
    return count
}

onMounted(() => {
    // Already installed as standalone — never show prompt
    if (window.matchMedia('(display-mode: standalone)').matches) return

    isIos.value = /iphone|ipad|ipod/i.test(navigator.userAgent)

    const dismissedAt = localStorage.getItem(STORAGE_KEY)
    const visitCount  = trackVisit()

    // If dismissed before, only re-show starting from the 3rd visit after that
    if (dismissedAt) {
        if (visitCount < parseInt(dismissedAt, 10) + 3) return
        // Clear the old dismissal so we can remind again from now on
        localStorage.removeItem(STORAGE_KEY)
        localStorage.setItem(VISIT_KEY, '0')
    }

    if (isIos.value) {
        // iOS: no beforeinstallprompt — show our manual guide after a short delay
        setTimeout(() => { visible.value = true }, 5000)
        return
    }

    window.addEventListener('beforeinstallprompt', (e) => {
        e.preventDefault()
        installEvent.value = e
        setTimeout(() => { if (!dismissed.value) visible.value = true }, 5000)
    })

    window.addEventListener('appinstalled', () => {
        visible.value = false
        installEvent.value = null
    })
})

const install = async () => {
    if (isIos.value) {
        // Toggle step-by-step iOS instructions
        showIosInstructions.value = !showIosInstructions.value
        return
    }
    if (!installEvent.value) return
    installEvent.value.prompt()
    const { outcome } = await installEvent.value.userChoice
    if (outcome === 'accepted') {
        visible.value = false
    }
    installEvent.value = null
}

const dismiss = () => {
    visible.value = false
    dismissed.value = true
    // Store current visit count as the dismissal baseline
    const currentVisit = parseInt(localStorage.getItem(VISIT_KEY) || '0', 10)
    localStorage.setItem(STORAGE_KEY, String(currentVisit))
}

const installLabel = computed(() => isIos.value ? 'Nasıl Kurulur?' : 'Yükle')
</script>

<template>
    <Transition
        enter-active-class="transition duration-300 ease-out"
        enter-from-class="translate-y-full opacity-0"
        enter-to-class="translate-y-0 opacity-100"
        leave-active-class="transition duration-200 ease-in"
        leave-from-class="opacity-100"
        leave-to-class="opacity-0"
    >
        <div v-if="visible" class="fixed bottom-20 right-4 z-50 max-w-sm rounded-xl border border-slate-200 bg-white p-4 shadow-2xl dark:border-slate-700 dark:bg-slate-800 lg:bottom-4">
            <div class="flex items-start gap-3">
                <div class="flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-rose-500 to-rose-700 text-2xl">
                    📱
                </div>
                <div class="flex-1">
                    <h3 class="font-semibold text-slate-900 dark:text-slate-100">Onoxsoft'u uygulamaya çevir</h3>
                    <p class="mt-1 text-xs text-slate-600 dark:text-slate-400">
                        Hızlı erişim için ana ekranına ekle. Tarayıcı sekmesi olmadan tek tıkla aç.
                    </p>

                    <!-- iOS step-by-step guide -->
                    <div v-if="isIos && showIosInstructions" class="mt-2 space-y-1 rounded-lg bg-slate-50 p-2 text-xs text-slate-700 dark:bg-slate-700 dark:text-slate-300">
                        <p class="font-medium text-slate-800 dark:text-slate-100">Safari'de nasıl kurulur:</p>
                        <p>1. Alttaki <strong>Paylaş</strong> butonuna dokun (⬆)</p>
                        <p>2. <strong>"Ana Ekrana Ekle"</strong> seçeneğine dokun</p>
                        <p>3. Sağ üstte <strong>Ekle</strong>'ye dokun</p>
                    </div>

                    <div class="mt-3 flex gap-2">
                        <button @click="install" class="inline-flex items-center gap-1 rounded-lg bg-rose-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-rose-700">
                            <ArrowDownTrayIcon v-if="!isIos" class="h-3.5 w-3.5" />
                            {{ installLabel }}
                        </button>
                        <button @click="dismiss" class="rounded-lg px-3 py-1.5 text-xs font-medium text-slate-600 hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-slate-700">
                            Sonra
                        </button>
                    </div>
                </div>
                <button @click="dismiss" class="text-slate-400 hover:text-slate-600 dark:hover:text-slate-300">
                    <XMarkIcon class="h-4 w-4" />
                </button>
            </div>
        </div>
    </Transition>
</template>
