<template>
  <div :class="['dashboard', themeClass]">
    <LoginModal
      :visible="showLoginModal"
      @success="handleLoginSuccess"
      @cancel="handleLoginCancel"
    />

    <header class="header">
      <h1 class="title">
        {{ systemTitle }}
        <span class="title-meta">库位 <span class="title-meta-value">{{ availableLocationsCount }}/{{ locations.length }}</span></span>
        <span class="title-fill-rate">
          <span
            class="title-meta title-fill-rate-item"
            @mouseenter="handleFillRateMouseEnter($event, overallFillRateDetail)"
            @mousemove="handleFillRateMouseMove"
            @mouseleave="handleFillRateMouseLeave"
          >
            库满度 <span class="title-meta-value">{{ overallFillRate }}</span>
          </span>
          <span
            :class="[
              'title-meta',
              'title-meta-a',
              'title-fill-rate-item',
              'title-fill-rate-toggle',
              { 'title-meta-inactive': !categoryColorVisibility.A }
            ]"
            @mouseenter="handleFillRateMouseEnter($event, categoryFillRateDetailMap.A)"
            @mousemove="handleFillRateMouseMove"
            @mouseleave="handleFillRateMouseLeave"
            @click="toggleCategoryColorVisibility('A')"
          >
            A <span class="title-meta-value">{{ categoryFillRateMap.A }}</span>
          </span>
          <span
            :class="[
              'title-meta',
              'title-meta-b',
              'title-fill-rate-item',
              'title-fill-rate-toggle',
              { 'title-meta-inactive': !categoryColorVisibility.B }
            ]"
            @mouseenter="handleFillRateMouseEnter($event, categoryFillRateDetailMap.B)"
            @mousemove="handleFillRateMouseMove"
            @mouseleave="handleFillRateMouseLeave"
            @click="toggleCategoryColorVisibility('B')"
          >
            B <span class="title-meta-value">{{ categoryFillRateMap.B }}</span>
          </span>
          <span
            :class="[
              'title-meta',
              'title-meta-c',
              'title-fill-rate-item',
              'title-fill-rate-toggle',
              { 'title-meta-inactive': !categoryColorVisibility.C }
            ]"
            @mouseenter="handleFillRateMouseEnter($event, categoryFillRateDetailMap.C)"
            @mousemove="handleFillRateMouseMove"
            @mouseleave="handleFillRateMouseLeave"
            @click="toggleCategoryColorVisibility('C')"
          >
            C <span class="title-meta-value">{{ categoryFillRateMap.C }}</span>
          </span>
        </span>
      </h1>
      <div class="controls">
        <label class="filter-item">
          <select
            v-model="selectedCategory"
            :class="['level-select', { 'level-select-placeholder': !selectedCategory }]"
          >
            <option value="">库位类型</option>
            <option
              v-for="category in categoryOptions"
              :key="category"
              :value="category"
            >
              {{ category }}
            </option>
          </select>
        </label>
        <label class="filter-item">
          <select
            v-model="selectedLocationAttribute"
            :class="['level-select', { 'level-select-placeholder': !selectedLocationAttribute }]"
          >
            <option value="">库位属性</option>
            <option
              v-for="attribute in locationAttributeOptions"
              :key="attribute"
              :value="attribute"
            >
              {{ getLocationAttributeLabel(attribute) }}
            </option>
          </select>
        </label>
        <label class="filter-item">
          <select
            v-model="selectedHasContainer"
            :class="['level-select', { 'level-select-placeholder': !selectedHasContainer }]"
          >
            <option value="">容器</option>
            <option value="Y">有容器</option>
            <option value="N">无容器</option>
          </select>
        </label>
        <label class="filter-item filter-input-item">
          <span class="filter-input-wrap">
            <input
              v-model="locGroupKeywordInput"
              class="filter-input"
              type="text"
              placeholder="库位组"
              @keydown.enter="applyLocGroupFilter"
            >
            <button
              v-if="locGroupKeywordInput"
              class="filter-clear-btn"
              type="button"
              @click="clearLocGroupFilter"
            >
              <svg
                viewBox="0 0 16 16"
                aria-hidden="true"
                class="filter-action-icon"
              >
                <path
                  d="M4.22 4.22a.75.75 0 0 1 1.06 0L8 6.94l2.72-2.72a.75.75 0 1 1 1.06 1.06L9.06 8l2.72 2.72a.75.75 0 1 1-1.06 1.06L8 9.06l-2.72 2.72a.75.75 0 1 1-1.06-1.06L6.94 8 4.22 5.28a.75.75 0 0 1 0-1.06z"
                  fill="currentColor"
                />
              </svg>
            </button>
            <button
              class="filter-confirm-btn"
              type="button"
              @click="applyLocGroupFilter"
            >
              <svg
                viewBox="0 0 16 16"
                aria-hidden="true"
                class="filter-action-icon"
              >
                <path
                  d="M6.5 2.5a4 4 0 1 0 2.47 7.15l2.69 2.68 1.06-1.06-2.68-2.69A4 4 0 0 0 6.5 2.5zm0 1.5a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5z"
                  fill="currentColor"
                />
              </svg>
            </button>
          </span>
        </label>
        <label class="filter-item filter-input-item">
          <span class="filter-input-wrap">
            <input
              v-model="locationIdKeywordInput"
              class="filter-input"
              type="text"
              placeholder="库位号"
              @keydown.enter="applyLocationIdFilter"
            >
            <button
              v-if="locationIdKeywordInput"
              class="filter-clear-btn"
              type="button"
              @click="clearLocationIdFilter"
            >
              <svg
                viewBox="0 0 16 16"
                aria-hidden="true"
                class="filter-action-icon"
              >
                <path
                  d="M4.22 4.22a.75.75 0 0 1 1.06 0L8 6.94l2.72-2.72a.75.75 0 1 1 1.06 1.06L9.06 8l2.72 2.72a.75.75 0 1 1-1.06 1.06L8 9.06l-2.72 2.72a.75.75 0 1 1-1.06-1.06L6.94 8 4.22 5.28a.75.75 0 0 1 0-1.06z"
                  fill="currentColor"
                />
              </svg>
            </button>
            <button
              class="filter-confirm-btn"
              type="button"
              @click="applyLocationIdFilter"
            >
              <svg
                viewBox="0 0 16 16"
                aria-hidden="true"
                class="filter-action-icon"
              >
                <path
                  d="M6.5 2.5a4 4 0 1 0 2.47 7.15l2.69 2.68 1.06-1.06-2.68-2.69A4 4 0 0 0 6.5 2.5zm0 1.5a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5z"
                  fill="currentColor"
                />
              </svg>
            </button>
          </span>
        </label>
        <label class="filter-item">
          <select
            v-model="selectedZoneId"
            :class="['level-select', { 'level-select-placeholder': !selectedZoneId }]"
          >
            <option value="">库区</option>
            <option
              v-for="zoneId in zoneOptions"
              :key="zoneId"
              :value="zoneId"
            >
              {{ zoneId }}
            </option>
          </select>
        </label>
        <select
          v-model.number="currentLevel"
          class="level-select level-select-floor"
          @change="handleLevelChange"
        >
          <option
            v-for="level in levelRange"
            :key="level"
            :value="level"
          >
            {{ level }}层
          </option>
        </select>
        <div
          ref="refreshControlRef"
          class="refresh-control"
        >
          <button
            class="refresh-btn"
            :disabled="loading || refreshing"
            @click="handleManualRefresh"
            @contextmenu.prevent="handleRefreshContextMenu"
          >
            {{ refreshCountdownText }}
          </button>
          <div
            v-if="showRefreshPopover"
            class="refresh-popover"
            @click.stop
          >
            <input
              ref="refreshIntervalInputRef"
              v-model="refreshIntervalInput"
              class="refresh-popover-input"
              type="text"
              inputmode="numeric"
              @keydown.enter="applyRefreshInterval"
            >
            <button
              class="refresh-popover-confirm"
              type="button"
              @click="applyRefreshInterval"
            >
              <svg
                viewBox="0 0 16 16"
                aria-hidden="true"
                class="filter-action-icon"
              >
                <path
                  d="M6.46 11.03 3.43 8a.75.75 0 1 1 1.06-1.06l1.97 1.96 5.05-5.04A.75.75 0 0 1 12.57 4.9l-5.58 5.59a.75.75 0 0 1-1.06 0z"
                  fill="currentColor"
                />
              </svg>
            </button>
          </div>
        </div>
        <div class="toggle-group">
          <label class="toggle-item">
            <span class="toggle-hint">组框</span>
            <input
              :checked="showGroupBorder"
              class="toggle-input"
              type="checkbox"
              @change="handleGroupBorderToggle"
            >
            <span class="toggle-track">
              <span class="toggle-thumb" />
            </span>
          </label>
          <label class="toggle-item">
            <span class="toggle-hint">卡片</span>
            <input
              v-model="showTooltip"
              class="toggle-input"
              type="checkbox"
            >
            <span class="toggle-track">
              <span class="toggle-thumb" />
            </span>
          </label>
          <label class="toggle-item theme-toggle">
            <span class="toggle-hint">主题</span>
            <input
              v-model="isLightTheme"
              class="toggle-input"
              type="checkbox"
            >
            <span class="toggle-track">
              <span class="toggle-thumb" />
            </span>
          </label>
        </div>
        <button
          class="logout-btn"
          @click="handleLogout"
        >
          退出
        </button>
      </div>
    </header>

    <div
      v-if="fillRateTooltipVisible && fillRateTooltipText"
      class="fill-rate-tooltip"
      :style="fillRateTooltipStyle"
    >
      <div class="fill-rate-tooltip-line">
        {{ fillRateTooltipText }}
      </div>
    </div>

    <main class="main-content">
      <div
        v-if="loading"
        class="loading"
      >
        加载中...
      </div>
      <div
        v-else-if="error"
        class="error"
      >
        {{ error }}
      </div>
      <div
        v-else
        class="map-container"
      >
        <WarehouseMap
          :locations="locations"
          :current-level="currentLevel"
          :selected-category="selectedCategory"
          :selected-location-attribute="selectedLocationAttribute"
          :selected-has-container="selectedHasContainer"
          :selected-zone-id="selectedZoneId"
          :loc-group-keyword="appliedLocGroupKeyword"
          :location-id-keyword="appliedLocationIdKeyword"
          :show-group-border="showGroupBorder"
          :show-tooltip="showTooltip"
          :category-color-visibility="categoryColorVisibility"
          :theme-mode="isLightTheme ? 'light' : 'dark'"
          @select-loc-group="handleSelectLocGroup"
          @select-location-id="handleSelectLocationId"
        />
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  onMounted,
  computed,
  onBeforeUnmount,
  nextTick,
  watchEffect,
  watch,
  type CSSProperties
} from 'vue'
import { fetchLocationData } from './api/location'
import type { LocationAttributeCode, LocationResourceDataVO } from './types'
import WarehouseMap from './components/WarehouseMap.vue'
import LoginModal from './components/LoginModal.vue'
import { config } from './config'
import { getApiEnvironment, isAuthenticated, removeToken } from './utils/auth'

