<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<?php
$header_title = isset($page_title) && $page_title !== '' ? $page_title : (isset($title) && $title !== '' ? $title : 'Dashboard');
$header_description = isset($page_description) ? $page_description : 'Overview of your business performance';
$header_badge = isset($header_badge) ? $header_badge : null;
$header_badge_html = isset($header_badge_html) ? $header_badge_html : (isset($page_meta) ? $page_meta : '');
$header_actions = isset($header_actions) ? $header_actions : null;
$header_actions_html = isset($header_actions_html) ? $header_actions_html : '';
$header_view_toggle = isset($header_view_toggle) && is_array($header_view_toggle) ? $header_view_toggle : array();
$header_filters = isset($header_filters) && is_array($header_filters) ? $header_filters : array();
$header_filter_extras_html = isset($header_filter_extras_html) ? $header_filter_extras_html : '';
$header_search = isset($header_search) && is_array($header_search) ? $header_search : array();
$header_tools = isset($header_tools) && is_array($header_tools) ? $header_tools : array();
$header_date_label = isset($header_date_label) ? $header_date_label : 'Today';
$header_notification_count = isset($unread_notifications) ? (int) $unread_notifications : 0;
$header_notifications_endpoint = base_url('admin/common/header_notifications');
$header_notifications_mark_all_endpoint = base_url('admin/common/mark_all_as_read');
$header_notifications_item_endpoint = base_url('admin/common/mark_desktop_notification_as_read');

$normalize_attrs = function ($attrs) {
    if (empty($attrs) || !is_array($attrs)) {
        return '';
    }
    $parts = array();
    foreach ($attrs as $key => $value) {
        if ($value === null || $value === false) {
            continue;
        }
        if ($value === true) {
            $parts[] = html_escape($key);
            continue;
        }
        $parts[] = html_escape($key) . '="' . html_escape($value) . '"';
    }
    return !empty($parts) ? ' ' . implode(' ', $parts) : '';
};

$has_active_child = function ($items) use (&$has_active_child) {
    if (empty($items) || !is_array($items)) {
        return false;
    }
    foreach ($items as $item) {
        if (!empty($item['active'])) {
            return true;
        }
        if (!empty($item['items']) && $has_active_child($item['items'])) {
            return true;
        }
    }
    return false;
};

$render_badge = function ($badge) {
    if (empty($badge)) {
        return '';
    }
    $tone_map = array(
        'neutral' => 'border-slate-200 bg-slate-50 text-slate-700 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-200',
        'primary' => 'border-indigo-200 bg-indigo-50 text-indigo-700 dark:border-indigo-800 dark:bg-indigo-900/30 dark:text-indigo-300',
		'info' => 'border-sky-200 bg-sky-50 text-sky-700 dark:border-sky-800 dark:bg-sky-900/30 dark:text-sky-300',
        'success' => 'border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-800 dark:bg-emerald-900/30 dark:text-emerald-300',
        'warning' => 'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-800 dark:bg-amber-900/30 dark:text-amber-300',
        'danger' => 'border-rose-200 bg-rose-50 text-rose-700 dark:border-rose-800 dark:bg-rose-900/30 dark:text-rose-300',
		'dark' => 'border-gray-600 bg-gray-700 text-white',
		'secondary' => 'border-gray-300 bg-gray-100 text-gray-800 dark:border-gray-600 dark:bg-gray-700 dark:text-white',

    );
    $tone = isset($tone_map[$badge['tone'] ?? '']) ? $tone_map[$badge['tone']] : $tone_map['neutral'];
    $label = isset($badge['label']) ? $badge['label'] : '';
    if ($label === '') {
        return '';
    }
    return '<span class="inline-flex items-center gap-1 rounded-full border px-2.5 px-3 py-1.5 text-xs font-semibold tracking-[0.16em] uppercase ' . $tone . '">' . html_escape($label) . '</span>';
};

