import { defineTrait } from '../define.js';

export const rovingTabindex = defineTrait({
  name: 'roving-tabindex',
  category: 'keyboard-navigation',
  description: 'Focus management within composite widgets',
  attributes: [],
  events: [],
  config: [],
  setup({ host }) {
    let activeIndex = 0;

    function getFocusableChildren() {
      return [...host.children].filter(
        (el) => !el.hasAttribute('disabled') && el.offsetParent !== null,
      );
    }

    function updateTabindices(items) {
      for (let i = 0; i < items.length; i++) {
        items[i].setAttribute('tabindex', i === activeIndex ? '0' : '-1');
      }
    }

    function onKeyDown(e) {
      const items = getFocusableChildren();
      if (items.length === 0) return;

      let nextIndex = activeIndex;

      if (e.key === 'ArrowDown' || e.key === 'ArrowRight') {
        e.preventDefault();
        nextIndex = (activeIndex + 1) % items.length;
      } else if (e.key === 'ArrowUp' || e.key === 'ArrowLeft') {
        e.preventDefault();
        nextIndex = (activeIndex - 1 + items.length) % items.length;
      } else if (e.key === 'Home') {
        e.preventDefault();
        nextIndex = 0;
      } else if (e.key === 'End') {
        e.preventDefault();
        nextIndex = items.length - 1;
      } else {
        return;
      }

      activeIndex = nextIndex;
      updateTabindices(items);
      items[activeIndex].focus();
    }

    // Initialize
    const items = getFocusableChildren();
    if (items.length > 0) {
      updateTabindices(items);
    }

    host.addEventListener('keydown', onKeyDown);

    return () => {
      host.removeEventListener('keydown', onKeyDown);
      // Restore tabindex on children
      const items = getFocusableChildren();
      for (const item of items) {
        item.removeAttribute('tabindex');
      }
    };
  },
});
