<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'

interface BeforeInstallPromptEvent extends Event {
  prompt(): Promise<void>
  userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }>
}

const installPrompt = ref<BeforeInstallPromptEvent | null>(null)
const isInstalled = ref(false)
const isPwa = ref(false)
const dismissed = ref(false)

// Check if running as PWA (standalone mode)
const checkPwaMode = () => {
  isPwa.value = window.matchMedia('(display-mode: standalone)').matches ||
    (window.navigator as any).standalone === true ||
    document.referrer.includes('android-app://')
}

// Check if app is already installed
const checkInstalled = () => {
  if ('getInstalledRelatedApps' in navigator) {
    (navigator as any).getInstalledRelatedApps().then((apps: any[]) => {
      isInstalled.value = apps.length > 0
    }).catch(() => {})
  }
}

const handleBeforeInstallPrompt = (e: Event) => {
  e.preventDefault()
  installPrompt.value = e as BeforeInstallPromptEvent
}

const handleAppInstalled = () => {
  isInstalled.value = true
  installPrompt.value = null
}

const install = async () => {
  if (!installPrompt.value) return

  await installPrompt.value.prompt()
  const { outcome } = await installPrompt.value.userChoice

  if (outcome === 'accepted') {
    isInstalled.value = true
  }
  installPrompt.value = null
}

const dismiss = () => {
  dismissed.value = true
  sessionStorage.setItem('pwa-dismissed', 'true')
}

const showBanner = computed(() => {
  if (isPwa.value) return false
  if (dismissed.value) return false
  return installPrompt.value !== null
})

onMounted(() => {
  checkPwaMode()
  checkInstalled()

  // Check if dismissed this session
  dismissed.value = sessionStorage.getItem('pwa-dismissed') === 'true'

  window.addEventListener('beforeinstallprompt', handleBeforeInstallPrompt)
  window.addEventListener('appinstalled', handleAppInstalled)

  // Listen for display mode changes
  window.matchMedia('(display-mode: standalone)').addEventListener('change', checkPwaMode)
})

onUnmounted(() => {
  window.removeEventListener('beforeinstallprompt', handleBeforeInstallPrompt)
  window.removeEventListener('appinstalled', handleAppInstalled)
})
</script>

<template>
  <Transition name="banner">
    <div v-if="showBanner" class="pwa-banner">
      <div class="banner-content">
        <div class="banner-icon">
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
            <polyline points="7 10 12 15 17 10"/>
            <line x1="12" y1="15" x2="12" y2="3"/>
          </svg>
        </div>
        <span class="banner-text">Instalar Agent UI</span>
      </div>
      <div class="banner-actions">
        <button class="btn-install" @click="install">
          Instalar
        </button>
        <button class="btn-dismiss" @click="dismiss" title="Cerrar">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <line x1="18" y1="6" x2="6" y2="18"/>
            <line x1="6" y1="6" x2="18" y2="18"/>
          </svg>
        </button>
      </div>
    </div>
  </Transition>
</template>

<style scoped>
.pwa-banner {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
  padding: 0.5rem 0.75rem;
  background: linear-gradient(135deg, rgba(99, 102, 241, 0.15) 0%, rgba(139, 92, 246, 0.15) 100%);
  border: 1px solid rgba(99, 102, 241, 0.3);
  border-radius: 8px;
  margin-left: 1rem;
}

.banner-content {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.banner-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  border-radius: 6px;
  color: white;
}

.banner-text {
  font-size: 0.85rem;
  font-weight: 500;
  color: var(--text-primary);
  white-space: nowrap;
}

.banner-actions {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.btn-install {
  padding: 0.35rem 0.75rem;
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 0.8rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-install:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.4);
}

.btn-dismiss {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  background: transparent;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.2s;
}

.btn-dismiss:hover {
  background: rgba(255, 255, 255, 0.1);
  color: var(--text-primary);
}

/* Transition */
.banner-enter-active,
.banner-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.banner-enter-from,
.banner-leave-to {
  opacity: 0;
  transform: translateX(-10px);
}

/* Responsive */
@media (max-width: 640px) {
  .pwa-banner {
    position: fixed;
    bottom: 80px;
    left: 16px;
    right: 16px;
    margin: 0;
    z-index: 9990;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  }

  .banner-text {
    font-size: 0.9rem;
  }
}
</style>
