"use client"

import { useState, useEffect, useRef } from "react"
import NetInfo from "@react-native-community/netinfo"

export const useNetworkStatus = () => {
  const [isConnected, setIsConnected] = useState(true)
  const [wasConnected, setWasConnected] = useState(true)
  const prevConnectedRef = useRef(true)

  useEffect(() => {
    // Verificar estado inicial da rede
    NetInfo.fetch().then((state) => {
      const connected = state.isConnected !== null ? state.isConnected : false
      setIsConnected(connected)
      setWasConnected(connected)
      prevConnectedRef.current = connected
    })

    // Inscrever-se para atualizações de estado da rede
    const unsubscribe = NetInfo.addEventListener((state) => {
      const currentlyConnected = state.isConnected !== null ? state.isConnected : false

      // Atualizar estado anterior
      setWasConnected(prevConnectedRef.current)
      setIsConnected(currentlyConnected)

      prevConnectedRef.current = currentlyConnected
    })

    return () => unsubscribe()
  }, [])

  // Retorna se acabou de ficar offline (estava conectado e agora não está)
  const justWentOffline = wasConnected && !isConnected

  return {
    isConnected,
    wasConnected,
    justWentOffline,
  }
}