$render_action_button = function ($action) use ($normalize_attrs) {
    if (!is_array($action)) {
        return '';
    }
    $label = isset($action['label']) ? $action['label'] : '';
    if ($label === '') {
        return '';
    }
    $icon = isset($action['icon']) ? $action['icon'] : '';
    $href = isset($action['href']) ? $action['href'] : '';
    $type = isset($action['type']) ? $action['type'] : 'button';
    $style = isset($action['style']) ? $action['style'] : 'default';
    $active = !empty($action['active']);
    $attrs = isset($action['attrs']) && is_array($action['attrs']) ? $action['attrs'] : array();

    $base = 'inline-flex h-9 items-center justify-center gap-2 whitespace-nowrap rounded-lg border px-3 text-xs font-semibold leading-none shadow-sm transition-colors';
    $styles = array(
        'default' => 'border-slate-200 bg-white text-slate-700 hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 dark:hover:bg-slate-800',
        'primary' => 'border-violet-600 bg-violet-600 text-white hover:bg-violet-500 dark:border-violet-500 dark:bg-violet-500 dark:hover:bg-violet-400',
		'info' => 'border-sky-200 bg-sky-50 text-sky-700 hover:bg-sky-100 dark:border-sky-800 dark:bg-sky-900/30 dark:text-sky-300 dark:hover:bg-sky-900/40',
        'danger' => 'border-rose-200 bg-rose-50 text-rose-700 hover:bg-rose-100 dark:border-rose-800 dark:bg-rose-900/20 dark:text-rose-300 dark:hover:bg-rose-900/30',
        'success' => 'border-emerald-200 bg-emerald-50 text-emerald-700 hover:bg-emerald-100 dark:border-emerald-800 dark:bg-emerald-900/20 dark:text-emerald-300 dark:hover:bg-emerald-900/30',
        'ghost' => 'border-transparent bg-transparent text-slate-600 shadow-none hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800',
		'warning' => 'border-amber-200 bg-amber-50 text-amber-700 hover:bg-amber-100 dark:border-amber-800 dark:bg-amber-900/30 dark:text-amber-300 dark:hover:bg-amber-900/40',
		'neutral' => 'border-slate-200 bg-slate-50 text-slate-700 hover:bg-slate-100 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-200 dark:hover:bg-slate-700',
    );
    $style_class = isset($styles[$style]) ? $styles[$style] : $styles['default'];
    if ($active) {
        $style_class = 'border-violet-200 bg-violet-50 text-violet-700 dark:border-violet-800 dark:bg-violet-900/30 dark:text-violet-300';
    }
    $icon_html = $icon !== '' ? '<i data-lucide="' . html_escape($icon) . '" class="h-4 w-4 shrink-0"></i>' : '';
    $attrs_html = $normalize_attrs($attrs);

    if ($href !== '') {
        return '<a href="' . html_escape($href) . '" class="' . $base . ' ' . $style_class . '"' . $attrs_html . '>' . $icon_html . '<span>' . html_escape($label) . '</span></a>';
    }
    return '<button type="' . html_escape($type) . '" class="' . $base . ' ' . $style_class . '"' . $attrs_html . '>' . $icon_html . '<span>' . html_escape($label) . '</span></button>';
};

$render_toggle_button = function ($item) use ($normalize_attrs) {
    if (!is_array($item) || empty($item['label'])) {
        return '';
    }
    $active = !empty($item['active']);
    $icon = !empty($item['icon']) ? '<i data-lucide="' . html_escape($item['icon']) . '" class="h-4 w-4 shrink-0"></i>' : '';
    $attrs = !empty($item['attrs']) && is_array($item['attrs']) ? $item['attrs'] : array();
    $attrs_html = $normalize_attrs($attrs);
    $classes = 'inline-flex h-9 items-center justify-center gap-2 whitespace-nowrap rounded-lg border px-3 text-xs font-semibold leading-none transition-colors ';
    $classes .= $active
        ? 'border-indigo-600 bg-indigo-600 text-white shadow-sm dark:border-indigo-500 dark:bg-indigo-500'
        : 'border-border bg-white text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 dark:hover:bg-slate-800';

    if (!empty($item['href'])) {
        return '<a href="' . html_escape($item['href']) . '" class="' . $classes . '"' . $attrs_html . '>' . $icon . '<span>' . html_escape($item['label']) . '</span></a>';
    }
    return '<button type="button" class="' . $classes . '"' . $attrs_html . '>' . $icon . '<span>' . html_escape($item['label']) . '</span></button>';
};

