<template>
  <header class="topbar" :class="{ 'chat-mode': isChat }">
    <div class="title-group">
      <div class="eyebrow">{{ isChat ? 'Smart Finance Q&A' : 'Smart Expense Operations' }}</div>
      <h1>{{ currentView.title }}</h1>
      <p>{{ currentView.desc }}</p>
    </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>
      </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="isApproval">
        <div class="kpi-chips">
          <div v-for="kpi in approvalKpis" :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>
        <div class="topbar-spacer"></div>
        <button class="create-top-btn" type="button">
          <i class="mdi mdi-check-circle"></i>
          <span>批量通过</span>
        </button>
      </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 class="chip-delta" :class="kpi.trend">{{ kpi.meta }}</span>
          </div>
        </div>
      </template>
    </div>
  </header>
</template>

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

const props = defineProps({
  currentView: { type: Object, required: true },
  search: { type: String, default: '' },
  activeView: { type: String, default: '' },
  ranges: { type: Array, default: () => [] },
  activeRange: { type: String, default: '' },
  customRange: {
    type: Object,
    default: () => ({ start: '2024-07-06', end: '2024-07-12' })
  }
})

const emit = defineEmits([
  'update:search',
  'update:activeRange',
  'update:customRange',
  'batchApprove',
  'openChat',
  'newApplication'
])

const isChat = computed(() => props.activeView === 'chat')
const isOverview = computed(() => props.activeView === 'overview')
const isRequests = computed(() => props.activeView === 'requests')
const isApproval = computed(() => props.activeView === 'approval')
const isPolicies = computed(() => props.activeView === 'policies')

const requestKpis = [
  { label: '全部单据', value: 30, delta: '+8', trend: 'up', arrow: 'mdi mdi-arrow-up', color: '#10b981' },
  { label: '待提交', value: 5, delta: '-1', trend: 'down', arrow: 'mdi mdi-arrow-down', color: '#f59e0b' },
  { label: '审批中', value: 8, delta: '+2', trend: 'up', arrow: 'mdi mdi-arrow-up', color: '#3b82f6' },
  { label: '已完成', value: 17, delta: '+7', trend: 'up', arrow: 'mdi mdi-arrow-up', color: '#10b981' }
]

const chatKpis = [
  { label: '今日已问数', value: 86, unit: '次', meta: '较昨日 +18', trend: 'up', color: '#10b981' },
  { label: '已解决问题', value: 72, unit: '条', meta: '解决率 83.7%', trend: 'up', color: '#3b82f6' },
  { label: '知识命中率', value: '92.3', unit: '%', meta: '较昨日 +2.6%', trend: 'up', color: '#8b5cf6' },
  { label: '平均响应时长', value: 2.1, unit: 's', meta: '较昨日 -0.3s', trend: 'down', color: '#f59e0b' }
]

const approvalKpis = [
  { label: '待审批单据', value: 12, unit: '单', meta: '较昨日 +3', trend: 'up', color: '#059669' },
  { label: '高风险单据', value: 4, unit: '单', meta: '较昨日 +1', trend: 'up', color: '#ef4444' },
  { label: '即将超时', value: 3, unit: '单', meta: '30 分钟内', trend: 'down', color: '#f59e0b' },
  { label: '今日已处理', value: 28, unit: '单', meta: '通过率 86%', trend: 'up', color: '#10b981' }
]

const knowledgeKpis = [
  { label: '文档总数', value: '1,248', meta: '较上周 +68', trend: 'up', icon: 'mdi mdi-file-document-outline', color: '#10b981' },
  { label: '文件夹总数', value: '36', meta: '较上周 +2', trend: 'up', icon: 'mdi mdi-folder-outline', color: '#3b82f6' },
  { label: '问答总量', value: '8,562', meta: '较上周 +321', trend: 'up', icon: 'mdi mdi-comment-text-multiple-outline', color: '#8b5cf6' },
  { label: '知识命中率', value: '87.3%', meta: '较上周 +1.2%', trend: 'up', icon: 'mdi mdi-bullseye-arrow', color: '#f59e0b' }
]
const calendarOpen = ref(false)
const draftStart = ref(props.customRange.start)
const draftEnd = ref(props.customRange.end)

const fallbackRangeLabels = ['今日', '本周', '本月']
const dateLabels = {
  '今日': '2024-07-12',
  '本周': '2024-07-06 ~ 2024-07-12',
  '本月': '2024-07'
}

