<script setup>
/**
 * PWAInstallPrompt - Componente para promover instalación de PWA
 * Muestra un banner elegante invitando a instalar la app
 */
import { ref, onMounted, onUnmounted } from 'vue';
import { usePWA, useDevice } from '@/Composables/usePWA';

const props = defineProps({
    delay: {
        type: Number,
        default: 5000, // Mostrar después de 5 segundos
    },
    dismissDays: {
        type: Number,
        default: 7, // No mostrar por 7 días si se cierra
    },
});

const { isInstallable, isStandalone, install } = usePWA();
const { isIOS } = useDevice();

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

const storageKey = 'pwa-install-dismissed';

const shouldShow = () => {
    // No mostrar si ya está instalado
    if (isStandalone.value) return false;
    
    // Verificar si fue descartado recientemente
    const dismissed = localStorage.getItem(storageKey);
    if (dismissed) {
        const dismissedDate = new Date(dismissed);
        const daysSince = (Date.now() - dismissedDate.getTime()) / (1000 * 60 * 60 * 24);
        if (daysSince < props.dismissDays) return false;
    }
    
    return true;
};

const show = () => {
    if (shouldShow() && (isInstallable.value || isIOS.value)) {
        isVisible.value = true;
    }
};

const dismiss = () => {
    isVisible.value = false;
    localStorage.setItem(storageKey, new Date().toISOString());
};

const handleInstall = async () => {
    if (isIOS.value) {
        // En iOS no podemos instalar directamente, mostrar instrucciones
        return;
    }
    
    isInstalling.value = true;
    const result = await install();
    isInstalling.value = false;
    
    if (result) {
        isVisible.value = false;
    }
};

let showTimeout = null;

onMounted(() => {
    showTimeout = setTimeout(show, props.delay);
    
    // También mostrar cuando se detecte que es instalable
    window.addEventListener('pwa-installable', show);
});

onUnmounted(() => {
    if (showTimeout) clearTimeout(showTimeout);
    window.removeEventListener('pwa-installable', show);
});
</script>

<template>
    <Transition
        enter-active-class="transition-all duration-300 ease-out"
        enter-from-class="opacity-0 translate-y-full"
        enter-to-class="opacity-100 translate-y-0"
        leave-active-class="transition-all duration-200 ease-in"
        leave-from-class="opacity-100 translate-y-0"
        leave-to-class="opacity-0 translate-y-full"
    >
        <div 
            v-if="isVisible"
            class="fixed bottom-20 md:bottom-6 left-4 right-4 md:left-auto md:right-6 md:w-96 bg-gradient-to-r from-indigo-600 to-purple-600 rounded-2xl shadow-xl z-50 overflow-hidden safe-area-bottom"
        >
            <div class="p-4">
                <div class="flex items-start gap-4">
                    <!-- App Icon -->
                    <div class="flex-shrink-0 w-14 h-14 bg-white rounded-xl shadow-lg flex items-center justify-center">
                        <svg class="w-8 h-8 text-indigo-600" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
                        </svg>
                    </div>
                    
                    <!-- Content -->
                    <div class="flex-1 min-w-0">
                        <h3 class="text-white font-semibold text-base">
                            Instala CoachPro
                        </h3>
                        <p class="text-white/80 text-sm mt-0.5">
                            {{ isIOS 
                                ? 'Toca compartir y "Añadir a inicio"' 
                                : 'Accede más rápido desde tu pantalla de inicio' 
                            }}
                        </p>
                    </div>
                    
                    <!-- Close button -->
                    <button 
                        @click="dismiss"
                        class="flex-shrink-0 p-1 -mr-1 -mt-1 text-white/60 hover:text-white transition-colors"
                    >
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                        </svg>
                    </button>
                </div>
                
                <!-- iOS Instructions -->
                <div v-if="isIOS" class="mt-4 flex items-center gap-2 text-white/80 text-sm">
                    <svg class="w-5 h-5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z"/>
                    </svg>
                    <span>Safari → Compartir → Añadir a pantalla de inicio</span>
                </div>
                
                <!-- Install Button (non-iOS) -->
                <button
                    v-else-if="isInstallable"
                    @click="handleInstall"
                    :disabled="isInstalling"
                    class="mt-4 w-full py-2.5 bg-white text-indigo-600 font-semibold rounded-xl shadow-lg hover:bg-gray-50 active:bg-gray-100 transition-colors disabled:opacity-70 touch-manipulation"
                >
                    <span v-if="isInstalling" class="flex items-center justify-center gap-2">
                        <svg class="w-5 h-5 animate-spin" fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/>
                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"/>
                        </svg>
                        Instalando...
                    </span>
                    <span v-else>Instalar ahora</span>
                </button>
            </div>
        </div>
    </Transition>
</template>
