<template>
  <view v-if="isOffline" class="offline-banner">
    <text class="offline-icon">📡</text>
    <text class="offline-text">网络已断开</text>
  </view>
</template>

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

const isOffline = ref(false);

// #ifdef H5
function checkNetworkStatus() {
  if (typeof navigator !== 'undefined' && navigator.onLine !== undefined) {
    isOffline.value = !navigator.onLine;
  }
}

function onOnline() {
  isOffline.value = false;
  uni.showToast({
    title: '网络已恢复',
    icon: 'success',
  });
}

function onOffline() {
  isOffline.value = true;
  uni.showToast({
    title: '网络已断开',
    icon: 'none',
  });
}

onMounted(() => {
  checkNetworkStatus();

  if (typeof window !== 'undefined') {
    window.addEventListener('online', onOnline);
    window.addEventListener('offline', onOffline);
  }
});

onUnmounted(() => {
  if (typeof window !== 'undefined') {
    window.removeEventListener('online', onOnline);
    window.removeEventListener('offline', onOffline);
  }
});
// #endif

// #ifndef H5
// App 端使用 uni-app API
onMounted(() => {
  uni.onNetworkStatusChange((res) => {
    isOffline.value = !res.isConnected;
    if (res.isConnected) {
      uni.showToast({ title: '网络已恢复', icon: 'success' });
    } else {
      uni.showToast({ title: '网络已断开', icon: 'none' });
    }
  });
});
// #endif
</script>

<style scoped>
.offline-banner {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: linear-gradient(90deg, #ff6b6b, #ee5a6f);
  color: white;
  padding: 16rpx 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  z-index: 9999;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
}

.offline-icon {
  font-size: 32rpx;
}

.offline-text {
  font-size: 28rpx;
  font-weight: 500;
}
</style>