const rangeOptions = computed(() =>
  props.ranges.map((range, index) => ({
    value: range,
    label: fallbackRangeLabels[index] ?? String(range)
  }))
)

const activeOption = computed(() =>
  rangeOptions.value.find((option) => option.value === props.activeRange) ?? rangeOptions.value[0]
)

const isCustomRange = computed(() => props.activeRange === 'custom')
const activeDateLabel = computed(() => {
  if (isCustomRange.value) return formatRangeLabel(props.customRange.start, props.customRange.end)
  return dateLabels[activeOption.value?.label] ?? '2024-07-06 ~ 2024-07-12'
})

const canApplyCustomRange = computed(() =>
  Boolean(draftStart.value && draftEnd.value && draftStart.value <= draftEnd.value)
)

watch(
  () => props.customRange,
  (range) => {
    draftStart.value = range.start
    draftEnd.value = range.end
  },
  { deep: true }
)

function setRange(range) {
  emit('update:activeRange', range)
  calendarOpen.value = false
}

function applyCustomRange() {
  if (!canApplyCustomRange.value) return
  emit('update:customRange', { start: draftStart.value, end: draftEnd.value })
  emit('update:activeRange', 'custom')
  calendarOpen.value = false
}

function formatRangeLabel(start, end) {
  if (!start || !end) return '选择时间段'
  if (start === end) return start
  return `${start} ~ ${end}`
}
</script>

<style scoped>
.topbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 24px;
  padding: 18px 24px 20px;
  background: #fff;
}

.topbar.chat-mode {
  padding-bottom: 16px;
  border-bottom: 1px solid #eef2f7;
}

.title-group {
  min-width: 0;
}

.eyebrow {
  display: inline-block;
  margin-bottom: 8px;
  padding: 3px 10px;
  border-radius: 6px;
  background: linear-gradient(135deg, rgba(16, 185, 129, 0.10), rgba(59, 130, 246, 0.10));
  color: #0d9668;
  font-size: 11px;
  font-weight: 800;
  letter-spacing: 1.2px;
  text-transform: uppercase;
}

.topbar h1 {
  color: #0f172a;
  font-size: 26px;
  font-weight: 800;
  letter-spacing: 0;
  line-height: 1.2;
}

.topbar p {
  margin-top: 6px;
  max-width: 720px;
  color: #64748b;
  font-size: 14px;
  line-height: 1.5;
}

.top-actions {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 14px;
  flex-wrap: wrap;
}

