<?php

declare(strict_types=1);

namespace FleekDash\Admin;

/**
 * Admin Bar Modern Styles
 *
 * Renders CSS and JavaScript for admin bar customization in modern mode.
 * Includes logo styles, greeting hide, Solar icons replacement.
 *
 * @package FleekDash\Admin
 * @since 2.2.9
 */
class AdminBarModernStyles
{
    /**
     * Render modern styles and scripts to admin_head and wp_head
     *
     * @return void
     */
    public function render(): void
    {
        // Double-check: Only apply in modern mode (safety check)
        $admin_bar_style = \get_option('fleekdash_admin_bar_style', 'modern');
        if ($admin_bar_style !== 'modern') {
            return;
        }

        $theme_color = \get_option('fleekdash_admin_bar_theme_color', 'auto');
        if (!in_array($theme_color, ['auto', 'light', 'dark'], true)) {
            $theme_color = 'auto';
        }

        ?>
        <style id="fleekdash-admin-bar-logo-styles">/* Hide "Howdy, " greeting from admin bar - Simple CSS solution */
            #wp-admin-bar-my-account>.ab-item {
                font-size: 0 !important;
                display: flex !important;
                align-items: center !important;
                gap: 6px !important;
            }

            /* WordPress doesn't use .display-name class - target all child elements except img */
            #wp-admin-bar-my-account>.ab-item > *:not(img) {
                font-size: 12.5px !important;
                display: inline-block !important;
                vertical-align: middle !important;
                margin-top: -1px !important;
            }/* Alternative: If WordPress uses nested spans, target the last span (usually contains username) */
            #wp-admin-bar-my-account>.ab-item span:last-child {
                font-size: 12.5px !important;
                display: inline-block !important;
                vertical-align: middle !important;
                margin-top: -1px !important;
            }

            #wp-admin-bar-my-account>.ab-item img {
                font-size: 0 !important;
                display: inline-block !important;
                height: 60% !important;
                margin-top: -1px !important;
            }

            /* FleekDash Logo in Admin Bar */
            #wp-admin-bar-fleekdash-logo {
                margin-left: 0 !important;
            }

            #wp-admin-bar-fleekdash-logo>.ab-item {
                padding: 0 12px !important;
                height: 32px !important;
                display: flex !important;
                align-items: center !important;
                border: none !important;
                box-shadow: none !important;
                background: transparent !important;
            }

            #wp-admin-bar-fleekdash-logo>.ab-item:hover {
                background: var(--muted) !important;
            }

            .fleekdash-admin-bar-logo-img {
                height: 20px !important;
                width: auto !important;
                max-width: 120px !important;
                object-fit: contain !important;
                display: block !important;
                transition: opacity 0.2s ease !important;
                border: none !important;
                box-shadow: none !important;
                outline: none !important;
            }

            #wp-admin-bar-fleekdash-logo:hover .fleekdash-admin-bar-logo-img {
                opacity: 0.8;
            }


            /* ===============================================
               SOLAR ICONS REPLACEMENT
               =============================================== */

            /* Hide original dashicons in admin bar */
            #wpadminbar .ab-icon:before,
            #wpadminbar .ab-item:before,
            #wpadminbar #adminbarsearch:before,
            #wpadminbar #adminbarsearch .ab-icon:before,
            #wpadminbar #wp-admin-bar-search .ab-item:before,
            #wpadminbar #wp-admin-bar-search .ab-icon:before {
                content: '' !important;
                display: none !important;
                visibility: hidden !important;
            }

                @media screen and (min-width: 783px) {
                    #wpadminbar .ab-item {
                        display: flex !important;
                        align-items: center !important;
                    }
                }

                @media screen and (min-width: 783px) {
                    #wpadminbar .fleekdash-solar-icon {
                        width: 20px !important;
                        height: 20px !important;
                        display: flex !important;
                        align-items: center !important;
                        justify-content: center !important;
                        margin-right: 6px !important;
                        flex-shrink: 0 !important;
                        margin-top: 0 !important;
                        margin-bottom: 0 !important;
                        color: inherit !important;
                    }

                    #wpadminbar .fleekdash-solar-icon svg {
                        width: 18px !important;
                        height: 18px !important;
                        fill: none !important;
                        stroke: currentColor !important;
                        stroke-width: 1.5 !important;
                        display: block !important;
                        margin: auto !important;
                        color: inherit !important;
                    }

                    #wpadminbar .ab-item .fleekdash-solar-icon {
                        color: var(--foreground) !important;
                        opacity: 1 !important;
                    }
                }

            #wpadminbar li:not(#wp-admin-bar-fleekdash-logo) .ab-item * {
                filter: none !important;
            }

            #wpadminbar .ab-item:hover .fleekdash-solar-icon,
            #wpadminbar li:hover>.ab-item .fleekdash-solar-icon,
            #wpadminbar li.hover>.ab-item .fleekdash-solar-icon {
                color: var(--primary) !important;
                opacity: 1 !important;
            }

            #wpadminbar .ab-item:hover,
            #wpadminbar li:hover>.ab-item,
            #wpadminbar li.hover>.ab-item {
                filter: none !important;
            }

            #wpadminbar #wp-admin-bar-my-account>.ab-item>.fleekdash-solar-icon {
                display: none !important;
            }

            #wpadminbar #wp-admin-bar-user-info .fleekdash-solar-icon {
                display: none !important;
            }

            #wpadminbar #adminbarsearch .fleekdash-solar-icon {
                display: none !important;
            }

        </style>

        <script id="fleekdash-admin-bar-logo-sync">
            (function() {
                'use strict';

                const themeColor = <?php echo \wp_json_encode($theme_color); ?>;
                const forceLight = (themeColor === 'light');
                const forceDark = (themeColor === 'dark');
                const isAuto = (themeColor === 'auto');

                function applyAdminBarTheme() {
                    var bar = document.getElementById('wpadminbar');
                    if (!bar) return;
                    if (themeColor === 'auto') {
                        bar.removeAttribute('data-fleekdash-theme');
                    } else {
                        bar.setAttribute('data-fleekdash-theme', themeColor);
                    }
                }

                function updateAdminBarLogo() {
                    try {
                        const logoImg = document.querySelector('.fleekdash-admin-bar-logo-img');
                        if (!logoImg) return;

                        if (logoImg.classList.contains('fleekdash-classic-logo')) {
                            logoImg.style.setProperty('filter', 'invert(1) brightness(1.1)', 'important');
                            return;
                        }

                        const lightLogo = logoImg.getAttribute('data-light-logo');
                        const darkLogo = logoImg.getAttribute('data-dark-logo');
                        const hasDarkLogo = logoImg.getAttribute('data-has-dark-logo') === 'true';
                        const autoInvertDarkMode = logoImg.getAttribute('data-auto-invert-dark-mode') !== 'false';

                        if (!lightLogo) return;

                        let isDark = false;

                        if (forceLight) {
                            isDark = false;
                        } else if (forceDark) {
                            isDark = true;
                        } else if (isAuto) {
                            const adminBar = document.getElementById('wpadminbar');
                            isDark = document.documentElement.classList.contains('dark') ||
                                     document.body?.classList.contains('dark') ||
                                     adminBar?.classList.contains('fleekdash-admin-bar-dark') ||
                                     document.documentElement.classList.contains('vx-dark-mode');
                        }

                        if (isDark) {
                            if (hasDarkLogo && darkLogo) {
                                logoImg.src = darkLogo;
                                logoImg.style.setProperty('filter', 'none', 'important');
                            } else if (autoInvertDarkMode) {
                                logoImg.src = lightLogo;
                                logoImg.style.setProperty('filter', 'invert(1) brightness(1.1)', 'important');
                            } else {
                                logoImg.src = lightLogo;
                                logoImg.style.setProperty('filter', 'none', 'important');
                            }
                        } else {
                            logoImg.src = lightLogo;
                            logoImg.style.setProperty('filter', 'none', 'important');
                        }

                        const logoContainer = logoImg.closest('.ab-item');
                        if (logoContainer) {
                            logoContainer.style.filter = 'none';
                        }
                    } catch (error) {
                        console.warn('[FleekDash] Admin bar logo sync error:', error);
                    }
                }

                function runAdminBarSync() {
                    applyAdminBarTheme();
                    updateAdminBarLogo();
                }

                if (document.readyState === 'loading') {
                    document.addEventListener('DOMContentLoaded', runAdminBarSync);
                } else {
                    runAdminBarSync();
                }

                let adminBarLogoTimeout = null;
                let adminBarLogoStorageTimeout = null;

                adminBarLogoTimeout = setTimeout(() => {
                    adminBarLogoTimeout = null;
                    runAdminBarSync();
                }, 100);

                const adminBarObserver = new MutationObserver((mutations) => {
                    mutations.forEach((mutation) => {
                        if (mutation.attributeName === 'class' && isAuto) {
                            updateAdminBarLogo();
                        }
                    });
                });

                adminBarObserver.observe(document.documentElement, {
                    attributes: true,
                    attributeFilter: ['class']
                });

                if (document.body) {
                    adminBarObserver.observe(document.body, {
                        attributes: true,
                        attributeFilter: ['class']
                    });
                } else {
                    document.addEventListener('DOMContentLoaded', function() {
                        if (adminBarObserver) {
                            adminBarObserver.observe(document.body, {
                                attributes: true,
                                attributeFilter: ['class']
                            });
                        }
                    });
                }

                const handleStorageChange = function(e) {
                    if (e.key === 'fleekdash-dark-mode') {
                        if (adminBarLogoStorageTimeout) {
                            clearTimeout(adminBarLogoStorageTimeout);
                        }
                        adminBarLogoStorageTimeout = setTimeout(() => {
                            adminBarLogoStorageTimeout = null;
                            updateAdminBarLogo();
                        }, 50);
                    }
                };

                window.addEventListener('fleekdash:theme-changed', updateAdminBarLogo);
                window.addEventListener('storage', handleStorageChange);

                window.addEventListener('beforeunload', function() {
                    if (adminBarObserver) {
                        adminBarObserver.disconnect();
                    }
                    window.removeEventListener('fleekdash:theme-changed', updateAdminBarLogo);
                    window.removeEventListener('storage', handleStorageChange);
                });

            })();
        </script>

        <script id="fleekdash-admin-bar-icons">
            (function() {
                'use strict';

                const solarIcons = {
                    'new-content': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="12" cy="12" r="10"/><path d="M12 8v8M8 12h8"/></svg>',
                    'comments': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12c0 1.6.376 3.112 1.043 4.453.178.356.237.763.134 1.148l-.595 2.226a1.3 1.3 0 0 0 1.591 1.591l2.226-.595a1.634 1.634 0 0 1 1.149.133A9.958 9.958 0 0 0 12 22Z"/></svg>',
                    'updates': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M16 8h5V3"/><path d="M8 16H3v5"/></svg>',
                    'search': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>',
                    'user': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="12" cy="8" r="4"/><path d="M5.338 18.32C5.999 15.528 8.772 14 12 14s6.001 1.527 6.662 4.32c.09.378.135.567.063.74a.625.625 0 0 1-.244.276c-.156.095-.36.095-.77.095H6.29c-.41 0-.614 0-.77-.095a.625.625 0 0 1-.244-.277c-.072-.172-.027-.361.063-.739Z"/></svg>',
                    'site': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 9h18"/></svg>',
                    'globe': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10Z"/></svg>',
                    'dashboard': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M2 12.204c0-2.289 0-3.433.52-4.381.518-.949 1.467-1.537 3.364-2.715l2-1.241C9.889 2.622 10.892 2 12 2c1.108 0 2.11.622 4.116 1.867l2 1.241c1.897 1.178 2.846 1.766 3.365 2.715.519.948.519 2.092.519 4.38v1.522c0 3.9 0 5.851-1.172 7.063C19.657 22 17.771 22 14 22h-4c-3.771 0-5.657 0-6.828-1.212C2 19.576 2 17.626 2 13.725v-1.521Z"/><path d="M12 15v3"/></svg>',
                    'edit': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M15.5 5.5 18.5 8.5M3 21l.867-3.9a.96.96 0 0 1 .272-.511l12.47-12.47a1.414 1.414 0 0 1 2 0l1.272 1.272a1.414 1.414 0 0 1 0 2L7.41 19.86a.96.96 0 0 1-.511.272L3 21Z"/></svg>',
                    'menu': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M4 7h16M4 12h16M4 17h16"/></svg>',
                    'settings': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z"/><path d="M18.727 14.727a1.5 1.5 0 0 0 .3 1.655l.055.054a1.816 1.816 0 0 1 0 2.573 1.818 1.818 0 0 1-2.573 0l-.055-.055a1.5 1.5 0 0 0-1.654-.3 1.5 1.5 0 0 0-.91 1.373v.155a1.818 1.818 0 1 1-3.636 0V20.1a1.5 1.5 0 0 0-.981-1.373 1.5 1.5 0 0 0-1.655.3l-.054.055a1.818 1.818 0 0 1-3.106-1.287 1.818 1.818 0 0 1 .533-1.286l.054-.055a1.5 1.5 0 0 0 .3-1.654 1.5 1.5 0 0 0-1.372-.91h-.156a1.818 1.818 0 1 1 0-3.636H3.9a1.5 1.5 0 0 0 1.373-.981 1.5 1.5 0 0 0-.3-1.655l-.055-.054A1.818 1.818 0 1 1 7.49 4.99l.055.054a1.5 1.5 0 0 0 1.654.3h.073a1.5 1.5 0 0 0 .909-1.372v-.155a1.818 1.818 0 0 1 3.636 0V3.9a1.5 1.5 0 0 0 .91 1.373 1.5 1.5 0 0 0 1.654-.3l.054-.055a1.818 1.818 0 0 1 2.573 0 1.818 1.818 0 0 1 0 2.573l-.055.054a1.5 1.5 0 0 0-.3 1.655v.073a1.5 1.5 0 0 0 1.373.909h.155a1.818 1.818 0 0 1 0 3.636H20.1a1.5 1.5 0 0 0-1.373.91Z"/></svg>',
                    'help': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="12" cy="12" r="10"/><path d="M10 8.484c.5-.654 1.212-1.027 2-1.027 1.105 0 2 .932 2 2.082 0 .65-.282 1.234-.72 1.618-.41.358-.886.756-1.138 1.308M12 16v.5"/></svg>',
                    'plugin': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.27 6.96 8 4.52a2 2 0 0 0 1.46 0l8-4.52"/><path d="M12 22.08V11"/></svg>',
                    'media': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="m21 15-3.172-3.172a2 2 0 0 0-2.828 0L9 16l-4 4h16v-4Z"/></svg>',
                    'posts': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8Z"/><path d="M14 2v6h6"/><path d="M16 13H8"/><path d="M16 17H8"/><path d="M10 9H8"/></svg>',
                    'appearance': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41"/><circle cx="12" cy="12" r="5"/></svg>',
                    'users': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="9" cy="6" r="4"/><path d="M1.996 18.352C2.62 15.524 5.453 14 9 14c.621 0 1.218.05 1.785.145"/><circle cx="17" cy="10" r="3"/><path d="M21 20c0-2.21-1.79-4-4-4s-4 1.79-4 4"/></svg>',
                    'tools': '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76Z"/></svg>',
                };

                const iconMapping = {
                    'wp-admin-bar-new-content': 'new-content',
                    'wp-admin-bar-comments': 'comments',
                    'wp-admin-bar-updates': 'updates',
                    'wp-admin-bar-search': 'search',
                    'wp-admin-bar-my-account': 'user',
                    'wp-admin-bar-site-name': 'dashboard',
                    'wp-admin-bar-dashboard': 'dashboard',
                    'wp-admin-bar-edit': 'edit',
                    'wp-admin-bar-menu-toggle': 'menu',
                    'wp-admin-bar-customize': 'settings',
                    'wp-admin-bar-appearance': 'appearance',
                    'wp-admin-bar-wp-help': 'help',
                    'wp-admin-bar-view-site': 'globe',
                    'wp-admin-bar-edit-profile': 'user',
                    'wp-admin-bar-logout': 'user',
                    'wp-admin-bar-user-info': 'user',
                };

                function createIconElement(iconName) {
                    const svg = solarIcons[iconName];
                    if (!svg) return null;
                    const span = document.createElement('span');
                    span.className = 'fleekdash-solar-icon';
                    span.innerHTML = svg;
                    return span;
                }

                function replaceAdminBarIcons() {
                    if (window.innerWidth <= 782) return;
                    try {
                        Object.entries(iconMapping).forEach(([menuId, iconName]) => {
                            const menuItem = document.getElementById(menuId);
                            if (!menuItem) return;
                            const abItem = menuItem.querySelector(':scope > .ab-item');
                            if (!abItem) return;
                            if (abItem.querySelector('.fleekdash-solar-icon')) return;
                            if (menuId === 'wp-admin-bar-my-account' && abItem.querySelector('img')) return;
                            const iconElement = createIconElement(iconName);
                            if (iconElement) abItem.insertBefore(iconElement, abItem.firstChild);
                        });

                        const adminbarSearch = document.getElementById('adminbarsearch');
                        if (adminbarSearch) {
                            const formIcon = adminbarSearch.querySelector('.fleekdash-solar-icon');
                            if (formIcon) formIcon.remove();
                        }

                        document.querySelectorAll('#wpadminbar .ab-submenu').forEach(submenu => {
                            const isUserInfoItem = (item) => item.closest('#wp-admin-bar-user-info');
                            submenu.querySelectorAll('.ab-item').forEach(item => {
                                if (item.querySelector('.fleekdash-solar-icon')) return;
                                if (isUserInfoItem(item)) return;
                                const href = item.getAttribute('href') || '';
                                const text = item.textContent?.toLowerCase().trim() || '';
                                let iconName = 'posts';
                                if (href.includes('post-new.php') && !href.includes('post_type=page')) iconName = 'posts';
                                else if (href.includes('post_type=page') || href.includes('edit.php?post_type=page')) iconName = 'posts';
                                else if (href.includes('media-new.php') || href.includes('upload.php')) iconName = 'media';
                                else if (href.includes('user-new.php') || href.includes('users.php')) iconName = 'users';
                                else if (href.includes('plugins.php')) iconName = 'plugin';
                                else if (href.includes('themes.php') || href.includes('theme-install.php')) iconName = 'appearance';
                                else if (href.includes('nav-menus.php')) iconName = 'menu';
                                else if (href.includes('widgets.php') || href.includes('customize.php') || href.includes('options-general.php')) iconName = 'settings';
                                else if (href.includes('tools.php')) iconName = 'tools';
                                else if (href.includes('edit-comments.php')) iconName = 'comments';
                                else if (href.includes('admin.php?page=')) iconName = 'posts';
                                else {
                                    if (text.includes('dashboard') || text.includes('home')) iconName = 'dashboard';
                                    else if (text.includes('plugin')) iconName = 'plugin';
                                    else if (text.includes('theme') || text.includes('appearance')) iconName = 'appearance';
                                    else if (text.includes('menu')) iconName = 'menu';
                                    else if (text.includes('widget') || text.includes('customize') || text.includes('setting')) iconName = 'settings';
                                    else if (text.includes('tool')) iconName = 'tools';
                                    else if (text.includes('comment')) iconName = 'comments';
                                    else if (text.includes('user') || text.includes('profile')) iconName = 'user';
                                    else if (text.includes('post') || text.includes('page')) iconName = 'posts';
                                    else if (text.includes('media') || text.includes('image')) iconName = 'media';
                                    else if (text.includes('visit site') || text.includes('view site')) iconName = 'globe';
                                }
                                const iconElement = createIconElement(iconName);
                                if (iconElement) item.insertBefore(iconElement, item.firstChild);
                            });
                        });
                    } catch (error) {
                        console.warn('[FleekDash] Admin bar icons replacement error:', error);
                    }
                }

                if (document.readyState === 'loading') {
                    document.addEventListener('DOMContentLoaded', replaceAdminBarIcons);
                } else {
                    replaceAdminBarIcons();
                }

                let adminBarIconsTimeout = setTimeout(() => {
                    adminBarIconsTimeout = null;
                    replaceAdminBarIcons();
                }, 500);

                window.addEventListener('beforeunload', function() {
                    if (adminBarIconsTimeout) {
                        clearTimeout(adminBarIconsTimeout);
                        adminBarIconsTimeout = null;
                    }
                });

            })();
        </script>

        <script id="fleekdash-admin-bar-search-autofocus">
            (function() {
                'use strict';

                function setupSearchAutofocus() {
                    const searchMenuItem = document.getElementById('wp-admin-bar-search');
                    const searchInput = document.getElementById('adminbar-search');
                    if (!searchMenuItem || !searchInput) return;

                    const observer = new MutationObserver((mutations) => {
                        mutations.forEach((mutation) => {
                            if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
                                const isVisible = searchMenuItem.classList.contains('hover') ||
                                                  searchMenuItem.classList.contains('opensub') ||
                                                  window.getComputedStyle(searchInput.closest('#adminbarsearch')).display !== 'none';
                                if (isVisible && searchInput.offsetParent !== null) {
                                    setTimeout(() => {
                                        try { searchInput.focus(); } catch (e) {}
                                    }, 50);
                                }
                            }
                        });
                    });

                    observer.observe(searchMenuItem, { attributes: true, attributeFilter: ['class'] });

                    searchMenuItem.addEventListener('mouseenter', () => {
                        setTimeout(() => {
                            const input = document.getElementById('adminbar-search');
                            if (input && input.offsetParent !== null) {
                                try { input.focus(); } catch (e) {}
                            }
                        }, 100);
                    }, { passive: true });
                }

                if (document.readyState === 'loading') {
                    document.addEventListener('DOMContentLoaded', setupSearchAutofocus);
                } else {
                    setupSearchAutofocus();
                }
            })();
        </script>
        <?php
    }
}
