<template>
  <header class="topbar" :class="{ 'chat-mode': isChat, 'detail-mode': isRequestDetail }">
    <div v-if="!isWorkbenchAiHome" class="title-group">
      <div class="eyebrow">{{ eyebrowLabel }}</div>
      <h1>{{ currentView.title }}</h1>
      <p>{{ currentView.desc }}</p>
    </div>
    <div v-else class="title-group" aria-hidden="true"></div>

    <div class="top-actions">
      <template v-if="isChat">
        <div class="kpi-chips">
          <div v-for="kpi in chatKpis" :key="kpi.label" class="kpi-chip" :style="{ '--chip-color': kpi.color }">
            <span class="chip-value">{{ kpi.value }}<small>{{ kpi.unit }}</small></span>
            <span class="chip-label">{{ kpi.label }}</span>
            <span class="chip-delta" :class="kpi.trend">{{ kpi.meta }}</span>
          </div>
        </div>
      </template>

      <template v-else-if="isOverview">
        <div class="range-combo" aria-label="首页时间范围">
          <div class="range-shell">
            <span class="range-meta">
              <i class="mdi mdi-calendar"></i>
              <span>{{ activeDateLabel }}</span>
            </span>

            <div class="range-tabs" role="tablist" aria-label="时间范围">
              <button
                v-for="option in rangeOptions"
                :key="option.value"
                type="button"
                role="tab"
                :aria-selected="activeRange === option.value"
                :class="{ active: activeRange === option.value }"
                @click="setRange(option.value)"
              >
                {{ option.label }}
              </button>
            </div>
          </div>

          <div class="custom-range-wrap">
            <button
              class="custom-range-btn"
              type="button"
              :class="{ active: isCustomRange }"
              :aria-expanded="calendarOpen"
              aria-haspopup="dialog"
              @click="calendarOpen = !calendarOpen"
            >
              <i class="mdi mdi-calendar-plus"></i>
              <span>选择时间段</span>
            </button>

            <div v-if="calendarOpen" class="calendar-popover" role="dialog" aria-label="选择看板时间段">
              <header>
                <strong>选择看板时间段</strong>
                <button type="button" aria-label="关闭日期选择" @click="calendarOpen = false">
                  <i class="mdi mdi-close"></i>
                </button>
              </header>

              <div class="date-fields">
                <label>
                  <span>开始日期</span>
                  <input v-model="draftStart" type="date" />
                </label>
                <label>
                  <span>结束日期</span>
                  <input v-model="draftEnd" type="date" />
                </label>
              </div>

              <footer>
                <button class="ghost-btn" type="button" @click="calendarOpen = false">取消</button>
                <button class="apply-btn" type="button" :disabled="!canApplyCustomRange" @click="applyCustomRange">
                  应用
                </button>
              </footer>
            </div>
          </div>

          <div class="dashboard-switch-wrap">
            <EnterpriseSelect
              v-model="overviewDashboardValue"
              class="dashboard-switch-select"
              :options="overviewDashboardOptions"
              aria-label="选择看板类型"
              size="default"
            />
          </div>
        </div>
      </template>

      <template v-else-if="isRequestDetail">
        <div class="detail-topbar-actions">
          <div v-if="detailKpis.length" class="kpi-chips detail-kpi-chips">
            <div
              v-for="kpi in detailKpis"
              :key="kpi.label"
              class="kpi-chip detail-kpi-chip"
              :style="{ '--chip-color': kpi.color }"
            >
              <span class="chip-value">{{ kpi.value }}<small>{{ kpi.unit }}</small></span>
              <span class="chip-label">{{ kpi.label }}</span>
              <span class="chip-delta" :class="kpi.trend">{{ kpi.meta }}</span>
            </div>
          </div>
          <div v-if="detailAlerts.length" class="detail-alert-strip">
            <span
              v-for="alert in detailAlerts"
              :key="alert.label"
              class="detail-alert-pill"
              :class="alert.tone"
            >
              <i :class="alert.icon || 'mdi mdi-alert-circle-outline'"></i>
              <span>{{ alert.label }}</span>
            </span>
          </div>
        </div>
      </template>

      <template v-else-if="isWorkbench">
        <div class="topbar-toolset" aria-label="工作台快捷工具">
          <div ref="notificationWrapRef" class="notification-wrap" :class="{ 'is-open': notificationOpen }">
            <button
              class="topbar-icon-btn notification-btn"
              type="button"
              aria-label="通知"
              :aria-expanded="notificationOpen"
              aria-haspopup="dialog"
              @click="toggleNotification"
            >
              <i class="mdi mdi-bell-outline"></i>
              <span v-if="topbarNotificationCount" class="notification-badge">{{ topbarNotificationCount }}</span>
            </button>

            <Transition name="notification-panel">
              <div v-if="notificationOpen" class="notification-popover" role="dialog" aria-label="通知中心">
                <header class="notification-head">
                  <div class="notification-head-brand">
                    <span class="notification-head-icon" aria-hidden="true">
                      <i class="mdi mdi-bell-ring-outline"></i>
                    </span>
                    <span class="notification-head-copy">
                      <strong>通知中心</strong>
                      <small>{{ unreadNotifications.length ? `${unreadNotifications.length} 条待处理` : '暂无待处理通知' }}</small>
                    </span>
                  </div>
                  <span class="notification-head-actions">
                    <button
                      class="notification-clear-btn"
                      type="button"
                      :disabled="notificationBulkActionDisabled"
                      @click="handleNotificationBulkAction"
                    >
                      {{ notificationBulkActionLabel }}
                    </button>
                    <button
                      class="notification-close-btn"
                      type="button"
                      aria-label="关闭通知"
                      @click="closeNotification"
                    >
                      <i class="mdi mdi-close"></i>
                    </button>
                  </span>
                </header>

                <div class="notification-tabs" role="tablist" aria-label="通知状态">
                  <button
                    type="button"
                    role="tab"
                    :aria-selected="notificationTab === 'unread'"
                    :class="{ active: notificationTab === 'unread' }"
                    @click="notificationTab = 'unread'"
                  >
                    <span>未读</span>
                    <em>{{ unreadNotifications.length }}</em>
                  </button>
                  <button
                    type="button"
                    role="tab"
                    :aria-selected="notificationTab === 'read'"
                    :class="{ active: notificationTab === 'read' }"
                    @click="notificationTab = 'read'"
                  >
                    <span>已读</span>
                    <em>{{ readNotifications.length }}</em>
                  </button>
                </div>

                <div v-if="activeNotifications.length" class="notification-list">
                  <button
                    v-for="item in activeNotifications"
                    :key="item.id"
                    type="button"
                    class="notification-row"
                    :class="{ unread: item.unread }"
                    @click="openNotification(item)"
                  >
                    <span class="notification-avatar" :class="item.tone" aria-hidden="true">
                      <span class="notification-avatar-label">{{ item.avatarLabel }}</span>
                      <span v-if="item.badge" class="notification-avatar-badge">{{ item.badge }}</span>
                    </span>
                    <span class="notification-row-content">
                      <span class="notification-row-top">
                        <strong class="notification-row-title">{{ item.title }}</strong>
                        <time class="notification-time">{{ item.timeLabel || item.time }}</time>
                      </span>
                      <small class="notification-preview">{{ item.description }}</small>
                    </span>
                  </button>
                </div>
                <div v-else class="notification-empty">
                  <span class="notification-empty-icon" aria-hidden="true">
                    <i class="mdi mdi-bell-check-outline"></i>
                  </span>
                  <strong>{{ notificationTab === 'unread' ? '暂无未读通知' : '暂无已读通知' }}</strong>
                  <span>新的单据与待办会在这里汇总展示</span>
                </div>
              </div>
            </Transition>
          </div>

          <div ref="helpWrapRef" class="help-wrap" :class="{ 'is-open': helpOpen }">
            <button
              class="topbar-icon-btn help-btn"
              type="button"
              aria-label="帮助"
              :aria-expanded="helpOpen"
              aria-haspopup="dialog"
              @click="toggleHelp"
            >
              <i class="mdi mdi-help-circle-outline"></i>
            </button>

            <Transition name="help-panel">
              <div v-if="helpOpen" class="help-popover" role="dialog" aria-label="产品信息">
                <header class="help-head">
                  <span class="help-head-icon" aria-hidden="true">
                    <i class="mdi mdi-information-outline"></i>
                  </span>
                  <span class="help-head-copy">
                    <strong>{{ topbarHelpDemo.productName }}</strong>
                    <small>产品版本与版权信息</small>
                  </span>
                  <button
                    class="help-close-btn"
                    type="button"
                    aria-label="关闭帮助"
                    @click="closeHelp"
                  >
                    <i class="mdi mdi-close"></i>
                  </button>
                </header>

                <dl class="help-meta">
                  <div class="help-meta-row">
                    <dt>版本号</dt>
                    <dd>{{ topbarHelpDemo.version }}</dd>
                  </div>
                  <div class="help-meta-row">
                    <dt>更新时间</dt>
                    <dd>{{ topbarHelpDemo.updatedAt }}</dd>
                  </div>
                  <div class="help-meta-row help-meta-row--block">
                    <dt>Copyright</dt>
                    <dd>{{ topbarHelpDemo.copyright }}</dd>
                  </div>
                </dl>
              </div>
            </Transition>
          </div>

          <button class="company-switcher" type="button" aria-label="切换公司">
            <span>{{ displayCompanyName }}</span>
            <i class="mdi mdi-chevron-down"></i>
          </button>
          <button
            type="button"
            class="topbar-ai-mode-toggle"
            :class="{ active: isTopbarAiMode }"
            :aria-pressed="isTopbarAiMode"
            :aria-label="topbarWorkbenchModeTitle"
            :title="topbarWorkbenchModeTitle"
            @click="toggleTopbarWorkbenchMode"
          >
            <span class="topbar-ai-mode-toggle__glyph">AI</span>
          </button>
        </div>
      </template>

      <template v-else-if="isDocuments">
        <div class="kpi-chips">
          <div v-for="kpi in documentKpis" :key="kpi.label" class="kpi-chip" :style="{ '--chip-color': kpi.color }">
            <span class="chip-value">{{ kpi.value }}<small>单</small></span>
            <span class="chip-label">{{ kpi.label }}</span>
            <span class="chip-delta" :class="kpi.trend">{{ kpi.delta }} <i :class="kpi.arrow"></i></span>
          </div>
        </div>
      </template>

      <template v-else-if="isRequests">
        <div class="kpi-chips">
          <div v-for="kpi in requestKpis" :key="kpi.label" class="kpi-chip" :style="{ '--chip-color': kpi.color }">
            <span class="chip-value">{{ kpi.value }}<small>单</small></span>
            <span class="chip-label">{{ kpi.label }}</span>
            <span class="chip-delta" :class="kpi.trend">{{ kpi.delta }} <i :class="kpi.arrow"></i></span>
          </div>
        </div>
      </template>

      <template v-else-if="showDigitalEmployeeWorkRecordKpis">
        <div class="kpi-chips">
          <div
            v-for="kpi in digitalEmployeeWorkRecordKpis"
            :key="kpi.label"
            class="kpi-chip"
            :style="{ '--chip-color': kpi.color }"
          >
            <span class="chip-value">{{ kpi.value }}<small>条</small></span>
            <span class="chip-label">{{ kpi.label }}</span>
            <span class="chip-delta" :class="kpi.trend">{{ kpi.delta }} <i :class="kpi.arrow"></i></span>
          </div>
        </div>
      </template>

      <template v-else-if="isPolicies">
        <div class="kpi-chips">
          <div v-for="kpi in knowledgeKpis" :key="kpi.label" class="kpi-chip" :style="{ '--chip-color': kpi.color }">
            <span class="chip-value">{{ kpi.value }}</span>
            <span class="chip-label">{{ kpi.label }}</span>
            <span v-if="kpi.meta" class="chip-delta" :class="kpi.trend">{{ kpi.meta }}</span>
          </div>
        </div>
      </template>

      <template v-else-if="isEmployees">
        <div class="kpi-chips">
          <div v-for="kpi in employeeKpis" :key="kpi.label" class="kpi-chip" :style="{ '--chip-color': kpi.color }">
            <span class="chip-value">{{ kpi.value }}<small>{{ kpi.unit }}</small></span>
            <span class="chip-label">{{ kpi.label }}</span>
            <span class="chip-delta" :class="kpi.trend">{{ kpi.meta }}</span>
          </div>
        </div>
      </template>

    </div>
  </header>
