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

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

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

const attrs = useAttrs();

const containerClass = computed(() =>
  cn(
    'relative flex h-10 w-full min-w-0 cursor-pointer select-none items-center rounded-md border border-transparent px-2 py-2',
    'transition-colors hover-layer hover-layer-default',
    // Hover/active tint relative to the `secondary` surface the popover menu sits on.
    '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(
    'group/sidebar-popover-menu-item flex h-full w-full min-w-0 items-center gap-3 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]:text-content-on-surface-primary',
    attrs.class as string | undefined,
  ),
);

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

<template>
  <div :data-active="props.isActive" :class="containerClass">
    <Primitive
      v-bind="passthroughAttrs"
      :as="props.as"
      :as-child="props.asChild"
      :data-active="props.isActive"
      :aria-current="props.isActive ? 'true' : undefined"
      :class="itemClass"
    >
      <div
        class="flex size-6 shrink-0 items-center justify-center rounded-md text-content-on-surface-primary"
      >
        <slot name="icon" />
      </div>

      <span
        :class="
          cn(
            'min-w-0 flex-1 truncate text-content-on-surface-primary',
            props.isActive ? 'body-14-medium' : 'body-14-regular',
          )
        "
      >
        {{ props.label }}
      </span>

      <div
        v-if="props.shortcut || $slots['end-icon']"
        class="flex shrink-0 items-center gap-2"
      >
        <span
          v-if="props.shortcut"
          class="body-14-regular text-content-on-surface-muted"
        >
          {{ props.shortcut }}
        </span>
        <span
          v-if="$slots['end-icon']"
          class="flex shrink-0 items-center justify-center text-content-on-surface-muted"
        >
          <slot name="end-icon" />
        </span>
      </div>
    </Primitive>
  </div>
</template>
