<template>
  <pn-page-wrapper>
    <template #title>
      <slot name="title" />
    </template>
    <q-tab-panels
      id="tab-panels"
      v-model="tabSelect"
      keep-alive
      class="bg-transparent w100"
      style="flex-grow: 1;"
      >
      <q-tab-panel
        v-for="tab in tabs"
        :key="tab.name"
        :name="tab.name"
        class="q-pa-none column w100"
        >
        <router-view :tabsSlotHeight/>
      </q-tab-panel>
    </q-tab-panels>

    <template #tabs>
      <div class="q-pa-none q-ma-none">
        <q-resize-observer @resize="onTabsSlotResize"/>
        <div class="q-py-md q-px-md overflow-hidden rounded-fix">
          <div style="height: 0px;" class="row no-wrap no-pointer-events overflow-hidden">
            <div
              v-for="(tab, idx) in tabs"
              :key="idx"
              class="text-caption text-bold"
              >
              <q-resize-observer @resize="val => onTabResize(val, idx)"/>
              {{ $t(tab.label) }}
            </div>
          </div>

          <div
            id="tabs-wrapper"
            class="bg-white shadow-t rounded-fix"
            :style="minWidthTab"
            >
            <q-tabs
              v-model="tabSelect"
              dense
              align="center"
              id="tabs"
              :breakpoint="0"
              class="w100 text-grey-7 "
              style="z-index: 1000;"
              >
              <q-route-tab
                v-for="tab in tabs"
                :to="{ name: tab.name }"
                :name="tab.name"
                :key="tab.name"
                :ripple="false"
                no-caps
                dense
                :class="tabSelect === tab.name ? 'active' : ''"
                >
                <div class="column items-center">
                  <q-icon :name="tab.icon + (tabSelect === tab.name ? '' : '-outline')" :size="config?.icon"/>
                  <span
                    v-if="config?.showLabel"
                    class="text-caption tab-label text-bold"
                    >
                    {{ $t(tab.label) }}
                  </span>
                </div>
              </q-route-tab>
              <q-resize-observer @resize="size => tabsWidth = size.width" />
            </q-tabs>
          </div>
          <div class="bg-transparent"
            style="height: var(--tg-safe-area-inset-bottom)"
          />
        </div>
      </div>
      
    </template>
  </pn-page-wrapper>
</template>

<script setup lang="ts">
  import { ref, onBeforeMount, computed } from 'vue'
  import { useRoute } from 'vue-router'

  const route = useRoute()

  interface Tab {
    name: string
    label: string
    icon: string
  }
  
  const props = defineProps<{
    tabs: Tab[]
  }>()

  const tabSelect = ref<string>()

  onBeforeMount(() => {
    const initialTab = props.tabs.find(t => t.name === route.name)?.name || props.tabs[0]?.name || ''
    tabSelect.value = initialTab
  })

  const tabsSlotHeight = ref(0)
  
  interface sizeParams {
    height: number,
    width: number
  }

  function onTabsSlotResize(size: sizeParams) {
    tabsSlotHeight.value = size.height
  }

  // hidden icon name if overflow - with resize-observer
  const tabsWidth = ref(0)
  const widthTabLabel = ref(new Array(props.tabs.length).fill(0))
  
  function onTabResize (size: sizeParams, idx: number) {
    if (size.width) widthTabLabel.value[idx] = size.width
  }

  const config = computed(() => {
    const ICON_SM = 24
    const ICON_MD = 32
    
    const availableWidth = tabsWidth.value - 2 * 8

    const variants = [
      { icon: 'sm', gap: 16, showLabel: true },
      { icon: 'sm', gap: 8,  showLabel: true },
      { icon: 'md', gap: 16, showLabel: false },
      { icon: 'md', gap: 8,  showLabel: false },
      { icon: 'sm', gap: 16, showLabel: false },
      { icon: 'sm', gap: 8,  showLabel: false }
    ] as const

    for (const v of variants) {
      const iconW = v.icon === 'sm' ? ICON_SM : ICON_MD
      let totalNeeded = 0
      
      props.tabs.forEach((_, idx) => {
        const labelW = v.showLabel ? widthTabLabel.value[idx] : 0
        const contentW = Math.max(iconW, labelW)
        totalNeeded += contentW + (v.gap * 2)
      })

      if (totalNeeded <= availableWidth || v === variants[variants.length - 1]) {
        return v
      }
    }
    return variants[variants.length - 1]
  })

  const minWidthTab = computed(() => {
    const activeIdx = props.tabs.findIndex(el => el.name === tabSelect.value)
    const currentGap = config.value?.gap ?? 8
    
    const labelW = config.value?.showLabel ? widthTabLabel.value[activeIdx] : 0
    const iconW = config.value?.icon === 'sm' ? 24 : 32
    const activeContentWidth = Math.max(labelW, iconW)

    const PADDING_AROUND = 3

    return {
      '--current-gap': `${currentGap}px`,
      '--min-width-tab': '1px',
      '--active-tab-width': (activeContentWidth + 16 * 2) + 'px',
      '--tabs-height': tabsSlotHeight.value - 32 - PADDING_AROUND * 2 + 'px',
      '--padding-around': PADDING_AROUND + 'px'
    }
  })
</script>

<style scoped lang="scss">
  #tabs-wrapper {
    padding: var(--padding-around);
  }

  #tabs :deep(.q-tabs__content) {
    justify-content: space-evenly;
    padding: 0 8px;
  }
  
  #tabs :deep(.q-tab) {
    padding: 0 var(--current-gap);
  }

  #tabs :deep(.active) {
    color: var(--q-primary)
  }
 
  #tabs :deep(.q-router-link--active .q-tab__indicator) {
    height: calc(var(--tabs-height) - var(--tg-safe-area-inset-bottom, 0px));
    border-radius: calc(var(--tabs-height) / 2);
    overflow: hidden;
    opacity: 0.1;
    background-color: var(--q-primary);
  }

  #tabs :deep(.q-focus-helper) {
    border-radius: calc(var(--tabs-height) / 2);
    top: var(--tabs-y-padding);
    border: 0px;
  }

  #tabs :deep(.q-tabs__arrow) {
    display: none;
  }

  #tabs :deep(.q-tab__content) {
    min-width: var(--min-width-tab);
    padding-top: 5px;
    padding-bottom: 1px;
  }

  #tabs :deep(.q-tab__content .tab-label) {
    margin-top: -2px;
  }

  #tabs :deep(.q-tab--active .q-tab__indicator) {
    width: var(--active-tab-width);
    right: inherit;
    left: inherit;
  }

  #tabs :deep(.q-focus-helper) {
    width: calc(100% - var(--current-gap) * 2 + 32px) !important;
    left: calc(var(--current-gap) - 16px);
  }
</style>
