<script setup>
import { computed, ref } from 'vue'
import { solutions } from '../data/homepage'
import QrPlaceholder from './QrPlaceholder.vue'

const activeKey = ref(solutions[0].key)
const activeIndex = computed(() => solutions.findIndex(item => item.key === activeKey.value))
const activeSolution = computed(() => solutions[activeIndex.value] ?? solutions[0])

const selectSolution = (index) => {
  activeKey.value = solutions[index]?.key ?? solutions[0].key
}

const handleTabKeydown = (event, index) => {
  const keyMap = {
    ArrowRight: 1,
    ArrowDown: 1,
    ArrowLeft: -1,
    ArrowUp: -1
  }

  if (event.key === 'Home' || event.key === 'End' || keyMap[event.key]) {
    event.preventDefault()
  } else {
    return
  }

  const nextIndex =
    event.key === 'Home'
      ? 0
      : event.key === 'End'
        ? solutions.length - 1
        : (index + keyMap[event.key] + solutions.length) % solutions.length

  selectSolution(nextIndex)
  document.getElementById(`solution-tab-${solutions[nextIndex].key}`)?.focus()
}
</script>

<template>
  <section class="solution-section page-section page-section--compact">
    <div class="container">
      <div class="solution-tabs" role="tablist" aria-label="版本切换">
        <button
          v-for="(solution, index) in solutions"
          :key="solution.key"
          :id="`solution-tab-${solution.key}`"
          type="button"
          :class="['solution-tab', { active: solution.key === activeKey }]"
          role="tab"
          :aria-selected="solution.key === activeKey"
          aria-controls="solution-panel"
          :tabindex="solution.key === activeKey ? 0 : -1"
          @click="selectSolution(index)"
          @keydown="handleTabKeydown($event, index)"
        >
          {{ solution.tab }}
        </button>
        <span class="tab-indicator" :style="{ transform: `translateX(${activeIndex * 100}%)` }"></span>
      </div>

      <div class="solution-grid">
        <article
          id="solution-panel"
          :key="activeSolution.key"
          class="solution-card active"
          role="tabpanel"
          :aria-labelledby="`solution-tab-${activeSolution.key}`"
          tabindex="0"
        >
          <div class="solution-card-top">
            <span class="solution-kicker">{{ activeSolution.tab }}</span>
            <h3>{{ activeSolution.title }}</h3>
          </div>
          <ol v-if="activeSolution.key !== 'personal'" class="solution-points">
            <li v-for="point in activeSolution.points" :key="point">{{ point }}</li>
          </ol>
          <p v-else class="solution-personal-text">{{ activeSolution.points[0] }}</p>
          <div class="solution-qr-row">
            <span>具体咨询：</span>
            <QrPlaceholder :label="activeSolution.qrLabel" :title="`${activeSolution.tab}咨询二维码`" />
          </div>
        </article>
      </div>
    </div>
  </section>
</template>
