<script setup lang="ts">
import { computed, useAttrs } from 'vue';
import { SidebarMenuButton } from '@/components/core/sidebar';
import { UiIcon } from '@/components/UiIcon';
import { ACTIVE_INDICATOR_CLASS } from '@/lib/activeIndicator';
import { cn, omitClass } from '@/lib/utils';
import type { UiSidebarPopoverTriggerProps } from './types';

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

const props = withDefaults(defineProps<UiSidebarPopoverTriggerProps>(), {
  tooltip: '',
  isActive: false,
});

const attrs = useAttrs();

const containerClass = computed(() =>
  cn(
    'relative flex w-full min-w-0 items-center gap-2 rounded-md border border-transparent transition-colors',
    'group-data-[collapsible=icon]:size-8 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:gap-0',
    'has-[:focus-visible]:border-border-surface-focus-ring has-[:focus-visible]:ring-[3px] has-[:focus-visible]:ring-ring/50',
    // Row hover/active fill for transparent sidebar triggers.
    'hover:bg-background-surface-muted-subtle data-[active=true]:bg-background-surface-muted-subtle',
    ACTIVE_INDICATOR_CLASS,
  ),
);

const rootClass = computed(() =>
  cn(
    '!rounded-md !px-2 !py-2 text-content-on-surface-primary',
    props.isActive ? 'body-14-medium' : 'body-14-regular',
    '!hover:bg-transparent !active:bg-transparent',
    'data-[active=true]:!bg-transparent data-[active=true]:!text-content-on-surface-primary',
    '[&>[data-slot=start-icon]]:shrink-0',
    '[&>[data-slot=label]]:min-w-0 [&>[data-slot=label]]:truncate',
    'focus-visible:ring-0',
    attrs.class as string | undefined,
  ),
);

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

<template>
  <div :data-active="props.isActive" :class="containerClass">
    <SidebarMenuButton
      v-bind="passthroughAttrs"
      :tooltip="props.tooltip"
      :is-active="props.isActive"
      :class="cn(rootClass, 'min-w-0 flex-1')"
    >
      <div data-slot="start-icon">
        <slot name="icon">
          <div
            class="flex size-6 items-center justify-center rounded-md border border-border-surface-default bg-background-surface-primary text-content-on-surface-primary"
          >
            <UiIcon name="panel-left" size="s" />
          </div>
        </slot>
      </div>

      <span data-slot="label">
        {{ props.label }}
      </span>

      <div class="ml-auto shrink-0 group-data-[collapsible=icon]:hidden">
        <slot name="end-icon">
          <UiIcon name="chevron-down" size="s" />
        </slot>
      </div>
    </SidebarMenuButton>
  </div>
</template>