</template>

<script setup>
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'

import { useDocumentCenterInbox } from '../../composables/useDocumentCenterInbox.js'
import { useTopBarNotificationStates } from '../../composables/useTopBarNotificationStates.js'
import { useTopBarWorkbenchPopovers } from '../../composables/useTopBarWorkbenchPopovers.js'
import { createCurrentYearDateRange } from '../../utils/dateRangeDefaults.js'
import { resolveDocumentNotificationId } from '../../utils/documentCenterNewState.js'
import EnterpriseSelect from '../shared/EnterpriseSelect.vue'
import {
  CHAT_KPIS,
  buildDigitalEmployeeWorkRecordKpis,
  buildDocumentKpis,
  buildEmployeeKpis,
  buildKnowledgeKpis,
  buildRequestKpis
} from './topBarKpis.js'
import { useTopBarOverviewRange } from './useTopBarOverviewRange.js'

const props = defineProps({
  currentView: { type: Object, required: true },
  search: { type: String, default: '' },
  activeView: { type: String, default: '' },
  ranges: { type: Array, default: () => [] },
  activeRange: { type: String, default: '' },
  employeeSummary: {
    type: Object,
    default: () => null
  },
  knowledgeSummary: {
    type: Object,
    default: () => null
  },
  requestSummary: {
    type: Object,
    default: () => null
  },
  documentSummary: {
    type: Object,
    default: () => null
  },
  digitalEmployeeSummary: {
    type: Object,
    default: () => null
  },
  workbenchSummary: {
    type: Object,
    default: () => null
  },
  workbenchMode: {
    type: String,
    default: 'traditional'
  },
  companyName: {
    type: String,
    default: ''
  },
  detailMode: {
    type: Boolean,
    default: false
  },
  detailAlerts: {
    type: Array,
    default: () => []
  },
  detailKpis: {
    type: Array,
    default: () => []
  },
  customRange: {
    type: Object,
    default: createCurrentYearDateRange
  },
  overviewDashboard: {
    type: String,
    default: 'finance'
  }
})

