<script setup lang="ts">
import type { TabDefinition } from '@easyflow-core/typings';

import type { TabConfig, TabsProps } from '../../types';

import { computed, ref } from 'vue';

import { Pin, X } from '@easyflow-core/icons';
import { EasyFlowContextMenu, EasyFlowIcon } from '@easyflow-core/shadcn-ui';

interface Props extends TabsProps {}

defineOptions({
  name: 'EasyFlowTabsChrome',
  inheritAttrs: false,
});

const props = withDefaults(defineProps<Props>(), {
  contentClass: 'easyflow-tabs-content',
  contextMenus: () => [],
  gap: 8,
  tabs: () => [],
});

const emit = defineEmits<{
  close: [string];
  unpin: [TabDefinition];
}>();
const active = defineModel<string>('active');

const contentRef = ref();
const tabRef = ref();

const style = computed(() => {
  const { gap } = props;
  return {
    '--gap': `${gap}px`,
  };
});

const tabsView = computed(() => {
  return props.tabs.map((tab) => {
    const { fullPath, meta, name, path, key } = tab || {};
    const { affixTab, icon, newTabTitle, tabClosable, title } = meta || {};
    return {
      affixTab: !!affixTab,
      closable: Reflect.has(meta, 'tabClosable') ? !!tabClosable : true,
      fullPath,
      icon: icon as string,
      key,
      meta,
      name,
      path,
      title: (newTabTitle || title || name) as string,
    } as TabConfig;
  });
});

function onMouseDown(e: MouseEvent, tab: TabConfig) {
  if (
    e.button === 1 &&
    tab.closable &&
    !tab.affixTab &&
    tabsView.value.length > 1 &&
    props.middleClickToClose
  ) {
    e.preventDefault();
    e.stopPropagation();
    emit('close', tab.key);
  }
}
</script>

<template>
  <div
    ref="contentRef"
    :class="contentClass"
    :style="style"
    class="tabs-chrome !flex h-full w-max items-center gap-1 overflow-y-hidden px-2"
  >
    <TransitionGroup name="slide-left">
      <div
        v-for="(tab, i) in tabsView"
        :key="tab.key"
        ref="tabRef"
        :class="[
          {
            'is-active': tab.key === active,
            draggable: !tab.affixTab,
            'affix-tab': tab.affixTab,
          },
        ]"
        :data-active-tab="active"
        :data-index="i"
        class="tabs-chrome__item draggable translate-all group relative flex h-full min-w-0 select-none items-center"
        data-tab-item="true"
        @click="active = tab.key"
        @mousedown="onMouseDown($event, tab)"
      >
        <EasyFlowContextMenu
          :handler-data="tab"
          :menus="contextMenus"
          :modal="false"
          item-class="pr-6"
        >
          <div class="relative size-full">
            <!-- divider -->
            <!-- background -->
            <div
              class="tabs-chrome__background absolute inset-0 z-[-1] px-0 py-0 transition-opacity duration-150"
            >
              <div
                :class="{ 'is-active': tab.key === active }"
                class="tabs-chrome__background-content h-[calc(100%-8px)] rounded-2xl bg-transparent transition-all duration-150"
              ></div>
            </div>

            <!-- extra -->
            <div
              class="tabs-chrome__extra absolute right-2 top-1/2 z-[3] size-4 -translate-y-1/2"
            >
              <!-- close-icon -->
              <X
                v-show="!tab.affixTab && tabsView.length > 1 && tab.closable"
                class="mt-[2px] size-3 cursor-pointer rounded-full stroke-[hsl(var(--nav-item-muted-foreground))] transition-all hover:bg-[hsl(var(--surface-contrast-soft))/0.92] hover:stroke-[hsl(var(--foreground))] group-hover:stroke-[hsl(var(--nav-item-active-foreground))] group-[.is-active]:stroke-[hsl(var(--nav-item-active-foreground))]"
                @click.stop="() => emit('close', tab.key)"
              />
              <Pin
                v-show="tab.affixTab && tabsView.length > 1 && tab.closable"
                class="mt-[1px] size-3.5 cursor-pointer rounded-full stroke-[hsl(var(--nav-item-muted-foreground))] transition-all hover:bg-[hsl(var(--surface-contrast-soft))/0.92] hover:stroke-[hsl(var(--foreground))] group-hover:stroke-[hsl(var(--nav-item-active-foreground))] group-[.is-active]:stroke-[hsl(var(--nav-item-active-foreground))]"
                @click.stop="() => emit('unpin', tab)"
              />
            </div>

            <!-- tab-item-main -->
            <div
              class="tabs-chrome__item-main z-[2] mx-3 my-0 flex h-full min-w-0 items-center overflow-hidden pl-2 pr-5 text-[hsl(var(--nav-item-muted-foreground))] duration-150 group-hover:text-[hsl(var(--nav-item-active-foreground))] group-[.is-active]:font-medium group-[.is-active]:text-[hsl(var(--nav-item-active-foreground))]"
            >
              <EasyFlowIcon
                v-if="showIcon"
                :icon="tab.icon"
                class="mr-2 flex size-[15px] items-center overflow-hidden"
              />

              <span
                class="flex-1 overflow-hidden whitespace-nowrap text-[13px]"
              >
                {{ tab.title }}
              </span>
            </div>
          </div>
        </EasyFlowContextMenu>
      </div>
    </TransitionGroup>
  </div>
</template>

<style scoped>
.tabs-chrome {
  &__background-content {
    position: relative;
    overflow: visible;
  }

  &__background-content.is-active::before {
    position: absolute;
    inset: 1px -5px -1px;
    content: '';
    background: hsl(var(--background));
    border-top: 2px solid hsl(var(--primary) / 38%);
    border-right: 1px solid hsl(var(--primary) / 16%);
    border-left: 1px solid hsl(var(--primary) / 16%);
    border-radius: 15px 15px 0 0;
  }

  &__background-content.is-active::after {
    display: none;
  }

  &__item:not(.dragging) {
    @apply cursor-pointer;

    &:hover:not(.is-active) {
      & + .tabs-chrome__item {
        .tabs-chrome__divider {
          @apply opacity-0;
        }
      }

      .tabs-chrome__divider {
        @apply opacity-0;
      }
    }

    &.is-active {
      @apply z-[2];

      & + .tabs-chrome__item {
        .tabs-chrome__divider {
          @apply opacity-0 !important;
        }
      }
    }
  }
}
</style>
