---
/**
 * Tabs Component
 * Accessible tabbed interface with keyboard navigation
 *
 * Usage:
 * <Tabs tabs={[{ id: 'tab1', label: 'Tab 1' }, { id: 'tab2', label: 'Tab 2' }]}>
 *   <div data-tab-content="tab1">Content for tab 1</div>
 *   <div data-tab-content="tab2">Content for tab 2</div>
 * </Tabs>
 */
import { cn } from '@/lib/cn';

interface Tab {
  id: string;
  label: string;
}

interface Props {
  tabs: Tab[];
  defaultValue?: string;
  class?: string;
}

const { tabs, defaultValue = tabs[0]?.id, class: className } = Astro.props;
---

<div class={cn('w-full', className)} data-tabs data-default={defaultValue}>
  <!-- Tab List -->
  <div class="flex border-b border-border" role="tablist" aria-label="Tabs">
    {tabs.map((tab) => (
      <button
        type="button"
        role="tab"
        id={`tab-${tab.id}`}
        aria-selected={tab.id === defaultValue ? 'true' : 'false'}
        aria-controls={`panel-${tab.id}`}
        tabindex={tab.id === defaultValue ? 0 : -1}
        class={cn(
          'px-4 py-2.5 text-sm font-medium -mb-px border-b-2 transition-colors',
          'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
          tab.id === defaultValue
            ? 'border-foreground text-foreground'
            : 'border-transparent text-foreground-muted hover:text-foreground hover:border-border'
        )}
        data-tab-trigger={tab.id}
      >
        {tab.label}
      </button>
    ))}
  </div>

  <!-- Tab Panels Container -->
  <div class="mt-4 tabs-content">
    <slot />
  </div>
</div>

<script>
  function initTabs() {
    const tabContainers = document.querySelectorAll<HTMLElement>('[data-tabs]');
    tabContainers.forEach((container) => {
      if (container.dataset.tabsInit) return;
      container.dataset.tabsInit = 'true';

      const triggers = container.querySelectorAll<HTMLButtonElement>('[data-tab-trigger]');
      const contentElements = container.querySelectorAll<HTMLElement>('[data-tab-content]');
      const defaultTab = container.getAttribute('data-default');

      contentElements.forEach((el) => {
        const tabId = el.getAttribute('data-tab-content');
        if (tabId !== defaultTab) {
          el.classList.add('hidden');
        }
        el.setAttribute('role', 'tabpanel');
        el.setAttribute('id', `panel-${tabId}`);
        el.setAttribute('aria-labelledby', `tab-${tabId}`);
        el.setAttribute('tabindex', '0');
      });

      function activateTab(id: string) {
        triggers.forEach((trigger) => {
          const isActive = trigger.getAttribute('data-tab-trigger') === id;
          trigger.setAttribute('aria-selected', String(isActive));
          trigger.setAttribute('tabindex', isActive ? '0' : '-1');

          if (isActive) {
            trigger.classList.add('border-foreground', 'text-foreground');
            trigger.classList.remove('border-transparent', 'text-foreground-muted');
          } else {
            trigger.classList.remove('border-foreground', 'text-foreground');
            trigger.classList.add('border-transparent', 'text-foreground-muted');
          }
        });

        contentElements.forEach((el) => {
          const isActive = el.getAttribute('data-tab-content') === id;
          if (isActive) {
            el.classList.remove('hidden');
            el.classList.add('animate-tab-enter');
            el.addEventListener('animationend', () => {
              el.classList.remove('animate-tab-enter');
            }, { once: true });
          } else {
            el.classList.add('hidden');
            el.classList.remove('animate-tab-enter');
          }
        });
      }

      triggers.forEach((trigger) => {
        trigger.addEventListener('click', () => {
          const id = trigger.getAttribute('data-tab-trigger');
          if (id) activateTab(id);
        });

        trigger.addEventListener('keydown', (e) => {
          const triggersArray = Array.from(triggers);
          const currentIndex = triggersArray.indexOf(trigger);
          let newIndex = currentIndex;

          switch (e.key) {
            case 'ArrowLeft':
              newIndex = currentIndex > 0 ? currentIndex - 1 : triggersArray.length - 1;
              break;
            case 'ArrowRight':
              newIndex = currentIndex < triggersArray.length - 1 ? currentIndex + 1 : 0;
              break;
            case 'Home':
              newIndex = 0;
              break;
            case 'End':
              newIndex = triggersArray.length - 1;
              break;
            default:
              return;
          }

          e.preventDefault();
          const newTrigger = triggersArray[newIndex];
          const id = newTrigger.getAttribute('data-tab-trigger');
          if (id) {
            activateTab(id);
            newTrigger.focus();
          }
        });
      });
    });
  }

  initTabs();
  document.addEventListener('astro:page-load', initTabs);
</script>

<style>
  .tabs-content > :global([data-tab-content]) {
    outline: none;
    border-radius: var(--radius-md);
  }
  .tabs-content > :global([data-tab-content]:focus-visible) {
    outline: 2px solid var(--ring);
    outline-offset: 2px;
  }
</style>
