<template>
  <button
    role="tab"
    :id="'tab-' + id"
    :aria-selected="isActive.toString()"
    :aria-controls="ariaControls"
    :disabled="disabled"
    :tabindex="isActive ? 0 : -1"
    @click="handleClick"
    class="tab-item"
    :class="{ 'active': isActive, 'disabled': disabled }"
  >
    <slot>{{ title }}</slot>
  </button>
</template>

<script lang="ts" setup>
import { computed, inject } from 'vue';
import type { TabId, TabsContext } from './types';
import { TabsProviderKey } from './types';

const props = defineProps<{
  id: TabId;
  title?: string;
  disabled?: boolean;
}>();

defineOptions({
  name: 'VTab',
});

const tabsContext = inject<TabsContext>(TabsProviderKey);

if (!tabsContext) {
  throw new Error('VTab must be used within a VTabs component.');
}

const { activeTabId, selectTab } = tabsContext;

const isActive = computed(() => activeTabId.value === props.id);
const ariaControls = computed(() => `panel-${props.id}`);

const handleClick = () => {
  if (!props.disabled) {
    selectTab(props.id);
  }
};
</script>

<style lang="scss" scoped>
.tab-item {
  padding: 0.75rem 1.25rem; // Example padding
  margin-bottom: -1px; // Overlap with tab-list border for active state
  border: 1px solid transparent;
  border-top-left-radius: 0.25rem;
  border-top-right-radius: 0.25rem;
  cursor: pointer;
  background-color: transparent;
  color: #007bff; // Default tab text color (link-like)
  font-size: 1rem;
  font-weight: 500;
  text-align: center;
  transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out;

  &:hover:not(.disabled):not(.active) {
    border-color: #e9ecef #e9ecef #dee2e6; // Light border on hover
    background-color: #f8f9fa; // Light background on hover
    color: #0056b3;
  }

  &.active { // Or use [aria-selected="true"]
    color: #495057; // Active tab text color
    background-color: #fff; // Active tab background (same as panel usually)
    border-color: #dee2e6 #dee2e6 #fff; // Border connects with panel, bottom border transparent
  }

  &.disabled { // Or use [disabled]
    color: #6c757d; // Disabled text color
    cursor: not-allowed;
    background-color: transparent;
    border-color: transparent;
  }

  &:focus {
    outline: none; // Remove default outline
    // Add custom focus style if needed, e.g., box-shadow
    // For accessibility, ensure focus is visible.
    // box-shadow: 0 0 0 0.1rem rgba(0, 123, 255, 0.25); // Example focus ring
  }

  // Better focus visibility, especially for keyboard navigation
  &:focus-visible:not(.disabled) {
     outline: 2px solid #007bff; // Standard outline
     outline-offset: 2px;
     // Or use box-shadow for a softer focus ring:
     // box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.35);
  }
}
</style>
