<template>
  <div>
    <!-- Вывод секций через цикл -->
    <CreateSection
      v-for="{ name, isActive, isNextActiveSection } in visibleSections"
      :key="name"
      :isActive
      :isNextActiveSection
    >
      <slot :name="name" />
    </CreateSection>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import type { QRCodeDocument } from '@/types/DBDocumentTypes'

// Пропсы, которые будут передаваться из родительского компонента
const props = defineProps<{
  placement: null | QRCodeDocument['placement']
  selectedActions: QRCodeDocument['actions']
  messageDeliveryMethod: null | QRCodeDocument['messageDeliveryMethod']
}>()

// Доступные шаги и их условия
const steps = [
  {
    name: 'placement',
    isActive: true,
  },
  {
    name: 'actions',
    get isActive() {
      return !!props.placement
    },
  },
  {
    name: 'delivery',
    get isHidden() {
      return !props.placement || !props.selectedActions.includes('sendMessage')
    },
    get isActive() {
      return props.selectedActions.length > 0 && props.selectedActions.includes('sendMessage')
    },
  },
  {
    name: 'messages',
    get isHidden() {
      return (
        !props.placement ||
        !props.selectedActions.includes('sendMessage') ||
        props.messageDeliveryMethod === 'telegram'
      )
    },
    get isActive() {
      return props.messageDeliveryMethod && props.selectedActions.includes('sendMessage')
    },
  },
  {
    name: 'summary',
    get isActive() {
      return props.selectedActions.includes('sendMessage')
        ? !!props.messageDeliveryMethod && props.messageDeliveryMethod !== 'telegram'
        : props.selectedActions.length > 0
    },
  },
]

const activeSections = computed(() => {
  const result = []
  for (const step of steps) {
    const isActive = !step.isHidden && step.isActive
    if (isActive) {
      result.push(step.name)
    }
  }
  return result
})

const nextActiveSectionName = ref<string>('')

watch(
  activeSections,
  (newActiveSections, oldActiveSteps) => {
    nextActiveSectionName.value =
      (oldActiveSteps && newActiveSections[oldActiveSteps.length]) ?? newActiveSections.at(-1)!
  },
  {
    immediate: true,
  },
)

// Выводимые секции
const visibleSections = computed(() => {
  const result = []
  for (const step of steps) {
    if (step.isHidden) continue
    result.push({
      name: step.name,
      isActive: activeSections.value.includes(step.name),
      isNextActiveSection: nextActiveSectionName.value === step.name,
    })
  }
  return result
})
</script>