const LEVEL_STORAGE_KEY = 'warehouse-map.current-level'
const REFRESH_INTERVAL_STORAGE_KEY = 'warehouse-map.refresh-interval-ms'
const getInitialLevel = () => {
  const savedLevel = window.localStorage.getItem(LEVEL_STORAGE_KEY)
  const parsedLevel = savedLevel ? Number(savedLevel) : NaN
  if (
    Number.isInteger(parsedLevel) &&
    parsedLevel >= config.minLevel &&
    parsedLevel <= config.maxLevel
  ) {
    return parsedLevel
  }
  return config.minLevel
}

const getInitialRefreshInterval = () => {
  const savedInterval = window.localStorage.getItem(REFRESH_INTERVAL_STORAGE_KEY)
  const parsedInterval = savedInterval ? Number(savedInterval) : NaN
  if (Number.isInteger(parsedInterval) && parsedInterval > 0) {
    return parsedInterval
  }
  return config.refreshInterval
}

const currentLevel = ref(getInitialLevel())
const locations = ref<LocationResourceDataVO[]>([])
const loading = ref(false)
const refreshing = ref(false)
const hasLoadedOnce = ref(false)
const error = ref('')
const showLoginModal = ref(false)
const THEME_STORAGE_KEY = 'warehouse-map.theme'

