import { useEffect, useState } from 'react'
import { useRegisterSW } from 'virtual:pwa-register/react'

export default function PWAUpdatePrompt() {
  const [showPrompt, setShowPrompt] = useState(false)
  
  const {
    needRefresh: [needRefresh, setNeedRefresh],
    updateServiceWorker
  } = useRegisterSW({
    onRegistered(r) {
      console.log('SW зарегистрирован:', r)
    },
    onRegisterError(error) {
      console.log('SW ошибка регистрации:', error)
    }
  })

  useEffect(() => {
    if (needRefresh) {
      setShowPrompt(true)
    }
  }, [needRefresh])

  const handleUpdate = () => {
    updateServiceWorker(true)
    setShowPrompt(false)
  }

  const handleDismiss = () => {
    setNeedRefresh(false)
    setShowPrompt(false)
  }

  if (!showPrompt) return null

  return (
    <div className="fixed bottom-24 left-4 right-4 md:left-auto md:right-4 md:w-80 bg-white rounded-lg shadow-lg border border-gray-200 p-4 z-50">
      <p className="text-sm text-gray-700 mb-3">
        Доступна новая версия приложения
      </p>
      <div className="flex gap-2">
        <button
          onClick={handleUpdate}
          className="flex-1 px-3 py-2 bg-indigo-600 text-white text-sm rounded-md hover:bg-indigo-700"
        >
          Обновить
        </button>
        <button
          onClick={handleDismiss}
          className="px-3 py-2 bg-gray-100 text-gray-700 text-sm rounded-md hover:bg-gray-200"
        >
          Позже
        </button>
      </div>
    </div>
  )
}