const emit = defineEmits([
  'update:search',
  'update:activeRange',
  'update:customRange',
  'update:overviewDashboard',
  'openChat',
  'newApplication',
  'openDocument',
  'navigate',
  'toggleWorkbenchMode'
])
const isChat = computed(() => props.activeView === 'chat')
const isOverview = computed(() => props.activeView === 'overview')
const isWorkbench = computed(() => props.activeView === 'workbench')
const isRequestDetail = computed(() => ['requests', 'documents', 'audit', 'digitalEmployees', 'receiptFolder', 'budget'].includes(props.activeView) && props.detailMode)
const isDocuments = computed(() => props.activeView === 'documents' && !props.detailMode)
const isRequests = computed(() => props.activeView === 'requests')
const isDigitalEmployees = computed(() => props.activeView === 'digitalEmployees')
const isPolicies = computed(() => props.activeView === 'policies')
const isEmployees = computed(() => props.activeView === 'employees')
const eyebrowLabel = computed(() => (
  String(props.currentView?.eyebrow || '').trim()
    || (isChat.value ? 'Smart Finance Q&A' : 'Smart Expense Operations')
))
const displayCompanyName = computed(() => String(props.companyName || '远光软件股份有限公司').trim() || '远光软件股份有限公司')
const isTopbarAiMode = computed(() => props.workbenchMode === 'ai')
const topbarWorkbenchModeTitle = computed(() => (isTopbarAiMode.value ? 'AI 模式，点击切换传统模式' : '传统模式，点击切换 AI 模式'))
const isWorkbenchAiHome = computed(() => isWorkbench.value && isTopbarAiMode.value)
const MAX_NOTIFICATION_ITEMS = 30
const {
  markDocumentInboxRowRead,
  markDocumentInboxRowsRead,
  notificationRows: documentInboxNotificationRows,
  refreshDocumentInbox,
  startDocumentInboxPolling,
  stopDocumentInboxPolling
} = useDocumentCenterInbox()
let documentInboxInitialRefreshTimer = null
const {
  notificationOpen,
  helpOpen,
  notificationWrapRef,
  helpWrapRef,
  topbarHelpDemo,
  toggleNotification,
  toggleHelp,
  closeNotification,
  closeHelp
} = useTopBarWorkbenchPopovers()
const {
  readNotificationIds,
  hideNotificationStates,
  isNotificationHidden,
  isNotificationRead,
  loadNotificationStates,
  markNotificationStateRead,
  markNotificationStatesRead
} = useTopBarNotificationStates()
const notificationTab = ref('unread')