const getInitialTheme = () => {
  const saved = window.localStorage.getItem(THEME_STORAGE_KEY)
  if (saved === 'dark' || saved === 'light') {
    return saved
  }
  return 'light'
}

const isLightTheme = ref(getInitialTheme() === 'light')
const selectedCategory = ref('')
const selectedLocationAttribute = ref<LocationAttributeCode | ''>('')
const selectedHasContainer = ref<'Y' | 'N' | ''>('')
const selectedZoneId = ref('')
const categoryColorVisibility = ref<Record<'A' | 'B' | 'C', boolean>>({
  A: true,
  B: true,
  C: true
})
const locGroupKeywordInput = ref('')
const appliedLocGroupKeyword = ref('')
const locationIdKeywordInput = ref('')
const appliedLocationIdKeyword = ref('')
const showGroupBorder = ref(false)
const showTooltip = ref(true)
const refreshIntervalMs = ref(getInitialRefreshInterval())
const showRefreshPopover = ref(false)
const refreshIntervalInput = ref(String(Math.max(Math.floor(refreshIntervalMs.value / 1000), 1)))
const now = ref(Date.now())
const nextRefreshAt = ref(Date.now() + refreshIntervalMs.value)
const refreshControlRef = ref<HTMLElement | null>(null)
const refreshIntervalInputRef = ref<HTMLInputElement | null>(null)
const fillRateTooltipVisible = ref(false)
const fillRateTooltipText = ref('')
const fillRateTooltipPosition = ref({
  x: 0,
  y: 0
})
let refreshTimer: number | null = null
let countdownTimer: number | null = null

const LOCATION_ATTRIBUTE_LABEL_MAP: Record<LocationAttributeCode, string> = {
  OK: '正常',
  FI: '禁入',
  HD: '封存',
  SC: '管控'
}

const themeClass = computed(() => (isLightTheme.value ? 'theme-light' : 'theme-dark'))

const levelRange = computed(() => {
  const levels = []
  for (let i = config.minLevel; i <= config.maxLevel; i++) {
    levels.push(i)
  }
  return levels
})

