<script setup lang="ts">
import { computed, useAttrs } from 'vue';
import { Primitive } from 'reka-ui';
import { SidebarMenuSubItem as UiSidebarMenuItem } from '@/components/core/sidebar';
import { ACTIVE_INDICATOR_CLASS } from '@/lib/activeIndicator';
import { cn, omitClass } from '@/lib/utils';
import type { UiSidebarMenuSubItemProps } from './types';

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

const props = withDefaults(defineProps<UiSidebarMenuSubItemProps>(), {
  as: 'button',
  isActive: false,
});

const attrs = useAttrs();

const containerClass = computed(() =>
  cn(
    // Same hover/active fill as UiSidebarMenuButton so sub-items visually match primary rows.
    'relative flex h-8 w-full min-w-0 items-center gap-2 rounded-md border border-transparent px-2 py-1.5 transition-colors hover:bg-background-surface-muted-subtle data-[active=true]:bg-background-surface-muted-subtle',
    'has-[:focus-visible]:border-border-surface-focus-ring has-[:focus-visible]:ring-[3px] has-[:focus-visible]:ring-ring/50',
    ACTIVE_INDICATOR_CLASS,
  ),
);

const itemClass = computed(() =>
  cn(
    '!h-full min-w-0 flex-1 rounded-none bg-transparent px-0 py-0 text-left outline-hidden transition-colors',
    'body-14-regular text-content-on-surface-primary',
    '!hover:bg-transparent !active:bg-transparent',
    'focus-visible:ring-0',
    'data-[active=true]:!bg-transparent data-[active=true]:!text-content-on-surface-primary',
    '[&>[data-slot=label]]:min-w-0 [&>[data-slot=label]]:truncate',
    // Stretched-link: extend the hit area to cover the row's padding so clicks
    // anywhere on the row activate the sub-item.
    'before:content-[""] before:absolute before:inset-0 before:z-0',
    attrs.class as string | undefined,
  ),
);

const passthroughAttrs = computed(() =>
  omitClass(attrs as Record<string, unknown>),
);
</script>

<template>
  <UiSidebarMenuItem>
    <div :data-active="props.isActive" :class="containerClass">
      <Primitive
        v-bind="passthroughAttrs"
        :as="props.as"
        :as-child="props.asChild"
        :data-active="props.isActive"
        :class="itemClass"
      >
        <span
          v-if="$slots.default"
          data-slot="label"
          :class="props.isActive ? 'font-medium' : undefined"
        >
          <slot />
        </span>
      </Primitive>
    </div>
  </UiSidebarMenuItem>
</template>
