<?php
if (!empty($global)) {
    echo $global;
}

if (empty($tab_style) && !empty($all_tabs) && isset($all_tabs['_meta']['tab_style'])) {
	$tab_style = $all_tabs['_meta']['tab_style'];
}
$tab_style = isset($tab_style) ? $tab_style : config_item('tab_style');
if (empty($tab_style)) {
    $tab_style = 'pills';
}

if (is_numeric($tab_style)) {
	$style_map = array('1' => 'pills', '2' => 'underline', '3' => 'stacked', '4' => 'segmented', '5' => 'card');
	$tab_style = isset($style_map[$tab_style]) ? $style_map[$tab_style] : 'pills';
}
$tabs_wrapper_class = isset($tabs_wrapper_class) ? $tabs_wrapper_class : '';
$tabs_nav_class = isset($tabs_nav_class) ? $tabs_nav_class : '';
$tabs_panel_class = isset($tabs_panel_class) ? $tabs_panel_class : '';

function tab_classes($style, $active)
{
    $base = 'inline-flex items-center gap-2 text-sm font-medium transition whitespace-nowrap shrink-0';
    switch ($style) {
        case 'underline':
            return $base . ' px-1.5 py-2 border-b-2 ' . ($active ? 'border-slate-900 text-slate-900 dark:border-slate-100 dark:text-slate-100' : 'border-transparent text-slate-500 hover:text-slate-900 dark:text-slate-300 dark:hover:text-slate-100');
        case 'stacked':
            return $base . ' w-full justify-between rounded-lg px-3 py-2 ' . ($active ? 'bg-slate-900 text-white' : 'text-slate-600 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-900');
        case 'segmented':
            return $base . ' px-4 py-2 rounded-md ' . ($active ? 'bg-white text-slate-900 shadow-sm dark:bg-slate-800 dark:text-slate-100' : 'text-slate-500 hover:text-slate-900 dark:text-slate-300 dark:hover:text-slate-100');
        case 'card':
            return $base . ' px-3 py-2 rounded-lg border ' . ($active ? 'border-slate-300 text-slate-900 dark:border-slate-600 dark:text-slate-100 bg-white dark:bg-slate-800' : 'border-transparent text-slate-500 hover:border-slate-200 dark:hover:border-slate-700 dark:text-slate-300');
        case 'pills':
        default:
            return $base . ' rounded-lg px-3 py-2 ' . ($active ? 'bg-slate-900 text-white hover:bg-slate-800 dark:hover:bg-slate-900' : 'text-slate-600 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-900');
    }
}

function tab_icon($name)
{
	if (empty($name)) {
		return '';
	}
	return '<i data-lucide="' . html_escape($name) . '" class="h-4 w-4"></i>';
}

function tab_is_active($key, $tab, $active)
{
	if ($active === $key) {
		return true;
	}
	if (!empty($tab['children']) && is_array($tab['children'])) {
		foreach ($tab['children'] as $child_key => $child) {
			if ($active === $child_key) {
				return true;
			}
		}
	}
	return false;
}
?>