const currentEnvironment = ref(getApiEnvironment())

const systemTitle = computed(() => {
  return currentEnvironment.value === 'prod' ? '宝时立库生产' : '宝时立库测试'
})

const categoryOptions = computed(() => {
  return [...new Set(locations.value.map((loc) => loc.category).filter(Boolean))].sort()
})

const hasContainer = (containerCode: string | null) => {
  return Boolean(containerCode && containerCode.trim())
}

const formatFillRate = (total: number, occupied: number) => {
  if (total <= 0) {
    return '0.0%'
  }
  return `${((occupied / total) * 100).toFixed(1)}%`
}

const formatFillRateDetail = (occupied: number, total: number) => {
  return `${occupied}/${total}`
}

const availableLocationsCount = computed(() => {
  return locations.value.filter((loc) => loc.locationAttribute === 'OK').length
})

const overallFillRate = computed(() => {
  const occupiedCount = locations.value.filter((loc) => hasContainer(loc.containerCode)).length
  return formatFillRate(locations.value.length, occupiedCount)
})

const overallFillRateDetail = computed(() => {
  const occupiedCount = locations.value.filter((loc) => hasContainer(loc.containerCode)).length
  return formatFillRateDetail(occupiedCount, locations.value.length)
})

const categoryFillRateMap = computed<Record<'A' | 'B' | 'C', string>>(() => {
  const categories: Array<'A' | 'B' | 'C'> = ['A', 'B', 'C']
  return categories.reduce(
    (result, category) => {
      const categoryLocations = locations.value.filter((loc) => loc.category === category)
      const occupiedCount = categoryLocations.filter((loc) =>
        hasContainer(loc.containerCode)
      ).length
      result[category] = formatFillRate(categoryLocations.length, occupiedCount)
      return result
    },
    {
      A: '0.0%',
      B: '0.0%',
      C: '0.0%'
    }
  )
})

const categoryFillRateDetailMap = computed<Record<'A' | 'B' | 'C', string>>(() => {
  const categories: Array<'A' | 'B' | 'C'> = ['A', 'B', 'C']
  return categories.reduce(
    (result, category) => {
      const categoryLocations = locations.value.filter((loc) => loc.category === category)
      const occupiedCount = categoryLocations.filter((loc) =>
        hasContainer(loc.containerCode)
      ).length
      result[category] = formatFillRateDetail(occupiedCount, categoryLocations.length)
      return result
    },
    {
      A: '0/0',
      B: '0/0',
      C: '0/0'
    }
  )
})

const fillRateTooltipStyle = computed<CSSProperties>(() => ({
  left: `${fillRateTooltipPosition.value.x}px`,
  top: `${fillRateTooltipPosition.value.y}px`
}))

const locationAttributeOptions = computed<LocationAttributeCode[]>(() => {
  return [
    ...new Set(locations.value.map((loc) => loc.locationAttribute).filter(Boolean))
  ] as LocationAttributeCode[]
})

const zoneOptions = computed(() => {
  return [...new Set(locations.value.map((loc) => loc.zoneId).filter(Boolean))].sort()
})

const getLocationAttributeLabel = (attribute: LocationAttributeCode) => {
  return LOCATION_ATTRIBUTE_LABEL_MAP[attribute] || attribute
}

const toggleCategoryColorVisibility = (category: 'A' | 'B' | 'C') => {
  categoryColorVisibility.value = {
    ...categoryColorVisibility.value,
    [category]: !categoryColorVisibility.value[category]
  }
}

const updateFillRateTooltipPosition = (event: MouseEvent) => {
  const tooltipWidth = 120
  const tooltipHeight = 42
  const offset = 14
  const maxX = window.innerWidth - tooltipWidth - 12
  const maxY = window.innerHeight - tooltipHeight - 12

  fillRateTooltipPosition.value = {
    x: Math.max(12, Math.min(event.clientX + offset, maxX)),
    y: Math.max(12, Math.min(event.clientY + offset, maxY))
  }
}

const handleFillRateMouseEnter = (event: MouseEvent, text: string) => {
  fillRateTooltipText.value = text
  fillRateTooltipVisible.value = true
  updateFillRateTooltipPosition(event)
}

const handleFillRateMouseMove = (event: MouseEvent) => {
  if (!fillRateTooltipVisible.value) {
    return
  }
  updateFillRateTooltipPosition(event)
}

const handleFillRateMouseLeave = () => {
  fillRateTooltipVisible.value = false
  fillRateTooltipText.value = ''
}

const copyText = async (text: string) => {
  if (!text) return

  try {
    await navigator.clipboard.writeText(text)
    return
  } catch (error) {
    console.warn('Clipboard API copy failed, fallback to execCommand.', error)
  }

  const textarea = document.createElement('textarea')
  textarea.value = text
  textarea.setAttribute('readonly', 'true')
  textarea.style.position = 'fixed'
  textarea.style.top = '-9999px'
  document.body.appendChild(textarea)
  textarea.select()
  document.execCommand('copy')
  document.body.removeChild(textarea)
}