function normalizeNotificationId(value) {
  return String(value || '').trim()
}

function formatNotificationTimeLabel(value) {
  const raw = String(value || '').trim()
  if (!raw) {
    return '最近更新'
  }

  const normalized = raw.replace('T', ' ')
  const isoMatched = normalized.match(/^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})/)
  if (isoMatched) {
    return `${isoMatched[2]}-${isoMatched[3]} ${isoMatched[4]}:${isoMatched[5]}`
  }

  const shortMatched = normalized.match(/^(\d{2})-(\d{2})\s+(\d{2}):(\d{2})/)
  if (shortMatched) {
    return `${shortMatched[1]}-${shortMatched[2]} ${shortMatched[3]}:${shortMatched[4]}`
  }

  const date = new Date(raw)
  if (!Number.isFinite(date.getTime())) {
    return raw.length > 16 ? `${raw.slice(0, 16)}...` : raw
  }

  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  return `${month}-${day} ${hour}:${minute}`
}

function resolveDocumentNotificationTone(row) {
  if (row?.source === 'approval') {
    return 'warning'
  }

  return row?.isUnread ? 'info' : 'success'
}

function resolveDocumentNotificationDescription(row) {
  return [
    row?.title,
    row?.initiatorName ? `发起人 ${row.initiatorName}` : '',
    row?.statusLabel ? `状态 ${row.statusLabel}` : ''
  ].filter(Boolean).join(' · ') || '单据中心有新的单据状态'
}

