<script setup>
import { computed, inject, onMounted, onUnmounted, ref, watch } from "vue";
import { useNamespace } from "@yh-ui/hooks";
import { useComponentTheme } from "@yh-ui/theme";
import { tabPaneProps } from "./tab-pane";
import { TABS_INJECTION_KEY } from "./tabs";
defineOptions({
  name: "YhTabPane"
});
const props = defineProps(tabPaneProps);
const ns = useNamespace("tab-pane");
const { themeStyle } = useComponentTheme(
  "tab-pane",
  computed(() => props.themeOverrides)
);
const tabsContext = inject(TABS_INJECTION_KEY);
const hasRendered = ref(false);
const isActive = computed(() => {
  return tabsContext?.activeTab.value === props.name;
});
const shouldRender = computed(() => {
  if (!props.lazy) return true;
  return hasRendered.value || isActive.value;
});
watch(isActive, (val) => {
  if (val && !hasRendered.value) {
    hasRendered.value = true;
  }
});
onMounted(() => {
  tabsContext?.registerPane({
    name: String(props.name),
    label: props.label,
    disabled: props.disabled,
    closable: props.closable,
    lazy: props.lazy,
    icon: props.icon
  });
});
onUnmounted(() => {
  tabsContext?.unregisterPane(String(props.name));
});
watch(
  () => ({
    name: props.name,
    label: props.label,
    disabled: props.disabled,
    closable: props.closable,
    lazy: props.lazy,
    icon: props.icon
  }),
  (config) => {
    tabsContext?.registerPane({
      name: String(config.name),
      label: config.label,
      disabled: config.disabled,
      closable: config.closable,
      lazy: config.lazy,
      icon: config.icon
    });
  }
);
</script>

<template>
  <div
    v-if="shouldRender"
    v-show="isActive"
    :class="[ns.b(), ns.is('active', isActive)]"
    :style="themeStyle"
    role="tabpanel"
  >
    <slot></slot>
  </div>
</template>

<style>
.yh-tab-pane {
  outline: none;
}
</style>