const applyLocGroupFilter = () => {
  appliedLocGroupKeyword.value = locGroupKeywordInput.value.trim()
}

const applyLocationIdFilter = () => {
  appliedLocationIdKeyword.value = locationIdKeywordInput.value.trim()
}

const clearLocGroupFilter = () => {
  locGroupKeywordInput.value = ''
  appliedLocGroupKeyword.value = ''
}

const clearLocationIdFilter = () => {
  locationIdKeywordInput.value = ''
  appliedLocationIdKeyword.value = ''
}

const handleGroupBorderToggle = (event: Event) => {
  showGroupBorder.value = (event.target as HTMLInputElement).checked
}

const refreshCountdownText = computed(() => {
  const remainMs = Math.max(nextRefreshAt.value - now.value, 0)
  const totalSeconds = Math.floor(remainMs / 1000)
  const minutes = Math.floor(totalSeconds / 60)
  const seconds = totalSeconds % 60
  return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
})

const loadLocationData = async (options: { silent?: boolean } = {}) => {
  const { silent = false } = options
  if (!isAuthenticated()) {
    showLoginModal.value = true
    return
  }

  const shouldUseSilentRefresh = silent && hasLoadedOnce.value
  if (shouldUseSilentRefresh) {
    refreshing.value = true
  } else {
    loading.value = true
    error.value = ''
  }

  try {
    const data = await fetchLocationData({
      warehouse: config.warehouse,
      locLevel: currentLevel.value
    })
    locations.value = data
    hasLoadedOnce.value = true
  } catch (err: unknown) {
    if (!shouldUseSilentRefresh) {
      error.value = err instanceof Error ? err.message : '加载数据失败，请检查接口连接'
    }
    console.error('Failed to load location data:', err)
  } finally {
    if (shouldUseSilentRefresh) {
      refreshing.value = false
    } else {
      loading.value = false
    }
  }
}

const scheduleNextRefresh = () => {
  if (refreshTimer !== null) {
    window.clearTimeout(refreshTimer)
  }
  nextRefreshAt.value = Date.now() + refreshIntervalMs.value
  refreshTimer = window.setTimeout(async () => {
    await loadLocationData({ silent: true })
    scheduleNextRefresh()
  }, refreshIntervalMs.value)
}

const handleLevelChange = () => {
  window.localStorage.setItem(LEVEL_STORAGE_KEY, String(currentLevel.value))
  loadLocationData()
  scheduleNextRefresh()
}

const handleManualRefresh = () => {
  loadLocationData({ silent: true })
  scheduleNextRefresh()
}

const applyRefreshInterval = () => {
  const nextSeconds = Number(refreshIntervalInput.value.trim())
  if (!Number.isInteger(nextSeconds) || nextSeconds <= 0) {
    return
  }

  refreshIntervalMs.value = nextSeconds * 1000
  refreshIntervalInput.value = String(nextSeconds)
  window.localStorage.setItem(REFRESH_INTERVAL_STORAGE_KEY, String(refreshIntervalMs.value))
  showRefreshPopover.value = false
  scheduleNextRefresh()
}

const handleRefreshContextMenu = async () => {
  refreshIntervalInput.value = String(Math.max(Math.floor(refreshIntervalMs.value / 1000), 1))
  showRefreshPopover.value = true
  await nextTick()
  refreshIntervalInputRef.value?.focus()
  refreshIntervalInputRef.value?.select()
}

const handleDocumentClick = (event: MouseEvent) => {
  if (!showRefreshPopover.value) {
    return
  }

  const target = event.target as Node | null
  if (target && refreshControlRef.value?.contains(target)) {
    return
  }

  showRefreshPopover.value = false
}

const handleLoginSuccess = () => {
  currentEnvironment.value = getApiEnvironment()
  showLoginModal.value = false
  loadLocationData()
  scheduleNextRefresh()
}

const handleSelectLocGroup = async (locGroup1: string) => {
  await copyText(locGroup1)
  if (appliedLocGroupKeyword.value === locGroup1) {
    locGroupKeywordInput.value = ''
    appliedLocGroupKeyword.value = ''
    return
  }

  locGroupKeywordInput.value = locGroup1
  appliedLocGroupKeyword.value = locGroup1
  locationIdKeywordInput.value = ''
  appliedLocationIdKeyword.value = ''
}

const handleSelectLocationId = async (locationId: string) => {
  await copyText(locationId)
  if (appliedLocationIdKeyword.value === locationId) {
    locationIdKeywordInput.value = ''
    appliedLocationIdKeyword.value = ''
    return
  }

  locationIdKeywordInput.value = locationId
  appliedLocationIdKeyword.value = locationId
  locGroupKeywordInput.value = ''
  appliedLocGroupKeyword.value = ''
}