function resolveNotificationAvatarLabel(item) {
  const raw = String(
    item?.avatarLabel
      || item?.initiatorName
      || item?.applicantName
      || item?.employeeName
      || item?.category
      || item?.title
      || '通'
  ).trim()

  if (!raw) {
    return '通'
  }

  return raw.replace(/\s+/g, '').slice(0, 1).toUpperCase()
}

function resolveDocumentNotificationAvatarLabel(row) {
  return resolveNotificationAvatarLabel({
    avatarLabel:
      row?.initiatorName
      || row?.applicantName
      || row?.employeeName
      || row?.sourceLabel
      || row?.documentTypeLabel
      || row?.title
  })
}

function resolveWorkbenchNotificationId(item, index) {
  return normalizeNotificationId(`workbench:${item?.id || [item?.title, item?.description, item?.time, index].join('|')}`)
}

const documentNotificationItems = computed(() =>
  documentInboxNotificationRows.value
    .map((row) => {
      const id = normalizeNotificationId(resolveDocumentNotificationId(row))
      if (!id || isNotificationHidden(id)) {
        return null
      }
      const unread = Boolean(row.isUnread) && !isNotificationRead(id)

      return {
        id,
        kind: 'document',
        title: `${row.documentTypeLabel || '单据'} ${row.documentNo || row.claimId || '待生成'}`,
        description: resolveDocumentNotificationDescription(row),
        avatarLabel: resolveDocumentNotificationAvatarLabel(row),
        time: row.updatedAt || row.createdAt,
        timeLabel: formatNotificationTimeLabel(row.updatedAt || row.createdAt),
        category: row.sourceLabel || '单据中心',
        tone: resolveDocumentNotificationTone({ ...row, isUnread: unread }),
        unread,
        badge: unread ? '新' : '',
        target: {
          type: 'document',
          id: row.claimId,
          claimNo: row.documentNo
        },
        documentRow: row
      }
    })
    .filter(Boolean)
)

const workbenchNotificationItems = computed(() => (
  Array.isArray(props.workbenchSummary?.notifications)
    ? props.workbenchSummary.notifications.map((item, index) => {
        const id = resolveWorkbenchNotificationId(item, index)
        if (!id || isNotificationHidden(id)) {
          return null
        }
        const notificationTime = item.time || item.updatedAt || item.due

        return {
          ...item,
          id,
          kind: 'workbench',
          category: item.category || '个人工作台',
          avatarLabel: resolveNotificationAvatarLabel(item),
          time: notificationTime,
          timeLabel: formatNotificationTimeLabel(item.time || item.updatedAt || item.due),
          unread: Boolean(item.unread) && !readNotificationIds.value.has(id)
        }
      }).filter(Boolean)
    : []
))
const notificationItems = computed(() =>
  [...documentNotificationItems.value, ...workbenchNotificationItems.value].slice(0, MAX_NOTIFICATION_ITEMS)
)
const unreadNotifications = computed(() => notificationItems.value.filter((item) => item.unread))
const readNotifications = computed(() => notificationItems.value.filter((item) => !item.unread))
const activeNotifications = computed(() => (
  notificationTab.value === 'unread' ? unreadNotifications.value : readNotifications.value
))
const notificationBulkActionLabel = computed(() => (
  notificationTab.value === 'unread' ? '全部已读' : '删除已读'
))
const notificationBulkActionDisabled = computed(() => (
  notificationTab.value === 'unread'
    ? unreadNotifications.value.length === 0
    : readNotifications.value.length === 0
))
const topbarNotificationCount = computed(() => {
  const count = unreadNotifications.value.length
  return count > 0 ? Math.min(count, 99) : 0
})