.range-combo {
  position: relative;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.range-shell {
  height: 42px;
  display: inline-flex;
  align-items: center;
  padding: 3px;
  border: 1px solid #d7e0ea;
  border-radius: 10px;
  background: #fff;
  box-shadow: 0 1px 2px rgba(15, 23, 42, .04);
}

.range-meta {
  height: 34px;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 0 12px;
  border-right: 1px solid #e2e8f0;
  color: #334155;
  font-size: 13px;
  font-weight: 650;
  white-space: nowrap;
}

.range-meta .mdi {
  color: #10b981;
}

.range-tabs {
  display: inline-flex;
  align-items: center;
  gap: 2px;
  padding-left: 3px;
}

.range-tabs button {
  height: 34px;
  min-width: 54px;
  padding: 0 14px;
  border: 0;
  border-radius: 8px;
  background: transparent;
  color: #64748b;
  font-size: 13px;
  font-weight: 700;
  white-space: nowrap;
  transition: background 160ms ease, color 160ms ease, box-shadow 160ms ease;
}

.range-tabs button:hover:not(.active) {
  background: #f1f5f9;
  color: #334155;
}

.range-tabs button.active {
  background: #10b981;
  color: #fff;
  box-shadow: 0 6px 14px rgba(16, 185, 129, .18);
}

.custom-range-wrap {
  position: relative;
}

.custom-range-btn {
  height: 42px;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 0 13px;
  border: 1px solid #d7e0ea;
  border-radius: 10px;
  background: #fff;
  color: #334155;
  font-size: 13px;
  font-weight: 750;
  white-space: nowrap;
}

.custom-range-btn:hover,
.custom-range-btn.active {
  border-color: rgba(16, 185, 129, .34);
  background: #f6fffb;
  color: #0f9f78;
}

.calendar-popover {
  position: absolute;
  top: calc(100% + 10px);
  right: 0;
  width: 336px;
  z-index: 40;
  display: grid;
  gap: 14px;
  padding: 16px;
  border: 1px solid #d7e0ea;
  border-radius: 12px;
  background: #fff;
  box-shadow: 0 18px 42px rgba(15, 23, 42, .16);
}

.calendar-popover header,
.calendar-popover footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.calendar-popover header strong {
  color: #0f172a;
  font-size: 15px;
}

.calendar-popover header button {
  width: 30px;
  height: 30px;
  display: grid;
  place-items: center;
  border: 0;
  border-radius: 8px;
  background: transparent;
  color: #64748b;
}

.date-fields {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.date-fields label {
  display: grid;
  gap: 6px;
}

.date-fields span {
  color: #64748b;
  font-size: 12px;
  font-weight: 700;
}

.date-fields input {
  width: 100%;
  height: 38px;
  padding: 0 9px;
  border: 1px solid #d7e0ea;
  border-radius: 8px;
  color: #0f172a;
  font-size: 13px;
}

.ghost-btn,
.apply-btn {
  height: 36px;
  padding: 0 14px;
  border-radius: 8px;
  font-size: 13px;
  font-weight: 750;
}

.ghost-btn {
  border: 1px solid #d7e0ea;
  background: #fff;
  color: #334155;
}

.apply-btn {
  border: 0;
  background: #10b981;
  color: #fff;
}

.apply-btn:disabled {
  cursor: not-allowed;
  background: #cbd5e1;
}

.kpi-chips {
  display: flex;
  gap: 10px;
}

.kpi-chip {
  display: grid;
  grid-template-columns: auto auto;
  grid-template-rows: auto auto;
  gap: 2px 10px;
  padding: 8px 16px;
  border-radius: 10px;
  background: linear-gradient(135deg, color-mix(in srgb, var(--chip-color) 8%, #fff), color-mix(in srgb, var(--chip-color) 3%, #f8fafc));
  border: 1px solid color-mix(in srgb, var(--chip-color) 18%, #e2e8f0);
}

.chip-value {
  grid-row: 1 / 3;
  align-self: center;
  color: #0f172a;
  font-size: 22px;
  font-weight: 850;
  line-height: 1;
}

.chip-value small {
  font-size: 13px;
  font-weight: 700;
  margin-left: 2px;
}

.chip-label {
  color: #64748b;
  font-size: 12px;
  font-weight: 700;
}

.chip-delta {
  color: #94a3b8;
  font-size: 11px;
  font-weight: 700;
}

.chip-delta.up { color: #059669; }
.chip-delta.down { color: #f59e0b; }

.topbar-spacer {
  flex: 1;
  min-width: 0;
}

.create-top-btn {
  height: 40px;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 0 18px;
  border: 0;
  border-radius: 8px;
  background: #059669;
  color: #fff;
  font-size: 14px;
  font-weight: 750;
  box-shadow: 0 8px 18px rgba(5, 150, 105, 0.18);
  white-space: nowrap;
}

.create-top-btn:hover {
  background: #047857;
}

@media (max-width: 1120px) {
  .range-combo {
    width: 100%;
    justify-content: flex-end;
  }
}

@media (max-width: 960px) {
  .topbar {
    flex-direction: column;
    align-items: stretch;
  }

  .top-actions,
  .search-wrap,
  .search-wrap.wide,
  .month-chip,
  .qa-filter,
  .new-question-btn {
    width: 100%;
  }

  .range-combo {
    justify-content: stretch;
  }

  .range-shell {
    flex: 1;
  }

  .range-meta {
    flex: 1;
  }

  .custom-range-btn {
    width: 100%;
    justify-content: center;
  }

  .calendar-popover {
    right: auto;
    left: 0;
  }
}

@media (max-width: 640px) {
  .range-combo {
    display: grid;
    gap: 8px;
  }

  .range-shell {
    height: auto;
    display: grid;
    gap: 4px;
  }

  .range-meta {
    width: 100%;
    border-right: 0;
    border-bottom: 1px solid #e2e8f0;
    justify-content: center;
  }

  .range-tabs {
    width: 100%;
    padding-left: 0;
  }

  .range-tabs button {
    flex: 1;
    padding: 0 8px;
  }

  .calendar-popover {
    width: min(336px, calc(100vw - 32px));
  }

  .date-fields {
    grid-template-columns: 1fr;
  }
}
</style>