const handleLoginCancel = () => {
  // 不允许取消登录，必须登录才能使用
}

const handleLogout = () => {
  if (refreshTimer !== null) {
    window.clearTimeout(refreshTimer)
    refreshTimer = null
  }
  removeToken()
  locations.value = []
  hasLoadedOnce.value = false
  loading.value = false
  refreshing.value = false
  showLoginModal.value = true
}

onMounted(() => {
  countdownTimer = window.setInterval(() => {
    now.value = Date.now()
  }, 1000)
  document.addEventListener('mousedown', handleDocumentClick)

  if (!isAuthenticated()) {
    showLoginModal.value = true
  } else {
    loadLocationData()
    scheduleNextRefresh()
  }
})

watchEffect(() => {
  document.title = systemTitle.value
})

watch(isLightTheme, (isLight) => {
  window.localStorage.setItem(THEME_STORAGE_KEY, isLight ? 'light' : 'dark')
})

onBeforeUnmount(() => {
  if (refreshTimer !== null) {
    window.clearTimeout(refreshTimer)
  }
  if (countdownTimer !== null) {
    window.clearInterval(countdownTimer)
  }
  document.removeEventListener('mousedown', handleDocumentClick)
})
</script>

<style scoped>
.dashboard {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--bg);
  color: var(--text);
  --bg: #000000;
  --header-bg: linear-gradient(180deg, #050505 0%, #000000 100%);
  --header-border: #1c1c1c;
  --text: #f2f2f2;
  --text-muted: rgba(255, 255, 255, 0.6);
  --text-dim: #d8d8d8;
  --label-text: #8e8e8e;
  --rate-a: rgba(201, 242, 215, 0.88);
  --rate-b: rgba(203, 220, 255, 0.9);
  --rate-c: rgba(240, 220, 156, 0.9);
  --rate-inactive: var(--text-muted);
  --panel-bg: rgba(0, 0, 0, 0.96);
  --panel-border: #1f1f1f;
  --panel-shadow: 0 12px 28px rgba(0, 0, 0, 0.32);
  --input-bg: rgba(255, 255, 255, 0.03);
  --input-border: #252525;
  --input-text: #f2f2f2;
  --input-placeholder: rgba(255, 255, 255, 0.28);
  --input-hover-bg: rgba(255, 255, 255, 0.05);
  --input-hover-border: #3a3a3a;
  --icon-border: #202020;
  --toggle-track-bg: #111111;
  --toggle-track-border: #2c2c2c;
  --toggle-thumb-bg: #f2f2f2;
  --toggle-track-checked-bg: #2b2b2b;
  --toggle-track-checked-border: #5a5a5a;
  --refresh-bg: #101010;
  --refresh-border: #282828;
  --refresh-text: #e8e8e8;
  --refresh-hover-bg: #181818;
  --refresh-hover-border: #3a3a3a;
  --popover-bg: rgba(4, 4, 4, 0.98);
  --popover-border: #242424;
  --btn-neutral-bg: rgba(255, 255, 255, 0.03);
  --btn-neutral-border: #252525;
  --btn-neutral-text: #cfcfcf;
  --btn-neutral-hover-bg: rgba(255, 255, 255, 0.06);
  --btn-neutral-hover-border: #3a3a3a;
  --danger-bg: rgba(210, 92, 92, 0.08);
  --danger-border: rgba(210, 92, 92, 0.45);
  --danger-text: #f2bcbc;
  --danger-hover-bg: rgba(210, 92, 92, 0.16);
  --danger-hover-border: rgba(210, 92, 92, 0.7);
  --danger-hover-text: #ffd4d4;
  --error-text: #ff4444;
  --select-arrow: #6d6d6d;
}

