<script>"use strict";
import Tab from "./Tab.svelte";
import { afterUpdate, onMount, createEventDispatcher } from "svelte";
const dispatch = createEventDispatcher();
export let tabs = [];
export let activeTabIndex = 0;
let tabUnderlineWidth = 0;
let tabUnderlineLeft = 0;
let tabsRef = [];
function setActiveTab(index) {
  activeTabIndex = index;
  setTabPosition();
  dispatch("change", { activeTabIndex: index });
}
function setTabPosition() {
  const currentTab = tabsRef[activeTabIndex];
  if (currentTab) {
    tabUnderlineLeft = currentTab?.offsetLeft ?? 0;
    tabUnderlineWidth = currentTab?.offsetWidth ?? 0;
  }
}
function handleTabMounted(event) {
  tabsRef.push(event.detail.element);
  setTabPosition();
}
onMount(() => {
  setTimeout(() => {
    setTabPosition();
  }, 100);
  window.addEventListener("resize", setTabPosition);
  return () => window.removeEventListener("resize", setTabPosition);
});
afterUpdate(async () => {
  setTabPosition();
});
</script>

<div class="relative border-b border-stone-300">
	<div class="flex">
		{#each tabs as tab, index}
			<Tab
				on:tabMounted={handleTabMounted}
				label={tab.label}
				icon={tab?.icon}
				disabled={tab?.disabled}
				isActive={index === activeTabIndex}
				onClick={() => setActiveTab(index)}
				badge={tab?.badge}
			/>
		{/each}
	</div>
	<span
		class="absolute bottom-[-1px] h-[1px] bg-stone-700 transition-all duration-300 ease-in-out"
		style="width: {tabUnderlineWidth}px; left: {tabUnderlineLeft}px;"
	/>
</div>