function toggleTopbarWorkbenchMode() {
  emit('toggleWorkbenchMode')
}

function clearDocumentInboxInitialRefreshTimer() {
  if (documentInboxInitialRefreshTimer && typeof window !== 'undefined') {
    window.clearTimeout(documentInboxInitialRefreshTimer)
    documentInboxInitialRefreshTimer = null
  }
}

function scheduleDocumentInboxInitialRefresh() {
  if (typeof window === 'undefined') {
    return
  }

  clearDocumentInboxInitialRefreshTimer()
  documentInboxInitialRefreshTimer = window.setTimeout(() => {
    documentInboxInitialRefreshTimer = null
    void refreshDocumentInbox()
  }, props.activeView === 'workbench' ? 1200 : 6000)
}

function markNotificationRead(item) {
  if (!item?.id || !item.unread) {
    return
  }

  if (item.kind === 'document' && item.documentRow) {
    markDocumentInboxRowRead(item.documentRow)
  }

  void markNotificationStateRead(item)
}

function markUnreadNotificationsRead() {
  const currentItems = unreadNotifications.value
  if (!currentItems.length) {
    return
  }

  const documentRows = currentItems
    .filter((item) => item.kind === 'document' && item.documentRow)
    .map((item) => item.documentRow)

  if (documentRows.length) {
    markDocumentInboxRowsRead(documentRows)
  }

  void markNotificationStatesRead(currentItems)
}

function deleteReadNotifications() {
  const currentItems = readNotifications.value
  if (!currentItems.length) {
    return
  }

  void hideNotificationStates(currentItems)
}

function handleNotificationBulkAction() {
  if (notificationBulkActionDisabled.value) {
    return
  }

  if (notificationTab.value === 'unread') {
    markUnreadNotificationsRead()
    return
  }

  deleteReadNotifications()
}

function openNotification(item) {
  markNotificationRead(item)
  closeNotification()
  const target = item?.target || {}
  if (target.type === 'document' && (target.id || target.claimNo)) {
    emit('openDocument', {
      claimId: target.id,
      id: target.id || target.claimNo,
      claimNo: target.claimNo
    })
  }
}

const requestKpis = computed(() => buildRequestKpis(props.requestSummary ?? {}))
const documentKpis = computed(() => buildDocumentKpis(props.documentSummary ?? {}))
const showDigitalEmployeeWorkRecordKpis = computed(() => {
  const summary = props.digitalEmployeeSummary ?? {}
  return isDigitalEmployees.value && summary.section === 'workRecords'
})
const digitalEmployeeWorkRecordKpis = computed(() => buildDigitalEmployeeWorkRecordKpis(props.digitalEmployeeSummary ?? {}))
const chatKpis = CHAT_KPIS
const knowledgeKpis = computed(() => buildKnowledgeKpis(props.knowledgeSummary ?? {}))
const employeeKpis = computed(() => buildEmployeeKpis(props.employeeSummary ?? {}))
const {
  calendarOpen,
  draftStart,
  draftEnd,
  overviewDashboardOptions,
  overviewDashboardValue,
  rangeOptions,
  activeOption,
  isCustomRange,
  activeDateLabel,
  canApplyCustomRange,
  setRange,
  applyCustomRange
} = useTopBarOverviewRange(props, emit)

watch(
  () => props.activeView,
  (activeView, previousView) => {
    if (activeView === 'workbench' && previousView !== 'workbench') {
      clearDocumentInboxInitialRefreshTimer()
      void loadNotificationStates()
      void refreshDocumentInbox({ force: true })
    }
    if (activeView !== 'workbench') {
      closeNotification()
      closeHelp()
    }
  }
)

watch(notificationOpen, (open) => {
  if (open) {
    void loadNotificationStates()
  }
})

onMounted(() => {
  void loadNotificationStates()
  scheduleDocumentInboxInitialRefresh()
  startDocumentInboxPolling()
})

onBeforeUnmount(() => {
  clearDocumentInboxInitialRefreshTimer()
  stopDocumentInboxPolling()
})

</script>

<style scoped src="../../assets/styles/components/top-bar.css"></style>