<div class="<?= trim('mt-2 max-w-full min-w-0 space-y-2 ' . $tabs_wrapper_class) ?>">
    <style>
        .tab-scroll-area::-webkit-scrollbar {
            display: none;
        }
    </style>
    <?php if ($tab_style === 'stacked') { ?>
        <div class="grid max-w-full min-w-0 gap-6 md:grid-cols-[220px_minmax(0,1fr)]">
            <div class="<?= trim('rounded-lg border border-border bg-card p-4 shadow-sm ' . $tabs_nav_class) ?>">
                <div class="space-y-2">
                    <?php if (!empty($all_tabs)) {
                        foreach ($all_tabs as $key => $v_tab) {
                            if (!is_array($v_tab) || empty($v_tab['name'])) {
                                continue;
                            }
                            $is_active = tab_is_active($key, $v_tab, $active);
                            $has_children = isset($v_tab['children']) && is_array($v_tab['children']);
                            ?>
                            <?php if ($has_children) { ?>
                                <details class="rounded-lg border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900" <?= $is_active ? 'open' : '' ?>>
                                    <summary class="flex cursor-pointer items-center justify-between px-3 py-2 text-sm font-medium text-slate-700 dark:text-slate-200">
                                        <span class="flex items-center gap-2">
                                            <?= tab_icon(isset($v_tab['icon']) ? $v_tab['icon'] : '') ?>
                                            <?= lang($v_tab['name']) ?>
                                        </span>
                                        <i data-lucide="chevron-down" class="h-4 w-4"></i>
                                    </summary>
                                    <div class="space-y-1 p-2">
                                        <?php foreach ($v_tab['children'] as $child_key => $child) { ?>
                                            <?php $child_active = ($active == $child_key); ?>
                                            <a href="<?= base_url($child['url']) ?>" class="<?= tab_classes($tab_style, $child_active) ?>">
                                                <span class="flex items-center gap-2">
                                                    <?= tab_icon(isset($child['icon']) ? $child['icon'] : '') ?>
                                                    <?= lang($child['name']) ?>
                                                </span>
                                            </a>
                                        <?php } ?>
                                    </div>
                                </details>
                            <?php } else { ?>
                                <a href="<?= base_url($v_tab['url']) ?>" class="<?= tab_classes($tab_style, $is_active) ?>">
                                    <span class="flex items-center gap-2">
                                        <?= tab_icon(isset($v_tab['icon']) ? $v_tab['icon'] : '') ?>
                                        <span><?= lang($v_tab['name']) ?></span>
                                    </span>
                                    <?php if (!empty($v_tab['count'])) { ?>
                                        <span class="inline-flex items-center rounded-full bg-slate-200 px-2 py-0.5 text-xs font-semibold text-slate-600 dark:bg-slate-700 dark:text-slate-300">
                                            <?= $v_tab['count'] ?>
                                        </span>
                                    <?php } ?>
                                </a>
                            <?php } ?>
                        <?php }
                    } ?>
                </div>
            </div>
            <div class="<?= trim('min-w-0 overflow-hidden rounded-xl border border-border bg-card p-4 shadow-sm ' . $tabs_panel_class) ?>">
                <?php
                $view = tab_load_view($all_tabs, $active);
                $this->load->view($view);
                ?>
            </div>
        </div>
    <?php } else { ?>
        <div class="<?= trim('max-w-full min-w-0 rounded-lg border border-border bg-card p-4 shadow-sm ' . $tabs_nav_class) ?>">
            <div class="relative flex min-w-0 items-center gap-2">
                <button type="button" class="tab-scroll-left flex hidden h-9 w-9 items-center justify-center rounded-lg border border-slate-200 bg-white text-slate-500 hover:bg-slate-50 dark:bg-slate-700 dark:border-slate-700">
                    <i data-lucide="chevron-left" class="h-4 w-4 dark:stroke-slate-200"></i>
                </button>
                <div class="tab-scroll-area min-w-0 flex-1 overflow-x-auto scroll-smooth" style="scrollbar-width: none; overflow-y: visible;">
                    <div class="<?= $tab_style === 'segmented' ? 'inline-flex rounded-xl bg-slate-100 p-1 dark:bg-slate-900 dark:ring-1 dark:ring-slate-800' : 'flex flex-nowrap items-center gap-2' ?>">
                <?php if (!empty($all_tabs)) {
                    foreach ($all_tabs as $key => $v_tab) {
                        if (!is_array($v_tab) || empty($v_tab['name'])) {
                            continue;
                        }
                        $is_active = tab_is_active($key, $v_tab, $active);
                        $has_children = isset($v_tab['children']) && is_array($v_tab['children']);
                        ?>
                        <?php if ($has_children) { ?>
                            <div class="relative shrink-0" data-tab-dropdown>
                                <button type="button" class="<?= tab_classes($tab_style, $is_active) ?>" data-tab-dropdown-trigger aria-expanded="<?= $is_active ? 'true' : 'false' ?>" <?= $is_active ? 'data-tab-active="true"' : '' ?>>
                                    <?= tab_icon(isset($v_tab['icon']) ? $v_tab['icon'] : '') ?>
                                    <span class="max-w-[140px] truncate"><?= lang($v_tab['name']) ?></span>
                                    <i data-lucide="chevron-down" class="h-4 w-4"></i>
                                </button>
                                <div class="hidden absolute right-0 top-[calc(100%+0.5rem)] z-30 w-56 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-6rem)] overflow-y-auto rounded-xl border border-border bg-card p-2 shadow-lg" data-tab-dropdown-menu>
                                    <?php foreach ($v_tab['children'] as $child_key => $child) { ?>
                                        <?php $child_active = ($active == $child_key); ?>
                                        <a href="<?= base_url($child['url']) ?>" class="flex items-center gap-2 rounded-lg px-3 py-2 text-xs transition-colors hover:bg-muted <?= $child_active ? 'bg-muted text-foreground' : 'text-foreground' ?>" <?= $child_active ? 'data-tab-active="true"' : '' ?>>
                                            <?= tab_icon(isset($child['icon']) ? $child['icon'] : '') ?>
                                            <span><?= lang($child['name']) ?></span>
                                        </a>
                                    <?php } ?>
                                </div>
                            </div>
                        <?php } else { ?>
                            <a href="<?= base_url($v_tab['url']) ?>" class="<?= tab_classes($tab_style, $is_active) ?>" <?= $is_active ? 'data-tab-active="true"' : '' ?>>
                                <?= tab_icon(isset($v_tab['icon']) ? $v_tab['icon'] : '') ?>
                                <span><?= lang($v_tab['name']) ?></span>
                                <?php if (!empty($v_tab['count'])) { ?>
                                    <span class="inline-flex items-center rounded-full bg-slate-200 px-2 py-0.5 text-xs font-semibold text-slate-600 dark:bg-slate-700 dark:text-slate-300">
                                        <?= $v_tab['count'] ?>
                                    </span>
                                <?php } ?>
                            </a>
                        <?php } ?>
                    <?php }
                } ?>
                    </div>
                </div>
                <button type="button" class="tab-scroll-right flex hidden h-9 w-9 items-center justify-center rounded-lg border border-slate-200 bg-white text-slate-500 hover:bg-slate-50 dark:bg-slate-700 dark:border-slate-700">
                    <i data-lucide="chevron-right" class="h-4 w-4 dark:stroke-slate-200"></i>
                </button>
            </div>
        </div>

        <div class="<?= trim('min-w-0 overflow-hidden rounded-2xl border border-border bg-card p-4 shadow-sm md:p-6 ' . $tabs_panel_class) ?>">
            <?php
            $view = tab_load_view($all_tabs, $active);
            $this->load->view($view);
            ?>
        </div>
    <?php } ?>
