/**
 * OfflineBanner — Shows a thin banner when device is offline
 * Dark Medical: AMBER background, compact, animated
 */

import { useEffect, useState, useRef } from 'react'
import { View, StyleSheet, Animated } from 'react-native'
import * as Network from 'expo-network'
import { StyledText } from './StyledText'
import { useTranslation } from 'react-i18next'
import { AMBER, NAVY } from '@/src/shared/constants/colors'
import { SPACING } from '@/src/shared/constants/spacing'

export function OfflineBanner() {
  const [isOffline, setIsOffline] = useState(false)
  const slideAnim = useRef(new Animated.Value(-36)).current
  const { t } = useTranslation()

  useEffect(() => {
    let mounted = true

    const check = async () => {
      try {
        const state = await Network.getNetworkStateAsync()
        if (mounted) setIsOffline(!state.isConnected || !state.isInternetReachable)
      } catch {
        // Assume online if check fails
      }
    }

    check()
    const interval = setInterval(check, 5000)

    return () => {
      mounted = false
      clearInterval(interval)
    }
  }, [])

  useEffect(() => {
    Animated.spring(slideAnim, {
      toValue: isOffline ? 0 : -36,
      useNativeDriver: true,
      friction: 8,
    }).start()
  }, [isOffline])

  return (
    <Animated.View
      style={[styles.container, { transform: [{ translateY: slideAnim }] }]}
      pointerEvents="none"
    >
      <StyledText size={12} weight="semibold" color={NAVY[900]}>
        {t('common:offline')}
      </StyledText>
    </Animated.View>
  )
}

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    height: 36,
    backgroundColor: AMBER[500],
    alignItems: 'center',
    justifyContent: 'center',
    zIndex: 999,
  },
})