$render_filter_items = function ($items, $level = 0) use (&$render_filter_items, $normalize_attrs, $has_active_child) {
    if (empty($items) || !is_array($items)) {
        return '';
    }
    $html = '';
    foreach ($items as $item) {
        if (!is_array($item) || empty($item['label'])) {
            continue;
        }
        $active = !empty($item['active']);
        $children_active = !empty($item['items']) && $has_active_child($item['items']);
        $row_classes = 'flex w-full items-center justify-between gap-3 rounded-xl px-3 py-2 text-left text-sm transition-colors ';
        $row_classes .= ($active || $children_active)
            ? 'bg-indigo-50 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300'
            : 'text-slate-700 hover:bg-slate-50 dark:text-slate-200 dark:hover:bg-slate-800';

        if (!empty($item['divider_before'])) {
            $html .= '<div class="my-1 border-t border-border dark:border-slate-700"></div>';
        }

        if (!empty($item['items']) && is_array($item['items'])) {
            $show_child_search = count($item['items']) >= 6 || !empty($item['lookup']);
            $lookup_config_json = !empty($item['lookup']) ? htmlspecialchars(json_encode($item['lookup'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8') : '';
            $html .= '<div class="group/header-submenu relative">';
            $html .= '<button type="button" class="' . $row_classes . '">';
            $html .= '<span class="flex items-center gap-2">';
            if (!empty($item['icon'])) {
                $html .= '<i data-lucide="' . html_escape($item['icon']) . '" class="h-4 w-4"></i>';
            }
            $html .= '<span>' . html_escape($item['label']) . '</span>';
            $html .= '</span>';
            $html .= '<i data-lucide="chevron-right" class="h-4 w-4 shrink-0"></i>';
            $html .= '</button>';
            $html .= '<div data-header-filter-submenu class="invisible absolute left-full top-0 z-20 ml-2 w-64 rounded-2xl border border-border bg-white p-2 opacity-0 shadow-2xl transition duration-150 group-hover/header-submenu:visible group-hover/header-submenu:opacity-100 group-focus-within/header-submenu:visible group-focus-within/header-submenu:opacity-100 dark:border-slate-700 dark:bg-slate-900">';
            if ($show_child_search) {
                $html .= '<div class="mb-2">';
                $html .= '<label class="relative block">';
                $html .= '<span class="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3 text-muted-foreground"><i data-lucide="search" class="h-4 w-4"></i></span>';
                $html .= '<input type="search" data-header-filter-search-input class="h-10 w-full rounded-xl border border-border bg-white pl-10 pr-3 text-sm text-foreground shadow-sm outline-none transition focus:border-primary/40 focus:ring-2 focus:ring-primary/10 dark:border-slate-700 dark:bg-slate-900" placeholder="' . html_escape(!empty($item['lookup']['placeholder']) ? $item['lookup']['placeholder'] : (lang('search') . '...')) . '">';
                $html .= '</label>';
                $html .= '</div>';
            }
            $html .= '<div class="max-h-72 space-y-1 overflow-y-auto" data-header-filter-search-list>';
            $html .= $render_filter_items($item['items'], $level + 1);
            if (!empty($item['lookup'])) {
                $html .= '<div class="space-y-1" data-header-filter-remote data-header-filter-remote-config="' . $lookup_config_json . '"></div>';
            }
            $html .= '</div>';
            if ($show_child_search) {
                $html .= '<div class="hidden rounded-xl border border-dashed border-border px-3 py-4 text-center text-sm text-muted-foreground dark:border-slate-700" data-header-filter-search-empty>' . html_escape(lang('no_data')) . '</div>';
            }
            $html .= '</div>';
            $html .= '</div>';
        } else {
            $attrs = !empty($item['attrs']) && is_array($item['attrs']) ? $item['attrs'] : array();
            $attrs['data-header-filter-item'] = '1';
            if (!empty($item['label'])) {
                $attrs['data-header-filter-item-label'] = $item['label'];
                $attrs['data-header-filter-search-text'] = $item['label'];
            }
            $attrs_html = $normalize_attrs($attrs);
            $content = '';
            if (!empty($item['href'])) {
                $content .= '<a href="' . html_escape($item['href']) . '" data-header-filter-search-item class="header-filter-item ' . $row_classes . '"' . $attrs_html . '>';
            } else {
                $content .= '<button type="button" data-header-filter-search-item class="header-filter-item ' . $row_classes . '"' . $attrs_html . '>';
            }
            $content .= '<span class="flex items-center gap-2">';
            if (!empty($item['icon'])) {
                $content .= '<i data-lucide="' . html_escape($item['icon']) . '" class="h-4 w-4"></i>';
            }
            $content .= '<span>' . html_escape($item['label']) . '</span>';
            $content .= '</span>';
            if (!empty($item['meta'])) {
                $content .= '<span class="text-xs font-medium text-muted-foreground">' . html_escape($item['meta']) . '</span>';
            }
            $content .= !empty($item['href']) ? '</a>' : '</button>';
            $html .= $content;
        }
    }
    return $html;
};

$render_filter_dropdown = function ($filter) use ($render_filter_items, $normalize_attrs) {
    if (!is_array($filter) || empty($filter['label'])) {
        return '';
    }
    $label = $filter['label'];
    $icon = !empty($filter['icon']) ? $filter['icon'] : 'sliders-horizontal';
    $active = !empty($filter['active']);
    $selected_label = !empty($filter['selected_label']) ? $filter['selected_label'] : '';
    $attrs = !empty($filter['attrs']) && is_array($filter['attrs']) ? $filter['attrs'] : array();
    $attrs_html = $normalize_attrs($attrs);
    $button_classes = 'inline-flex h-9 items-center justify-center gap-2 whitespace-nowrap rounded-lg border px-3 text-xs font-medium leading-none transition-colors ';
    $button_classes .= $active || $selected_label !== ''
        ? 'border-indigo-200 bg-indigo-50 text-indigo-700 dark:border-indigo-800 dark:bg-indigo-900/30 dark:text-indigo-300'
        : 'border-border bg-white text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 dark:hover:bg-slate-800';

    $html = '<details class="group relative"' . $attrs_html . '>';
    $html .= '<summary class="list-none cursor-pointer ' . $button_classes . '">';
    $html .= '<i data-lucide="' . html_escape($icon) . '" class="h-4 w-4 shrink-0"></i>';
    $html .= '<span>' . html_escape($label) . '</span>';
    if ($selected_label !== '') {
        $html .= '<span data-header-filter-selected class="rounded-full bg-white/80 px-1.5 py-0.5 text-[10px] font-semibold leading-none dark:bg-slate-800">' . html_escape($selected_label) . '</span>';
    }
    $html .= '<i data-lucide="chevron-down" class="h-4 w-4 shrink-0"></i>';
    $html .= '</summary>';
    $html .= '<div class="absolute right-0 z-50 mt-2 w-72 overflow-visible rounded-2xl border border-border bg-white p-2 shadow-2xl dark:border-slate-700 dark:bg-slate-900">';
    $html .= $render_filter_items(isset($filter['items']) ? $filter['items'] : array());
    $html .= '</div>';
    $html .= '</details>';
    return $html;
};
?>

<header class="sticky top-0 z-40 border-b border-border bg-background/90 backdrop-blur-xl">
    <div class="flex min-h-[54px] flex-col gap-2 px-4 py-2 sm:min-h-[60px] sm:flex-row sm:items-center sm:justify-between sm:gap-3 sm:px-5 sm:py-2.5">
        <div class="flex min-w-0 items-center gap-3 sm:gap-4">
            <button id="sidebar-trigger" data-sidebar-open class="md:hidden inline-flex h-8 w-8 items-center justify-center rounded-lg border border-border bg-card transition-colors hover:bg-muted">
                <i data-lucide="menu" class="h-4 w-4"></i>
            </button>
            <button id="sidebar-collapse-trigger" data-sidebar-collapse class="hidden md:inline-flex h-8 w-8 items-center justify-center rounded-lg border border-border bg-card transition-colors hover:bg-muted" title="<?= lang('collapse_sidebar') ?>">
                <i data-lucide="panel-left-close" data-sidebar-collapse-icon class="h-4 w-4"></i>
            </button>

            <div class="min-w-0">
                <div class="flex flex-wrap items-center gap-3">
                    <h1 class="truncate text-lg font-semibold leading-tight text-foreground sm:text-[1.2rem]"><?= html_escape($header_title) ?></h1>
                    <?php if (is_array($header_badge)) { ?>
                        <?= $render_badge($header_badge) ?>
                    <?php } elseif ($header_badge_html !== '') { ?>
                        <?= $header_badge_html ?>
                    <?php } ?>
                </div>
                <?php if ($header_description !== '') { ?>
                    <p class="truncate text-sm text-muted-foreground"><?= html_escape($header_description) ?></p>
                <?php } ?>
            </div>
        </div>

        <div class="flex w-full flex-wrap items-center gap-1.5 sm:w-auto sm:justify-end sm:gap-2">
            <?php if (!empty($header_search)) { ?>
                <label class="relative hidden md:block">
                    <span class="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3 text-muted-foreground">
                        <i data-lucide="<?= html_escape($header_search['icon'] ?? 'search') ?>" class="h-4 w-4"></i>
                    </span>
                    <input
                        type="<?= html_escape($header_search['type'] ?? 'search') ?>"
                        name="<?= html_escape($header_search['name'] ?? 'header_search') ?>"
                        value="<?= html_escape($header_search['value'] ?? '') ?>"
                        placeholder="<?= html_escape($header_search['placeholder'] ?? 'Search anything...') ?>"
                        class="h-9 w-64 rounded-lg border border-border bg-white pl-9 pr-9 text-xs text-foreground shadow-sm outline-none transition focus:border-primary/40 focus:ring-2 focus:ring-primary/10 dark:border-slate-700 dark:bg-slate-900"
                        <?= !empty($header_search['attrs']) ? $normalize_attrs($header_search['attrs']) : '' ?>
                    >
                    <?php if (!empty($header_search['trailing_icon'])) { ?>
                        <span class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3 text-muted-foreground">
                            <i data-lucide="<?= html_escape($header_search['trailing_icon']) ?>" class="h-4 w-4"></i>
                        </span>
                    <?php } ?>
                </label>
            <?php } ?>

            <?php if (!empty($header_view_toggle)) { ?>
                <div class="inline-flex items-center rounded-lg border border-border bg-card p-0.5 shadow-sm dark:border-slate-700 dark:bg-slate-900">
                    <?php foreach ($header_view_toggle as $toggle_item) { ?>
                        <?= $render_toggle_button($toggle_item) ?>
                    <?php } ?>
                </div>
            <?php } ?>

            <?php if ($header_filter_extras_html !== '' || !empty($header_filters)) { ?>
                <div class="flex flex-wrap items-center gap-1.5">
                    <?php if ($header_filter_extras_html !== '') { ?>
                        <?= $header_filter_extras_html ?>
                    <?php } ?>
                    <?php foreach ($header_filters as $filter) { ?>
                        <?= $render_filter_dropdown($filter) ?>
                    <?php } ?>
                </div>
            <?php } ?>

            <?php
            if (is_array($header_actions)) {
                foreach ($header_actions as $action) {
                    echo $render_action_button($action);
                }
            } elseif (is_string($header_actions) && $header_actions !== '') {
                echo $header_actions;
            }
            if ($header_actions_html !== '') {
                echo $header_actions_html;
            }
            ?>

            <?php if (empty($header_tools['hide_default_tools'])) { ?>
                <?php if (empty($header_tools['hide_theme'])) { ?>
                    <button
                        data-toggle-theme
                        class="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-border bg-card shadow-sm transition-colors hover:bg-muted"
                        aria-label="<?= lang('toggle_theme') ?>"
                        aria-pressed="false"
                    >
                        <span class="inline-flex h-5 w-5 items-center justify-center rounded-md bg-muted/70">
                            <i data-lucide="moon" class="hidden h-4 w-4 dark:block"></i>
                            <i data-lucide="sun" class="block h-4 w-4 dark:hidden"></i>
                        </span>
                    </button>
                <?php } ?>
                <?php if (empty($header_tools['hide_notifications'])) { ?>
                    <div class="relative" data-header-notifications data-load-url="<?= html_escape($header_notifications_endpoint) ?>" data-mark-all-url="<?= html_escape($header_notifications_mark_all_endpoint) ?>" data-item-url="<?= html_escape($header_notifications_item_endpoint) ?>">
                        <button type="button" class="relative inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-border bg-card shadow-sm transition-colors hover:bg-muted" data-header-notifications-trigger aria-expanded="false" aria-label="<?= html_escape(lang('notification')) ?>">
                            <i data-lucide="bell" class="h-4 w-4"></i>
                            <span data-header-notification-badge class="absolute -right-1 -top-1 min-w-[1rem] rounded-full bg-rose-500 px-1 py-0.5 text-center text-[9px] font-bold leading-none text-white <?= $header_notification_count > 0 ? '' : 'hidden' ?>">
                                <?= $header_notification_count > 99 ? '99+' : $header_notification_count ?>
                            </span>
                        </button>
                        <div class="absolute right-0 top-[calc(100%+0.75rem)] z-50 hidden w-[22rem] max-w-[calc(100vw-2rem)]" data-header-notifications-panel-wrap>
                            <div class="rounded-3xl border border-border bg-white p-4 shadow-2xl dark:border-slate-700 dark:bg-slate-900" data-header-notifications-panel>
                                <div class="flex items-center gap-3 text-sm text-muted-foreground">
                                    <i data-lucide="loader-circle" class="h-4 w-4 animate-spin"></i>
	                                    <span><?= lang('loading_notifications') ?></span>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php } ?>
            <?php } ?>
        </div>
    </div>
</header>

<script>
window.__headerFilterRemoteCache = window.__headerFilterRemoteCache || new Map();

document.addEventListener('input', function(event) {
    var input = event.target.closest('[data-header-filter-search-input]');
    if (!input) {
        return;
    }

    var submenu = input.closest('[data-header-filter-submenu]');
    if (!submenu) {
        return;
    }

    var query = (input.value || '').trim().toLowerCase();
    var items = submenu.querySelectorAll('[data-header-filter-search-item]');
    var visibleCount = 0;

    items.forEach(function(item) {
        var text = (item.getAttribute('data-header-filter-search-text') || item.textContent || '').toLowerCase();
        var match = query === '' || text.indexOf(query) !== -1;
        item.classList.toggle('hidden', !match);
        if (match) {
            visibleCount += 1;
        }
    });

    var remoteContainer = submenu.querySelector('[data-header-filter-remote]');
    if (remoteContainer) {
        var remoteCount = parseInt(remoteContainer.getAttribute('data-header-filter-visible-count') || '0', 10);
        visibleCount += remoteCount;
    }

    var emptyState = submenu.querySelector('[data-header-filter-search-empty]');
    if (emptyState) {
        emptyState.classList.toggle('hidden', visibleCount !== 0);
    }
});

(function() {
    var remoteDebounceTimers = new WeakMap();

    function parseConfig(container) {
        try {
            return JSON.parse(container.getAttribute('data-header-filter-remote-config') || '{}');
        } catch (error) {
            return {};
        }
    }

    function escapeHtml(value) {
        return String(value)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    function renderRemoteItems(container, config, items, query) {
        var html = '';
        var visibleCount = 0;

        items.forEach(function(item) {
            if (!item || typeof item !== 'object') {
                return;
            }

            var itemId = item.id != null ? String(item.id) : '';
            var itemText = item.text != null ? String(item.text) : '';
            if (!itemId || !itemText) {
                return;
            }

            if (query && itemText.toLowerCase().indexOf(query.toLowerCase()) === -1) {
                return;
            }

            visibleCount += 1;
            var attrs = Object.assign({}, config.action_attrs || {});
            attrs['data-header-filter-item'] = '1';
            attrs['data-header-filter-item-label'] = itemText;
            attrs['data-header-filter-search-text'] = itemText;
            if (config.filter_attr) {
                attrs[config.filter_attr] = itemId;
            }
            if (config.label_attr) {
                attrs[config.label_attr] = (config.label_prefix || '') + itemText;
            }

            var attrString = Object.keys(attrs).map(function(key) {
                return key + '="' + escapeHtml(attrs[key]) + '"';
            }).join(' ');

            html += '<button type="button" data-header-filter-search-item class="header-filter-item flex w-full items-center justify-between gap-3 rounded-xl px-3 py-2 text-left text-sm text-slate-700 transition-colors hover:bg-slate-50 dark:text-slate-200 dark:hover:bg-slate-800" ' + attrString + '>';
            html += '<span class="truncate">' + escapeHtml(itemText) + '</span>';
            html += '</button>';
        });

        container.innerHTML = html;
        container.setAttribute('data-header-filter-visible-count', String(visibleCount));
        if (window.lucide && typeof window.lucide.createIcons === 'function') {
            window.lucide.createIcons();
        }
    }

    async function loadRemoteItems(container, query) {
        var config = parseConfig(container);
        if (!config.endpoint) {
            return;
        }

        var params = new URLSearchParams();
        params.set('q', query || '');
        params.set('limit', String(config.limit || 12));
        if (config.extra && typeof config.extra === 'object') {
            Object.keys(config.extra).forEach(function(key) {
                params.set(key, config.extra[key]);
            });
        }

        var cacheKey = [
            config.cache_key || config.endpoint,
            query || '',
            JSON.stringify(config.extra || {}),
            String(config.limit || 12)
        ].join('|');

        if (window.__headerFilterRemoteCache.has(cacheKey)) {
            renderRemoteItems(container, config, window.__headerFilterRemoteCache.get(cacheKey), query || '');
            return;
        }

	        container.innerHTML = '<div class="px-3 py-2 text-sm text-muted-foreground">' + escapeHtml(<?= json_encode(lang('loading')) ?>) + '</div>';
        container.setAttribute('data-header-filter-visible-count', '0');

        try {
            var response = await fetch(config.endpoint + '?' + params.toString(), {
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            });
            var payload = await response.json();
            var items = Array.isArray(payload.results) ? payload.results : [];
            window.__headerFilterRemoteCache.set(cacheKey, items);
            renderRemoteItems(container, config, items, query || '');
        } catch (error) {
	            container.innerHTML = '<div class="px-3 py-2 text-sm text-rose-500">' + escapeHtml(<?= json_encode(lang('lookup_failed')) ?>) + '</div>';
            container.setAttribute('data-header-filter-visible-count', '0');
        }
    }

    function queueRemoteLoad(submenu, query) {
        var remoteContainer = submenu.querySelector('[data-header-filter-remote]');
        if (!remoteContainer) {
            return;
        }

        var oldTimer = remoteDebounceTimers.get(remoteContainer);
        if (oldTimer) {
            clearTimeout(oldTimer);
        }

        var timer = setTimeout(function() {
            loadRemoteItems(remoteContainer, query || '');
        }, 180);
        remoteDebounceTimers.set(remoteContainer, timer);
    }

    document.addEventListener('mouseenter', function(event) {
        var submenu = event.target.closest('[data-header-filter-submenu]');
        if (!submenu) {
            return;
        }
        var input = submenu.querySelector('[data-header-filter-search-input]');
        if (input) {
            queueRemoteLoad(submenu, input.value || '');
            setTimeout(function() {
                if (document.body.contains(input)) {
                    input.focus();
                }
            }, 40);
        }
    }, true);

    document.addEventListener('focusin', function(event) {
        var submenu = event.target.closest('[data-header-filter-submenu]');
        if (!submenu) {
            return;
        }
        var input = submenu.querySelector('[data-header-filter-search-input]');
        if (input) {
            queueRemoteLoad(submenu, input.value || '');
        }
    });

    document.addEventListener('input', function(event) {
        var input = event.target.closest('[data-header-filter-search-input]');
        if (!input) {
            return;
        }
        var submenu = input.closest('[data-header-filter-submenu]');
        if (!submenu) {
            return;
        }
        queueRemoteLoad(submenu, input.value || '');
    });
})();

(function() {
    function updateNotificationBadges(count) {
        var normalized = Math.max(0, parseInt(count || '0', 10) || 0);
        document.querySelectorAll('[data-header-notification-badge]').forEach(function(badge) {
            badge.textContent = normalized > 99 ? '99+' : String(normalized);
            badge.classList.toggle('hidden', normalized === 0);
        });
    }

    async function requestJson(url, options) {
        var controller = window.AbortController ? new AbortController() : null;
        var timeout = window.setTimeout(function() {
            if (controller) {
                controller.abort();
            }
        }, 6000);
        try {
            var response = await fetch(url, Object.assign({
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                },
                signal: controller ? controller.signal : undefined
            }, options || {}));
            if (!response.ok) {
                throw new Error('Request failed');
            }
            return response.json();
        } finally {
            window.clearTimeout(timeout);
        }
    }

    document.addEventListener('click', async function(event) {
        var trigger = event.target.closest('[data-header-notifications-trigger]');
        if (!trigger) {
            return;
        }

        var root = trigger.closest('[data-header-notifications]');
        if (!root) {
            return;
        }

        event.preventDefault();

        var panelWrap = root.querySelector('[data-header-notifications-panel-wrap]');
        var panel = root.querySelector('[data-header-notifications-panel]');
        var isOpen = panelWrap && !panelWrap.classList.contains('hidden');

        document.querySelectorAll('[data-header-notifications-panel-wrap]').forEach(function(item) {
            if (item !== panelWrap) {
                item.classList.add('hidden');
            }
        });
        document.querySelectorAll('[data-header-notifications-trigger]').forEach(function(item) {
            if (item !== trigger) {
                item.setAttribute('aria-expanded', 'false');
            }
        });

        if (isOpen) {
            panelWrap.classList.add('hidden');
            trigger.setAttribute('aria-expanded', 'false');
            return;
        }

        panelWrap.classList.remove('hidden');
        trigger.setAttribute('aria-expanded', 'true');

        if (root.dataset.loaded === '1' && panel && panel.dataset.loading !== '1') {
            return;
        }

        panel.dataset.loading = '1';
        try {
            var payload = await requestJson(root.getAttribute('data-load-url'));
            if (!payload || payload.success !== true) {
                throw new Error('Failed to load notifications');
            }
            panel.innerHTML = payload.html || '';
            root.dataset.loaded = '1';
            updateNotificationBadges(payload.unread_count || 0);
            if (window.refreshAppUi) {
                window.refreshAppUi(panel);
            }
        } catch (error) {
	            panel.innerHTML = '<div class="rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700 dark:border-rose-900/40 dark:bg-rose-950/30 dark:text-rose-200">' + <?= json_encode(lang('could_not_load_notifications')) ?> + '</div>';
        } finally {
            delete panel.dataset.loading;
        }
    });

    document.addEventListener('click', function(event) {
        var insideNotifications = event.target.closest('[data-header-notifications]');
        if (insideNotifications) {
            return;
        }
        document.querySelectorAll('[data-header-notifications-panel-wrap]').forEach(function(item) {
            item.classList.add('hidden');
        });
        document.querySelectorAll('[data-header-notifications-trigger]').forEach(function(item) {
            item.setAttribute('aria-expanded', 'false');
        });
    });

    document.addEventListener('click', async function(event) {
        var action = event.target.closest('[data-header-notifications-mark-all]');
        if (!action) {
            return;
        }

        var root = action.closest('[data-header-notifications]');
        var panel = root ? root.querySelector('[data-header-notifications-panel]') : null;
        if (!root || !panel) {
            return;
        }

        event.preventDefault();

        try {
            var payload = await requestJson(root.getAttribute('data-mark-all-url'));
            updateNotificationBadges(payload.unread_count || 0);
            root.dataset.loaded = '0';
            panel.dataset.loading = '1';
            var refreshed = await requestJson(root.getAttribute('data-load-url'));
            panel.innerHTML = refreshed.html || '';
            root.dataset.loaded = '1';
            updateNotificationBadges(refreshed.unread_count || 0);
            if (window.refreshAppUi) {
                window.refreshAppUi(panel);
            }
        } catch (error) {
            if (window.toastr && typeof window.toastr.error === 'function') {
	                window.toastr.error(<?= json_encode(lang('could_not_update_notifications')) ?>);
            }
        } finally {
            delete panel.dataset.loading;
        }
    });

    document.addEventListener('click', function(event) {
        var link = event.target.closest('[data-header-notification-item]');
        if (!link) {
            return;
        }

        var root = link.closest('[data-header-notifications]');
        if (!root) {
            return;
        }

        var notificationId = link.getAttribute('data-notification-id');
        var unread = link.getAttribute('data-unread') === '1';
        if (!notificationId || !unread) {
            return;
        }

        var endpoint = root.getAttribute('data-item-url').replace(/\/$/, '') + '/' + notificationId;
        fetch(endpoint, {
            method: 'GET',
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            keepalive: true
        }).catch(function() {});

        link.setAttribute('data-unread', '0');
        var dot = link.querySelector('.bg-amber-500');
        if (dot) {
            dot.remove();
        }
        link.classList.remove('bg-amber-50/70', 'dark:bg-amber-950/10');
        var badge = document.querySelector('[data-header-notification-badge]');
        var currentCount = badge ? parseInt(badge.textContent || '0', 10) : 0;
        updateNotificationBadges((currentCount || 1) - 1);
    });
})();
</script>