.dashboard.theme-light {
  --bg: #f6f7f9;
  --header-bg: linear-gradient(180deg, #ffffff 0%, #f0f2f5 100%);
  --header-border: #d9dee6;
  --text: #1f1f1f;
  --text-muted: rgba(0, 0, 0, 0.55);
  --text-dim: #3f3f3f;
  --label-text: #5f6368;
  --rate-a: #1f7a3f;
  --rate-b: #2f5fd7;
  --rate-c: #b8921f;
  --rate-inactive: var(--label-text);
  --panel-bg: rgba(255, 255, 255, 0.96);
  --panel-border: #d7dce3;
  --panel-shadow: 0 12px 24px rgba(31, 35, 40, 0.12);
  --input-bg: #ffffff;
  --input-border: #cfd6df;
  --input-text: #1f1f1f;
  --input-placeholder: rgba(0, 0, 0, 0.35);
  --input-hover-bg: #f7f9fb;
  --input-hover-border: #aeb7c2;
  --icon-border: #cfd6df;
  --toggle-track-bg: #e4e7ec;
  --toggle-track-border: #c6ccd5;
  --toggle-thumb-bg: #ffffff;
  --toggle-track-checked-bg: #cfd6df;
  --toggle-track-checked-border: #aeb7c2;
  --refresh-bg: #ffffff;
  --refresh-border: #cfd6df;
  --refresh-text: #2a2f36;
  --refresh-hover-bg: #f1f4f8;
  --refresh-hover-border: #aeb7c2;
  --popover-bg: #ffffff;
  --popover-border: #d7dce3;
  --btn-neutral-bg: #ffffff;
  --btn-neutral-border: #cfd6df;
  --btn-neutral-text: #2a2f36;
  --btn-neutral-hover-bg: #f1f4f8;
  --btn-neutral-hover-border: #aeb7c2;
  --danger-bg: rgba(210, 92, 92, 0.1);
  --danger-border: rgba(210, 92, 92, 0.45);
  --danger-text: #a83b3b;
  --danger-hover-bg: rgba(210, 92, 92, 0.16);
  --danger-hover-border: rgba(210, 92, 92, 0.7);
  --danger-hover-text: #8f2f2f;
  --error-text: #c73939;
  --select-arrow: #6b7280;
}

.header {
  padding: 10px 18px;
  background: var(--header-bg);
  border-bottom: 1px solid var(--header-border);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  display: flex;
  align-items: baseline;
  gap: 6px;
  font-size: 18px;
  font-weight: bold;
  line-height: 1.1;
  color: var(--text);
  text-shadow: 0 0 8px rgba(255, 255, 255, 0.08);
}

.title-meta {
  font-size: 11px;
  font-weight: normal;
  color: var(--text-muted);
}

.title-meta-value {
  font-weight: 700;
}

.title-legend {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  margin-left: 2px;
}

.title-fill-rate {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  margin-left: 2px;
}

.title-fill-rate-item {
  cursor: help;
}

.fill-rate-tooltip {
  position: fixed;
  z-index: 1000;
  max-width: 160px;
  padding: 10px 12px;
  border: 1px solid var(--panel-border);
  border-radius: 8px;
  background: var(--panel-bg);
  box-shadow: var(--panel-shadow);
  color: var(--text);
  font-size: 12px;
  line-height: 1.45;
  pointer-events: none;
  backdrop-filter: blur(6px);
}

.fill-rate-tooltip-line + .fill-rate-tooltip-line {
  margin-top: 3px;
}

.title-meta-a,
.title-meta-b,
.title-meta-c {
  color: var(--text-muted);
}

.title-meta-a {
  color: var(--rate-a);
}

.title-meta-b {
  color: var(--rate-b);
}

.title-meta-c {
  color: var(--rate-c);
}

.title-meta-inactive {
  color: var(--rate-inactive);
}

.legend-chip {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 18px;
  height: 14px;
  padding: 0 4px;
  border-radius: 999px;
  font-size: 9px;
  font-weight: 600;
  line-height: 1;
  color: #f4f7fa;
  border: none;
  cursor: pointer;
  transition:
    transform 0.2s ease,
    opacity 0.2s ease,
    box-shadow 0.2s ease;
}

.legend-chip:hover {
  transform: translateY(-1px);
  box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.14);
}

.legend-chip-inactive {
  opacity: 0.42;
  box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.18);
}

.legend-chip-a {
  background: #1f7a3f;
  color: #f3fff7;
}

.legend-chip-b {
  background: #2f5fd7;
  color: #f5f8ff;
}

.legend-chip-c {
  background: #b8921f;
  color: #161200;
}

.controls {
  display: flex;
  align-items: center;
  gap: 6px;
  flex-wrap: wrap;
  row-gap: 6px;
}

.level-selector {
  display: flex;
  align-items: center;
  gap: 6px;
  color: var(--text-dim);
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: var(--text-dim);
}

.filter-input-item {
  min-width: auto;
}

.toggle-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: var(--text-dim);
}

.toggle-group {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  flex-wrap: nowrap;
}

.selector-label {
  font-size: 11px;
  color: var(--label-text);
}

.toggle-hint {
  font-size: 11px;
  color: var(--label-text);
  white-space: nowrap;
}

.level-select {
  min-width: 76px;
  padding: 6px 24px 6px 8px;
  background: var(--input-bg);
  border: 1px solid var(--input-border);
  color: var(--input-text);
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s;
  border-radius: 4px;
  outline: none;
  appearance: none;
  background-image:
    linear-gradient(45deg, transparent 50%, var(--select-arrow) 50%),
    linear-gradient(135deg, var(--select-arrow) 50%, transparent 50%);
  background-position:
    calc(100% - 13px) calc(50% - 2px),
    calc(100% - 8px) calc(50% - 2px);
  background-size:
    5px 5px,
    5px 5px;
  background-repeat: no-repeat;
  line-height: 1;
}

.level-select-placeholder {
  color: var(--label-text);
}

