<template>
  <div
    class="ivyforms-form-page-tabs ivyforms-flex ivyforms-align-items-center ivyforms-border-radius-8"
  >
    <div class="ivyforms-form-page-tabs__list ivyforms-flex ivyforms-align-items-center">
      <!-- Visible Page Tabs -->
      <div
        v-for="page in visiblePages"
        :key="page.id"
        class="ivyforms-page-tab-wrapper ivyforms-flex ivyforms-align-items-center"
        :class="{ 'is-active': activePage === page.id }"
      >
        <div
          role="button"
          tabindex="0"
          class="ivyforms-page-tab ivyforms-cursor-pointer"
          :class="{ 'is-active': activePage === page.id }"
          @click="handlePageClick(page.id)"
          @keydown.enter.prevent="handlePageClick(page.id)"
          @keydown.space.prevent="handlePageClick(page.id)"
        >
          <span class="ivyforms-page-tab__label">{{ truncateLabel(page.label) }}</span>

          <!-- Close button (X) -->
          <button
            v-if="pages.length > 1"
            type="button"
            class="ivyforms-page-tab__close ivyforms-flex ivyforms-align-items-center ivyforms-justify-content-center"
            :aria-label="`Remove ${page.label}`"
            @click.stop="handleDeletePage(page.id)"
          >
            <IvyIcon name="close" category="global" type="outline" size="s" />
          </button>
        </div>
      </div>

      <!-- Overflow Dropdown (Three Dots) -->
      <IvyDropdown
        v-if="hasOverflow"
        trigger="click"
        placement="bottom-start"
        popper-class="ivyforms-dropdown ivyforms-form-page-tabs-dropdown"
        @command="handleOverflowCommand"
      >
        <button
          type="button"
          class="ivyforms-page-tab ivyforms-page-tab--overflow ivyforms-cursor-pointer"
          aria-label="More pages"
          aria-haspopup="menu"
        >
          <IvyIcon name="context-menu-dot" category="global" type="fill" size="s" />
        </button>
        <template #dropdown>
          <IvyDropdownMenu>
            <IvyDropdownItem
              v-for="page in overflowPages"
              :key="page.id"
              :command="{ action: 'select', pageId: page.id }"
            >
              {{ page.label }}
            </IvyDropdownItem>
          </IvyDropdownMenu>
        </template>
      </IvyDropdown>

      <!-- Add Page Button -->
      <button
        type="button"
        class="ivyforms-page-tab ivyforms-page-tab--add ivyforms-cursor-pointer"
        @click="handleAddPage"
      >
        <IvyIcon
          name="plus"
          category="global"
          type="fill"
          size="s"
          class="ivyforms-page-tab--add__icon"
        />
        <ProBadge
          v-if="!isProActivated && pages.length >= 1"
          image="pro-bolt-no-background"
          size="d"
          class="ivyforms-page-tab--add__pro-badge"
        />
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import IvyDropdown from '@/views/_components/dropdown/IvyDropdown.vue'
import IvyDropdownMenu from '@/views/_components/dropdown/IvyDropdownMenu.vue'
import IvyDropdownItem from '@/views/_components/dropdown/IvyDropdownItem.vue'
import IvyIcon from '@/views/_components/icon/IvyIcon.vue'
import ProBadge from '@/views/_components/badges/ProBadge.vue'
import { useProFeatureUpgrade } from '@/composables/useProFeatureUpgrade'
import { useProAccess } from '@/composables/useProAccess'
import type { FormPage } from '@/types/form-page'

interface Props {
  modelValue: string // active page id
  pages: FormPage[]
  maxVisibleTabs?: number
}

const props = withDefaults(defineProps<Props>(), {
  pages: () => [],
  maxVisibleTabs: 4,
})

const emit = defineEmits<{
  'update:modelValue': [value: string]
  'page-add': []
  'page-delete': [pageId: string]
  'upgrade-required': [feature: string]
}>()

const activePage = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val),
})

// Calculate visible and overflow pages
const hasOverflow = computed(() => props.pages.length > props.maxVisibleTabs)

const visiblePages = computed(() => {
  if (!hasOverflow.value) {
    return props.pages
  }

  const maxVisible = props.maxVisibleTabs - 1
  const activeIndex = props.pages.findIndex((p) => p.id === activePage.value)

  if (activeIndex < maxVisible) {
    return props.pages.slice(0, maxVisible)
  } else {
    return [...props.pages.slice(0, maxVisible - 1), props.pages[activeIndex]]
  }
})

const overflowPages = computed(() => {
  if (!hasOverflow.value) {
    return []
  }

  const visibleIds = visiblePages.value.map((p) => p.id)
  return props.pages.filter((p) => !visibleIds.includes(p.id))
})

// Truncate long labels with ellipsis
const truncateLabel = (label: string, maxLength: number = 20) => {
  if (label.length > maxLength) {
    return label.substring(0, maxLength) + '...'
  }
  return label
}

const { showUpgradeDialog } = useProFeatureUpgrade()
const { isProActivated } = useProAccess()