</div>

<script>
    (function () {
        const wrapper = document.currentScript && document.currentScript.parentElement;
        if (!wrapper) return;
        const scrollArea = wrapper.querySelector('.tab-scroll-area');
        const btnLeft = wrapper.querySelector('.tab-scroll-left');
        const btnRight = wrapper.querySelector('.tab-scroll-right');
        if (!scrollArea || !btnLeft || !btnRight) return;

        function updateButtons() {
            const maxScroll = scrollArea.scrollWidth - scrollArea.clientWidth;
            const atStart = scrollArea.scrollLeft <= 0;
            const atEnd = scrollArea.scrollLeft >= maxScroll - 1;
            btnLeft.classList.toggle('hidden', atStart || maxScroll <= 0);
            btnRight.classList.toggle('hidden', atEnd || maxScroll <= 0);
        }

        btnLeft.addEventListener('click', function () {
            scrollArea.scrollBy({ left: -220, behavior: 'smooth' });
        });
        btnRight.addEventListener('click', function () {
            scrollArea.scrollBy({ left: 220, behavior: 'smooth' });
        });
        scrollArea.addEventListener('scroll', function () {
            updateButtons();
            if (activeDropdown) {
                positionDropdown(activeDropdown);
            }
        });
        window.addEventListener('resize', function () {
            updateButtons();
            if (activeDropdown) {
                positionDropdown(activeDropdown);
            }
        });

        let hoverTimer = null;
        function startHoverScroll(direction) {
            if (hoverTimer) return;
            hoverTimer = setInterval(function () {
                scrollArea.scrollBy({ left: direction * 18, behavior: 'auto' });
            }, 16);
        }
        function stopHoverScroll() {
            if (hoverTimer) {
                clearInterval(hoverTimer);
                hoverTimer = null;
            }
        }
        btnLeft.addEventListener('mouseenter', function () { startHoverScroll(-1); });
        btnRight.addEventListener('mouseenter', function () { startHoverScroll(1); });
        btnLeft.addEventListener('mouseleave', stopHoverScroll);
        btnRight.addEventListener('mouseleave', stopHoverScroll);

        wrapper.querySelectorAll('details > summary').forEach(function (summary) {
            summary.addEventListener('click', function (e) {
                e.preventDefault();
                const details = summary.parentElement;
                const nextState = !details.open;
                wrapper.querySelectorAll('details').forEach(function (other) {
                    if (other !== details) {
                        other.removeAttribute('open');
                    }
                });
                if (nextState) {
                    details.setAttribute('open', 'open');
                } else {
                    details.removeAttribute('open');
                }
            });
        });

        const dropdowns = Array.from(wrapper.querySelectorAll('[data-tab-dropdown]'));
        let activeDropdown = null;

        function closeDropdown(dropdown) {
            if (!dropdown) return;
            const trigger = dropdown.querySelector('[data-tab-dropdown-trigger]');
            const menu = dropdown.querySelector('[data-tab-dropdown-menu]');
            if (menu) {
                menu.classList.add('hidden');
                menu.style.position = '';
                menu.style.top = '';
                menu.style.left = '';
                menu.style.right = '';
                menu.style.zIndex = '';
            }
            if (trigger) {
                trigger.setAttribute('aria-expanded', 'false');
            }
            if (activeDropdown === dropdown) {
                activeDropdown = null;
            }
        }

        function openDropdown(dropdown) {
            if (!dropdown) return;
            if (activeDropdown && activeDropdown !== dropdown) {
                closeDropdown(activeDropdown);
            }
            const trigger = dropdown.querySelector('[data-tab-dropdown-trigger]');
            const menu = dropdown.querySelector('[data-tab-dropdown-menu]');
            if (menu) {
                menu.classList.remove('hidden');
                positionDropdown(dropdown);
            }
            if (trigger) {
                trigger.setAttribute('aria-expanded', 'true');
            }
            activeDropdown = dropdown;
        }

        function positionDropdown(dropdown) {
            const trigger = dropdown.querySelector('[data-tab-dropdown-trigger]');
            const menu = dropdown.querySelector('[data-tab-dropdown-menu]');
            if (!trigger || !menu || menu.classList.contains('hidden')) return;

            const triggerRect = trigger.getBoundingClientRect();
            const menuWidth = Math.min(menu.offsetWidth || 224, window.innerWidth - 16);
            const left = Math.max(8, Math.min(triggerRect.right - menuWidth, window.innerWidth - menuWidth - 8));

            menu.style.position = 'fixed';
            menu.style.top = (triggerRect.bottom + 8) + 'px';
            menu.style.left = left + 'px';
            menu.style.right = 'auto';
            menu.style.zIndex = '60';
        }

        dropdowns.forEach(function (dropdown) {
            const trigger = dropdown.querySelector('[data-tab-dropdown-trigger]');
            if (!trigger) return;
            trigger.addEventListener('click', function (e) {
                e.preventDefault();
                e.stopPropagation();
                if (activeDropdown === dropdown) {
                    closeDropdown(dropdown);
                } else {
                    openDropdown(dropdown);
                }
            });
        });

        document.addEventListener('click', function (e) {
            if (!activeDropdown) return;
            if (!activeDropdown.contains(e.target)) {
                closeDropdown(activeDropdown);
            }
        });

        document.addEventListener('keydown', function (e) {
            if (e.key === 'Escape' && activeDropdown) {
                closeDropdown(activeDropdown);
            }
        });

        const activeEl = wrapper.querySelector('[data-tab-active="true"]');
        if (activeEl) {
            activeEl.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
        }
        updateButtons();
    })();
</script>