.level-select-floor {
  min-width: 64px;
}

.filter-input-wrap {
  position: relative;
  display: inline-flex;
  width: 115px;
}

.filter-input {
  width: 100%;
  padding: 6px 8px;
  padding-right: 50px;
  background: var(--input-bg);
  border: 1px solid var(--input-border);
  color: var(--input-text);
  font-size: 12px;
  border-radius: 4px;
  outline: none;
  line-height: 1;
}

.filter-input::placeholder {
  color: var(--input-placeholder);
}

.filter-input:hover,
.filter-input:focus {
  background: var(--input-hover-bg);
  border-color: var(--input-hover-border);
}

.filter-confirm-btn {
  position: absolute;
  top: 1px;
  right: 1px;
  width: 24px;
  height: calc(100% - 2px);
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border: none;
  border-left: 1px solid var(--icon-border);
  background: transparent;
  color: var(--btn-neutral-text);
  cursor: pointer;
  border-radius: 0 3px 3px 0;
}

.filter-clear-btn {
  position: absolute;
  top: 1px;
  right: 25px;
  width: 24px;
  height: calc(100% - 2px);
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border: none;
  border-left: 1px solid var(--icon-border);
  background: transparent;
  color: var(--btn-neutral-text);
  cursor: pointer;
}

.filter-clear-btn:hover,
.filter-confirm-btn:hover {
  background: var(--btn-neutral-hover-bg);
}

.filter-action-icon {
  width: 12px;
  height: 12px;
}

.toggle-input {
  position: absolute;
  opacity: 0;
  pointer-events: none;
}

.toggle-track {
  position: relative;
  width: 34px;
  height: 18px;
  border-radius: 999px;
  background: var(--toggle-track-bg);
  border: 1px solid var(--toggle-track-border);
  transition: all 0.2s;
  cursor: pointer;
}

.toggle-thumb {
  position: absolute;
  top: 1px;
  left: 1px;
  width: 14px;
  height: 14px;
  border-radius: 50%;
  background: var(--toggle-thumb-bg);
  transition: transform 0.2s;
}

.toggle-input:checked + .toggle-track {
  background: var(--toggle-track-checked-bg);
  border-color: var(--toggle-track-checked-border);
}

.toggle-input:checked + .toggle-track .toggle-thumb {
  transform: translateX(16px);
}


.level-select:hover,
.level-select:focus {
  background: var(--input-hover-bg);
  border-color: var(--input-hover-border);
}

.refresh-btn {
  min-width: 58px;
  padding: 6px 8px;
  background: var(--refresh-bg);
  border: 1px solid var(--refresh-border);
  color: var(--refresh-text);
  cursor: pointer;
  font-size: 11px;
  transition: all 0.3s;
  border-radius: 4px;
  line-height: 1;
}

.refresh-control {
  position: relative;
}

.refresh-popover {
  position: absolute;
  top: calc(100% + 6px);
  right: 0;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px;
  background: var(--popover-bg);
  border: 1px solid var(--popover-border);
  border-radius: 4px;
  box-shadow: var(--panel-shadow);
  z-index: 20;
}

.refresh-popover-input {
  width: 56px;
  padding: 6px 8px;
  background: var(--input-bg);
  border: 1px solid var(--input-border);
  color: var(--input-text);
  font-size: 12px;
  border-radius: 4px;
  outline: none;
  line-height: 1;
}

.refresh-popover-input:focus {
  background: var(--input-hover-bg);
  border-color: var(--input-hover-border);
}

.refresh-popover-confirm {
  width: 24px;
  height: 28px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border: 1px solid var(--btn-neutral-border);
  background: var(--btn-neutral-bg);
  color: var(--btn-neutral-text);
  border-radius: 4px;
  cursor: pointer;
}

.refresh-popover-confirm:hover {
  background: var(--btn-neutral-hover-bg);
  border-color: var(--btn-neutral-hover-border);
}

.refresh-btn:hover:not(:disabled) {
  background: var(--refresh-hover-bg);
  border-color: var(--refresh-hover-border);
}

.refresh-btn:disabled {
  opacity: 0.7;
  cursor: wait;
}

.logout-btn {
  padding: 6px 10px;
  background: var(--danger-bg);
  border: 1px solid var(--danger-border);
  color: var(--danger-text);
  cursor: pointer;
  font-size: 11px;
  transition: all 0.3s;
  border-radius: 4px;
  line-height: 1;
}

.logout-btn:hover {
  background: var(--danger-hover-bg);
  border-color: var(--danger-hover-border);
  color: var(--danger-hover-text);
}

.main-content {
  flex: 1;
  padding: 0 12px 12px;
  overflow: auto;
  background: var(--bg);
}

.loading,
.error {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  font-size: 18px;
  color: var(--text);
}

.error {
  color: var(--error-text);
}

.map-container {
  width: 100%;
  height: 100%;
}
</style>
