import { ref } from "vue";

type TabbedSection = {
  key: string;
  tabGroup: string | null;
  [key: string]: unknown;
};

export type TabContentItem<S extends TabbedSection> =
  | { type: "section"; section: S }
  | { type: "tab-group"; groupKey: string; sections: S[] };

export function useTabGroups<S extends TabbedSection>() {
  const activeTabPerGroup = ref<Record<string, string>>({});

  function buildContentItems(sections: S[]): TabContentItem<S>[] {
    const result: TabContentItem<S>[] = [];
    let i = 0;

    while (i < sections.length) {
      const s = sections[i];

      if (s.tabGroup) {
        const groupKey = s.tabGroup;
        const group: S[] = [];

        while (i < sections.length && sections[i].tabGroup === groupKey) {
          group.push(sections[i]);
          i++;
        }

        if (!activeTabPerGroup.value[groupKey] && group.length > 0) {
          activeTabPerGroup.value[groupKey] = group[0].key;
        }

        result.push({ type: "tab-group", groupKey, sections: group });
      } else {
        result.push({ type: "section", section: s });
        i++;
      }
    }

    return result;
  }

  return { activeTabPerGroup, buildContentItems };
}
