<template>
  <view class="page">
    <view class="header-hero" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="top-bar">
        <view class="top-left" />
        <view class="top-center">
          <text class="page-title">{{ t('login.selectStore') }}</text>
          <text class="page-sub">{{ t('login.welcomeUser') }} {{ userName }}</text>
        </view>
        <view class="top-right" />
      </view>
    </view>

    <view class="list">
      <view v-if="!loading && stores.length === 0" class="empty-hint">
        <text class="empty-text">{{ t('login.noStoresBound') }}</text>
      </view>
      <view
        v-for="store in stores"
        :key="store.id"
        class="card"
        :class="{ selected: selectedStore === store.id }"
        @click="selectedStore = store.id"
      >
        <view class="card-icon" :class="{ selected: selectedStore === store.id }">
          <AppIcon name="mapPin" size="md" :color="selectedStore === store.id ? 'white' : 'gray'" />
        </view>
        <view class="card-content">
          <text class="card-title">{{ store.locationName }}</text>
          <view class="info-row">
            <AppIcon name="mapPin" size="sm" color="gray" />
            <text class="info">{{ store.fullAddress }}</text>
          </view>
          <text v-if="store.locationCode" class="info muted">{{ store.locationCode }}</text>
        </view>
        <view class="card-check">
          <AppIcon
            v-if="selectedStore === store.id"
            name="check"
            size="sm"
            color="white"
          />
          <AppIcon
            v-else
            name="chevronRight"
            size="sm"
            color="gray"
          />
        </view>
      </view>
    </view>

    <view class="bottom-bar" :style="{ paddingBottom: (bottomSafeArea + 24) + 'px' }">
      <view v-if="!loading && stores.length === 0" class="bottom-actions-row">
        <view class="back-btn" @click="handleBackToLogin">
          <text class="back-btn-text">{{ t('common.back') }}</text>
        </view>
        <view class="confirm-btn disabled">
          <text class="confirm-btn-text">{{ t('common.confirm') }}</text>
        </view>
      </view>
      <view
        v-else
        class="confirm-btn"
        :class="{ disabled: !selectedStore || loading }"
        @click="handleConfirm"
      >
        <text class="confirm-btn-text">{{ loading ? '…' : t('common.confirm') }}</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { onShow } from '@dcloudio/uni-app'
import AppIcon from '../../components/AppIcon.vue'
import { getStatusBarHeight, getBottomSafeArea } from '../../utils/statusBar'
import { usAppFetchMyLocations } from '../../services/usAppAuth'
import type { UsAppBoundLocationDto } from '../../types/usAppBound'
import { isUsAppSessionExpiredError } from '../../utils/usAppApiRequest'
import { setBoundLocations, getBoundLocations, clearAuthSession } from '../../utils/authSession'
import { switchStore } from '../../utils/stores'

const { t } = useI18n()
const statusBarHeight = getStatusBarHeight()
const bottomSafeArea = getBottomSafeArea()
const userName = computed(() => uni.getStorageSync('userName') || 'Employee')
const selectedStore = ref('')
const stores = ref<UsAppBoundLocationDto[]>([])
const loading = ref(false)

function applyList(list: UsAppBoundLocationDto[]) {
  const enabled = list.filter((s) => s.state !== false)
  stores.value = enabled
  setBoundLocations(enabled)
}

async function refreshFromApi() {
  loading.value = true
  try {
    const list = await usAppFetchMyLocations()
    applyList(list)
  } catch (e) {
    if (isUsAppSessionExpiredError(e)) return
    applyList(getBoundLocations())
    uni.showToast({ title: t('login.refreshStoresFail'), icon: 'none' })
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  applyList(getBoundLocations())
  refreshFromApi()
})

onShow(() => {
  applyList(getBoundLocations())
})

const handleBackToLogin = () => {
  clearAuthSession()
  uni.redirectTo({ url: '/pages/login/login' })
}

const handleConfirm = () => {
  if (loading.value || !selectedStore.value) {
    if (!selectedStore.value) {
      uni.showToast({ title: t('login.selectStoreError'), icon: 'none' })
    }
    return
  }
  const store = stores.value.find((s) => s.id === selectedStore.value)
  if (!store) return
  switchStore(store.id, store.locationName, store.locationCode)
  uni.showToast({ title: t('login.storeSelected'), icon: 'success' })
  setTimeout(() => {
    uni.redirectTo({ url: '/pages/index/index' })
  }, 400)
}
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: #f9fafb;
  display: flex;
  flex-direction: column;
}

.header-hero {
  flex-shrink: 0;
  background: linear-gradient(135deg, var(--theme-primary), var(--theme-primary-dark));
  padding: 16rpx 32rpx 32rpx;
}

.top-bar {
  height: 96rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.top-left,
.top-right {
  width: 64rpx;
  height: 64rpx;
}

.top-center {
  flex: 1;
  text-align: center;
}

.page-title {
  font-size: 34rpx;
  font-weight: 600;
  color: #fff;
  display: block;
  margin-bottom: 4rpx;
}

.page-sub {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.85);
}

.list {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  padding: 32rpx;
  padding-bottom: 24rpx;
}

.empty-hint {
  padding: 48rpx 24rpx;
  text-align: center;
}

.empty-text {
  font-size: 28rpx;
  color: #6b7280;
}

.card {
  padding: 32rpx;
  background: #ffffff;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: flex-start;
  gap: 24rpx;
  border: 3rpx solid #e5e7eb;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

.card.selected {
  border-color: var(--theme-primary);
  background: var(--theme-primary-light);
}

.card-icon {
  width: 80rpx;
  height: 80rpx;
  background: #f3f4f6;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.card-icon.selected {
  background: var(--theme-primary);
}

.card-content {
  flex: 1;
  min-width: 0;
}

.card-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #111827;
  display: block;
  margin-bottom: 12rpx;
}

.info-row {
  display: flex;
  align-items: flex-start;
  gap: 12rpx;
  margin-bottom: 6rpx;
}

.info {
  font-size: 26rpx;
  color: #6b7280;
  display: block;
  margin-bottom: 6rpx;
}

.info.muted {
  color: #9ca3af;
  font-size: 24rpx;
}

.card-check {
  width: 44rpx;
  height: 44rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  background: transparent;
}

.card.selected .card-check {
  background: var(--theme-primary);
}

.bottom-bar {
  flex-shrink: 0;
  padding: 24rpx 48rpx;
  background: #ffffff;
  border-top: 1rpx solid #e5e7eb;
}

.bottom-actions-row {
  display: flex;
  align-items: stretch;
  gap: 24rpx;
}

.back-btn {
  flex: 1;
  height: 96rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 3rpx solid var(--theme-primary);
  background: #ffffff;
  box-sizing: border-box;
}

.back-btn-text {
  font-size: 32rpx;
  font-weight: 600;
  color: var(--theme-primary);
  line-height: 1;
}

.bottom-actions-row .confirm-btn {
  flex: 1;
}

.confirm-btn {
  width: 100%;
  height: 96rpx;
  background: var(--theme-primary);
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.confirm-btn.disabled {
  opacity: 0.5;
}

.confirm-btn-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #fff;
  line-height: 1;
}
</style>