const handlePageClick = (pageId: string) => {
  activePage.value = pageId
}

const handleAddPage = () => {
  // Lite: block adding extra pages and surface upgrade dialog
  if (!isProActivated.value && props.pages.length >= 1) {
    showUpgradeDialog()
    emit('upgrade-required', 'multi-page')
    return
  }

  emit('page-add')
}

const handleDeletePage = (pageId: string) => {
  emit('page-delete', pageId)
}

const handleOverflowCommand = (command: { action: string; pageId?: string }) => {
  if (command.action === 'select' && command.pageId) {
    activePage.value = command.pageId
  }
}
</script>

<style lang="scss" scoped>
.ivyforms-form-page-tabs {
  gap: var(--spacing-01, 4px);
  padding: 3px;
  /* Figma: page tab rail */
  background: var(--map-base-dusk-o10);
  color: var(--map-base-text-0);
  min-height: 38px;
  height: 38px;
  box-sizing: border-box;
  border-radius: 8px;

  &__list {
    gap: var(--spacing-01, 4px);
    flex-wrap: nowrap;
  }
}

.ivyforms-page-tab-wrapper {
  position: relative;
}

.ivyforms-page-tab {
  display: inline-flex;
  align-items: center;
  gap: var(--spacing-02, 8px);
  min-height: 24px;
  min-width: 28px;
  padding: 3px 10px;
  border: none;
  border-radius: 6px;
  box-shadow: none;
  font-family: inherit;
  font-size: 14px;
  font-weight: 500;
  line-height: 20px;
  color: var(--map-base-text-0);
  background: transparent;
  transition:
    background 0.15s ease,
    box-shadow 0.15s ease;
  white-space: nowrap;
  user-select: none;
  outline: none;

  &__label {
    color: var(--map-base-text-0);
    text-align: center;
    font-family: inherit;
    font-size: 14px;
    font-weight: inherit;
    line-height: 20px;
  }

  &__close {
    width: 20px;
    height: 20px;
    padding: 0;
    margin-left: 2px;
    border: none;
    border-radius: 4px;
    background: transparent;
    color: var(--map-base-text-0);

    &:hover {
      background: var(--map-base-dusk-o10);
      color: var(--map-base-text-0);
    }

    :deep(.ivyforms-icon) {
      display: flex;
      align-items: center;
      justify-content: center;
    }

    :deep(.ivyforms-icon__svg) {
      color: var(--map-base-text-0);
      fill: var(--map-base-text-0);
    }

    &:hover :deep(.ivyforms-icon__svg) {
      color: var(--map-base-text-0);
      fill: var(--map-base-text-0);
    }
  }

  /* Inactive tab hover — subtle lift, keep label readable */
  &:hover:not(.is-active) {
    background: var(--map-base-dusk-o10);
    color: var(--map-base-text-0);
  }

  &.is-active {
    background: var(--map-ground-level-3);
    color: var(--map-base-text-0);
  }

  &--overflow {
    min-width: 32px;
    padding: 3px 8px;
    justify-content: center;
    color: var(--map-base-text-0);

    :deep(.ivyforms-icon__svg) {
      color: var(--map-base-text-0);
      fill: var(--map-base-text-0);
    }

    &:hover {
      background: var(--map-base-dusk-o10);
      color: var(--map-base-text-0);
    }

    &:hover :deep(.ivyforms-icon__svg) {
      color: var(--map-base-text-0);
      fill: var(--map-base-text-0);
    }
  }

  &--add {
    position: relative;
    min-width: 28px;
    padding: 3px 6px;
    justify-content: center;
    color: var(--map-base-text-0);

    &__icon {
      display: flex;
    }

    :deep(.ivyforms-icon__svg) {
      color: var(--map-base-text-0);
      fill: var(--map-base-text-0);
    }

    &:hover {
      background: var(--map-base-dusk-o10);
      color: var(--map-base-text-0);
    }

    &:hover :deep(.ivyforms-icon__svg) {
      color: var(--map-base-text-0);
      fill: var(--map-base-text-0);
    }

    &__pro-badge {
      position: absolute;
      top: -8px;
      right: -6px;
      pointer-events: none;
    }
  }
}

.ivyforms-page-tab-wrapper.is-active .ivyforms-page-tab {
  background: var(--map-ground-level-3);
}
</style>

<!-- Popper is teleported to body; class hooks theme tokens from body.ivyforms-theme-dark -->
<style lang="scss">
.ivyforms-form-page-tabs-dropdown.ivyforms-dropdown {
  .ivyforms-dropdown-menu {
    background: var(--map-ground-level-2-foreground, #2a3540);
  }

  .ivyforms-dropdown-item.el-dropdown-menu__item {
    &:not(.is-disabled) {
      color: var(--map-base-text-0);
    }

    &:hover:not(.is-disabled),
    &:focus {
      background: var(--map-hover);
      color: var(--map-base-text-0);
    }

    &:hover:not(.is-disabled) .ivyforms-dropdown-item__label,
    &:focus .ivyforms-dropdown-item__label {
      color: var(--map-base-text-0);
    }
  }
}
</style>
