<?php @include_once __DIR__.'/../analytics_bootstrap.php'; ?>
<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__.'/../db_connect.php';
require_once __DIR__.'/../customer_session_guard.php';

// Shared modals: available on every page that uses the header.
require_once __DIR__.'/../authModal.php';
require_once __DIR__.'/../upgradeModal.php';

$isLoggedIn = isset($_SESSION['user_id']);
$plan = $_SESSION['plan'] ?? 'free';
$currentPage = basename($_SERVER['PHP_SELF'] ?? '');

$toolGroups = [
    [
        'id' => 'main-tools',
        'title' => 'الأدوات الأساسية',
        'icon' => '▦',
        'tools' => [
            ['href' => 'jpg-to-pdf.php', 'title' => 'تحويل الصور إلى PDF', 'emoji' => '▧'],
            ['href' => 'merge-pdf.php', 'title' => 'دمج PDF', 'emoji' => '⊞'],
            ['href' => 'compress-pdf.php', 'title' => 'ضغط PDF', 'emoji' => '⇣'],
            ['href' => 'split-pdf.php', 'title' => 'تقسيم PDF', 'emoji' => '✂'],
        ],
    ],
    [
        'id' => 'edit-tools',
        'title' => 'تحرير وتخصيص PDF',
        'icon' => '✎',
        'tools' => [
            ['href' => 'reorder-pdf.php', 'title' => 'ترتيب صفحات PDF', 'emoji' => '↕'],
            ['href' => 'add-page-numbers.php', 'title' => 'إضافة أرقام الصفحات', 'emoji' => '№'],
            ['href' => 'watermark-pdf.php', 'title' => 'إضافة علامة مائية', 'emoji' => '◫'],
            ['href' => 'resize-pdf.php', 'title' => 'تغيير حجم الصفحات', 'emoji' => '↔'],
            ['href' => 'crop-pdf.php', 'title' => 'قص هوامش PDF', 'emoji' => '⌗'],
            ['href' => 'sign-pdf.php', 'title' => 'توقيع PDF', 'emoji' => '✍'],
            ['href' => 'stamp-pdf.php', 'title' => 'إضافة ختم PDF', 'emoji' => '◎'],
            ['href' => 'edit-pdf.php', 'title' => 'محرر PDF', 'emoji' => '✎'],
            ['href' => 'pdf-bookmarks.php', 'title' => 'إضافة فهرس / Bookmarks', 'emoji' => '☷'],
        ],
    ],
    [
        'id' => 'security-tools',
        'title' => 'الحماية والمعالجة',
        'icon' => '⌾',
        'tools' => [
            ['href' => 'protect-pdf.php', 'title' => 'حماية PDF بكلمة مرور', 'emoji' => '🔒'],
            ['href' => 'unlock-pdf.php', 'title' => 'إزالة كلمة المرور', 'emoji' => '🔓'],
            ['href' => 'repair-pdf.php', 'title' => 'إصلاح PDF', 'emoji' => '🛠'],
            ['href' => 'enhance-scan.php', 'title' => 'تحسين PDF الممسوح', 'emoji' => '✨'],
            ['href' => 'ocr-pdf.php', 'title' => 'OCR وتحويل الصور إلى نص', 'emoji' => '⌕'],
        ],
    ],
    [
        'id' => 'convert-tools',
        'title' => 'التحويل',
        'icon' => '⇄',
        'tools' => [
            ['href' => 'pdf-word-converter.php', 'title' => 'PDF ↔ Word', 'emoji' => 'W'],
            ['href' => 'pdf-excel-converter.php', 'title' => 'PDF ↔ Excel', 'emoji' => 'X'],
            ['href' => 'pdf-powerpoint-converter.php', 'title' => 'PDF ↔ PowerPoint', 'emoji' => 'P'],
        ],
    ],
];

function toolGroupHasCurrentPage(array $group, string $currentPage): bool {
    foreach ($group['tools'] as $tool) {
        if (($tool['href'] ?? '') === $currentPage) {
            return true;
        }
    }
    return false;
}
?>

<style>
/* =========================================================
   DeuxPDF — Side Navigation / Tools Menu V3
   ========================================================= */


/* =========================================================
   1. SIDE NAVIGATION
   ========================================================= */

.side-nav {
    position: fixed;
    top: 0;
    right: 0;

    width: min(350px, 92vw) !important;
    height: 100dvh;

    display: flex;
    flex-direction: column;

    background: #fff;
    overflow: hidden !important;

    transform: translateX(105%);
    visibility: hidden;
    pointer-events: none;

    transition:
        transform .28s ease,
        visibility 0s linear .28s;
}

.side-nav.open,
.side-nav.active,
.side-nav.show {
    transform: translateX(0);
    visibility: visible;
    pointer-events: auto;

    transition:
        transform .28s ease,
        visibility 0s;
}


/* =========================================================
   2. MENU OVERLAY
   ========================================================= */

.menu-overlay {
    visibility: hidden;
    opacity: 0;
    pointer-events: none;

    transition:
        opacity .25s ease,
        visibility 0s linear .25s;
}

.menu-overlay.open,
.menu-overlay.active,
.menu-overlay.show {
    visibility: visible;
    opacity: 1;
    pointer-events: auto;

    transition:
        opacity .25s ease,
        visibility 0s;
}


/* =========================================================
   3. SIDE HEADER
   ========================================================= */

.side-header {
    flex: 0 0 auto;

    padding: 18px 18px 14px;

    background: #fff;
    border-bottom: 1px solid #edf0f5;
}

.side-header-row {
    display: flex;
    align-items: center;
    justify-content: space-between;

    gap: 12px;
}

.side-header-title {
    display: flex;
    align-items: center;

    gap: 10px;

    font-size: 18px;
    font-weight: 800;

    color: #1f2937;
}

.side-header-title img {
    width: 34px;
    height: 34px;

    object-fit: contain;
}


/* Close Button */

.side-header .close-btn {
    width: 36px;
    height: 36px;

    display: inline-flex;
    align-items: center;
    justify-content: center;

    border-radius: 10px;

    background: #f5f7fa;
    color: #667085;

    text-decoration: none;

    font-size: 25px;
    line-height: 1;

    transition: .18s ease;
}

.side-header .close-btn:hover {
    background: #eef2f7;
    color: #111827;
}


/* =========================================================
   4. SCROLLABLE MENU AREA
   ========================================================= */

.side-nav-scroll {
    flex: 1 1 auto;

    min-height: 0;

    padding: 10px 10px 16px;

    overflow-y: auto;
    overscroll-behavior: contain;

    scrollbar-width: thin;
    scrollbar-color: #d5dbe5 transparent;
}

.side-nav-scroll::-webkit-scrollbar {
    width: 6px;
}

.side-nav-scroll::-webkit-scrollbar-thumb {
    background: #d5dbe5;
    border-radius: 99px;
}


/* =========================================================
   5. COMMON LINKS
   ========================================================= */

.nav-home-link,
.tool-link,
.account-link {
    text-decoration: none !important;
}


/* =========================================================
   6. HOME LINK
   ========================================================= */

.nav-home-link {
    min-height: 50px;

    display: flex !important;
    align-items: center;

    gap: 12px;

    padding: 8px 11px !important;
    margin-bottom: 10px;

    border: 1px solid #edf0f4;
    border-radius: 13px;

    background: #fff;
    color: #273142 !important;

    transition: .18s ease;
}

.nav-home-link:hover,
.nav-home-link.active {
    background: #f6f9ff;
    border-color: #dfe8fb;
}

.nav-home-link img {
    width: 31px !important;
    height: 31px !important;

    object-fit: contain;
}


/* =========================================================
   7. TOOL GROUP
   ========================================================= */

.tool-group {
    margin-bottom: 14px;

    border: 1px solid #e3e8ef;
    border-radius: 18px;

    background: #fff;

    overflow: hidden;

    box-shadow: 0 5px 18px rgba(15, 23, 42, .035);
}


/* Tool Group Header */

.tool-group-header {
    width: 100%;
    min-height: 58px;

    padding: 0 16px;

    display: flex;
    align-items: center;
    justify-content: space-between;

    gap: 10px;

    border: 0;

    background: #f8fafc;
    color: #344054;

    cursor: pointer;

    font-family: inherit;
    text-align: right;

    transition: background .18s ease;
}

.tool-group-header:hover {
    background: #f1f5f9;
}


/* Group Title Wrapper */

.tool-group-title-wrap {
    display: flex;
    align-items: center;

    gap: 9px;

    min-width: 0;
}


/* Group Symbol */

.tool-group-symbol {
    width: 36px;
    height: 36px;
    flex: 0 0 36px;

    display: inline-flex;
    align-items: center;
    justify-content: center;

    border: 1px solid #e6eaf0;
    border-radius: 11px;

    background: #fff;
    color: #40516b;

    font-size: 18px;
    font-weight: 800;
}


/* Group Name */

.tool-group-name {
    font-size: 15.5px;
    font-weight: 800;

    color: #172033;

    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}


/* Tool Counter */

.tool-count {
    margin-right: auto;

    min-width: 30px;
    height: 27px;

    padding: 0 7px;

    display: inline-flex;
    align-items: center;
    justify-content: center;

    border: 1px solid #e7ebf0;
    border-radius: 99px;

    background: #fff;
    color: #7a8494;

    font-size: 12px;
    font-weight: 700;
}


/* Group Arrow */

.tool-group-arrow {
    color: #98a2b3;

    font-size: 14px;

    transition: transform .2s ease;
}

.tool-group.open .tool-group-arrow {
    transform: rotate(180deg);
}


/* =========================================================
   8. TOOL GROUP BODY
   ========================================================= */

.tool-group-body {
    display: none;

    padding: 8px 9px 10px;

    background: #fff;

    border-top: 1px solid #f1f3f6;
}

.tool-group.open .tool-group-body {
    display: block;
}


/* =========================================================
   9. TOOL LINKS
   ========================================================= */

.tool-link {
    min-height: 44px;

    display: flex !important;
    align-items: center;

    gap: 11px;

    margin: 4px 0;
    padding: 7px 10px !important;

    border-radius: 10px;

    background: transparent;
    color: #4b5565 !important;

    transition: .16s ease;
}

.tool-link:hover {
    background: #f6f8fb;
    color: #162033 !important;
}

.tool-link.active {
    background: #eef4ff;
    color: #2459a9 !important;

    font-weight: 800;
}


/* =========================================================
   10. TOOL ICON
   ========================================================= */

.tool-icon-box {
    width: 30px;
    height: 30px;
    flex: 0 0 30px;

    display: inline-flex;
    align-items: center;
    justify-content: center;

    overflow: hidden;

    border: 1px solid #ffe2e2;
    border-radius: 9px;

    background: #fff2f2;
    color: #e5322d;

    font-size: 14px;
    font-weight: 800;
}

.tool-link.active .tool-icon-box {
    background: #fff;
}

.tool-icon-box img {
    width: 22px !important;
    height: 22px !important;

    object-fit: contain;
}


/* Tool Link Title */

.tool-link-title {
    min-width: 0;

    overflow: hidden;

    white-space: nowrap;
    text-overflow: ellipsis;

    font-size: 14px;
}


/* =========================================================
   11. ACCOUNT SECTION
   ========================================================= */

.side-account-box {
    margin-top: 13px;
    padding-top: 12px;

    border-top: 1px solid #e9edf2;
}

.side-account-label {
    padding: 0 7px 7px;

    color: #98a2b3;

    font-size: 11px;
    font-weight: 800;
}


/* =========================================================
   12. EMPTY STATE
   ========================================================= */

.menu-empty-state {
    display: none;

    padding: 35px 15px;

    text-align: center;

    color: #98a2b3;

    font-size: 13px;
}


/* =========================================================
   13. OTHER COLLAPSIBLE GROUPS
   ========================================================= */

.tools-group-content,
.menu-group-content,
.category-content {
    display: none;
}

.tools-group.open .tools-group-content,
.menu-group.open .menu-group-content,
.category.open .category-content {
    display: block;
}


/* =========================================================
   14. LANGUAGE SELECTOR
   ========================================================= */

.dx-side-language {
    margin-top: 16px;
}

.dx-side-lang-grid {
    display: grid;

    grid-template-columns: repeat(3, 1fr);

    gap: 7px;
}

.dx-side-lang {
    min-height: 67px;

    display: flex !important;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    gap: 2px;

    border: 1px solid #e8ebf0;
    border-radius: 12px;

    background: #fff;
    color: #596579 !important;

    text-decoration: none !important;

    transition: .18s ease;
}

.dx-side-lang span {
    font-size: 18px;
}

.dx-side-lang b {
    font-size: 12px;
    color: #e5322d;
}

.dx-side-lang small {
    font-size: 10px;
}

.dx-side-lang:hover,
.dx-side-lang.active {
    background: #fff2f2;
    border-color: #ffd8d8;
    color: #172033 !important;
}


/* =========================================================
   15. MOBILE
   ========================================================= */

@media (max-width: 600px) {

    .side-nav {
        width: min(350px, 94vw) !important;
    }

    .side-header {
        padding: 14px 14px 12px;
    }

    .side-nav-scroll {
        padding: 10px 9px 16px;
    }

    .tool-group-header {
        min-height: 56px;
        padding: 0 11px;
    }

    .tool-link {
        min-height: 44px;
    }

    .topbar {
        gap: 5px;
    }

    .login-btn {
        padding: 8px 10px !important;
        font-size: 13px !important;
    }
}

/* =========================================================
   CRITICAL TOPBAR LAYOUT — desktop + mobile
   Kept inline intentionally so the header cannot fall back to
   the logo image's natural size if an external stylesheet is cached.
   ========================================================= */
.topbar{
    width:100% !important;
    max-width:100vw !important;
    height:65px !important;
    min-height:65px !important;
    padding:0 25px !important;
    display:flex !important;
    align-items:center !important;
    justify-content:space-between !important;
    position:sticky !important;
    top:0 !important;
    left:0 !important;
    right:0 !important;
    overflow:visible !important;
    background:#fff !important;
    border-bottom:1px solid #e5e7eb !important;
    box-sizing:border-box !important;
    z-index:1000 !important;
}
.topbar .logo-section{display:flex !important;align-items:center !important;flex:0 0 auto !important;}
.topbar .logo-section a{display:flex !important;align-items:center !important;line-height:0 !important;}
.topbar .site-logo{
    display:block !important;
    width:auto !important;
    height:42px !important;
    max-width:150px !important;
    max-height:42px !important;
    object-fit:contain !important;
}
.topbar .topbar-right{display:flex !important;align-items:center !important;flex:0 0 auto !important;}
.topbar .menu-section{white-space:nowrap !important;}
.topbar .user-section{
    position:absolute !important;
    left:50% !important;
    right:auto !important;
    transform:translateX(-50%) !important;
    margin:0 !important;
    z-index:2 !important;
}

@media (max-width:768px){
    html,body{max-width:100% !important;overflow-x:hidden !important;}
    .topbar{
        height:58px !important;
        min-height:58px !important;
        padding:0 10px !important;
        display:grid !important;
        grid-template-columns:minmax(0,1fr) auto minmax(0,1fr) !important;
        gap:6px !important;
        direction:rtl !important;
    }
    .topbar .topbar-right{
        grid-column:1 !important;
        justify-self:start !important;
        min-width:0 !important;
    }
    .topbar .user-section{
        grid-column:2 !important;
        position:static !important;
        left:auto !important;
        right:auto !important;
        transform:none !important;
        justify-self:center !important;
        min-width:0 !important;
    }
    .topbar .logo-section{
        grid-column:3 !important;
        justify-self:end !important;
        min-width:0 !important;
    }
    .topbar .site-logo{
        width:auto !important;
        height:32px !important;
        max-width:105px !important;
        max-height:32px !important;
    }
    .topbar .menu-section{
        padding:7px 4px !important;
        font-size:13px !important;
        line-height:1.2 !important;
    }
    .topbar .login-btn{
        min-width:0 !important;
        padding:7px 9px !important;
        font-size:12px !important;
        line-height:1.25 !important;
        white-space:nowrap !important;
        border-radius:18px !important;
    }
    .topbar .user-trigger{gap:5px !important;}
    .topbar .user-avatar{width:30px !important;height:30px !important;margin:0 !important;object-fit:cover !important;}
    .topbar .user-info{max-width:90px !important;}
    .topbar .user-name{font-size:11px !important;white-space:nowrap !important;overflow:hidden !important;text-overflow:ellipsis !important;}
    .topbar .user-plan{font-size:9px !important;}
}

@media (max-width:380px){
    .topbar{padding:0 7px !important;gap:3px !important;}
    .topbar .site-logo{height:28px !important;max-width:88px !important;max-height:28px !important;}
    .topbar .menu-section{font-size:12px !important;padding:6px 2px !important;}
    .topbar .login-btn{font-size:11px !important;padding:6px 7px !important;}
}
</style>

<?php
$dxCurrentPage = basename(parse_url($_SERVER['REQUEST_URI'] ?? 'index.php', PHP_URL_PATH));
if ($dxCurrentPage === '' || $dxCurrentPage === '/' || !str_ends_with($dxCurrentPage, '.php')) $dxCurrentPage = 'index.php';
$dxUri = $_SERVER['REQUEST_URI'] ?? '';
$dxInEn = str_contains($dxUri, '/en/');
$dxInTr = str_contains($dxUri, '/tr/');
$dxBasePrefix = ($dxInEn || $dxInTr) ? '../' : '';
?>
<div id="menuOverlay" class="menu-overlay" onclick="toggleMenu()"></div>

<div class="topbar">
    <div class="topbar-right">
        <div class="menu-section" onclick="toggleMenu()">
            <span>☰ القائمة</span>
        </div>
    </div>

    <div class="user-section">
        <?php if ($isLoggedIn): ?>
            <div class="user-dropdown">
                <div class="user-trigger" onclick="toggleUserMenu()">
                    <img
                        src="<?= !empty($_SESSION['profile_image']) ? htmlspecialchars($_SESSION['profile_image']) : 'images/username.png' ?>"
                        class="user-avatar"
                        onerror="this.onerror=null;this.src='images/username.png';"
                        alt="User">

                    <div class="user-info">
                        <div class="user-name">
                            <span><?= htmlspecialchars($_SESSION['user_name'] ?? 'المستخدم') ?></span>

                            <?php if ($plan === 'premium'): ?>
                                <img src="images/Verified.png" class="verified-icon" alt="Verified">
                            <?php endif; ?>
                        </div>

                        <div class="user-plan <?= htmlspecialchars(strtolower($plan)) ?>">
                            <?= htmlspecialchars(strtoupper($plan)) ?>
                        </div>
                    </div>
                </div>

                <div id="userMenu" class="dropdown-menu">
                    <a href="profile.php">👤 حسابي</a>

                    <?php if ($plan === 'free'): ?>
                        <a href="payment.php">⭐ ترقية الحساب</a>
                    <?php endif; ?>

                    <a href="logout.php" onclick="return confirm('هل تريد تسجيل الخروج؟');">🚪 تسجيل الخروج</a>
                </div>
            </div>
        <?php else: ?>
            <button type="button" onclick="openAuth('tool')" class="login-btn">دخول / تسجيل</button>
        <?php endif; ?>
    </div>

    <div class="logo-section">
        <a href="index.php">
            <img src="images/deuxLOGOPDF.png" class="site-logo" alt="Logo">
        </a>
    </div>
</div>

<div id="sideNav" class="side-nav">
    <div class="side-header">
        <div class="side-header-row">
            <div class="side-header-title">
                <img src="images/deuxLOGO.png" alt="DeuxPDF">
                <span>أدوات DeuxPDF</span>
            </div>

            <a href="javascript:void(0)" class="close-btn" onclick="toggleMenu()" aria-label="إغلاق القائمة">&times;</a>
        </div>
</div>

    <div class="side-nav-scroll" id="sideNavScroll">

        <a href="index.php" class="nav-home-link <?= $currentPage === 'index.php' ? 'active' : '' ?>" data-tool-name="الرئيسية">
            <span class="tool-icon-box" aria-hidden="true">⌂</span>
            <span>الرئيسية</span>
        </a>

        <div id="toolGroupsContainer">
            <?php foreach ($toolGroups as $index => $group): ?>
                <?php
                    $groupHasCurrent = toolGroupHasCurrentPage($group, $currentPage);
                    $openClass = $groupHasCurrent || ($currentPage === 'index.php' && $index === 0) ? 'open' : '';
                ?>

                <section class="tool-group <?= $openClass ?>" data-group-title="<?= htmlspecialchars($group['title']) ?>">
                    <button
                        type="button"
                        class="tool-group-header"
                        onclick="toggleToolGroup(this)"
                        aria-expanded="<?= $openClass ? 'true' : 'false' ?>">

                        <span class="tool-group-title-wrap">
                            <span class="tool-group-symbol"><?= htmlspecialchars($group['icon']) ?></span>
                            <span class="tool-group-name"><?= htmlspecialchars($group['title']) ?></span>
                        </span>

                        <span class="tool-count"><?= count($group['tools']) ?></span>
                        <span class="tool-group-arrow">⌄</span>
                    </button>

                    <div class="tool-group-body">
                        <?php foreach ($group['tools'] as $tool): ?>
                            <?php $isActive = ($currentPage === $tool['href']); ?>

                            <a
                                href="<?= htmlspecialchars($tool['href']) ?>"
                                class="tool-link <?= $isActive ? 'active' : '' ?>"
                                data-tool-name="<?= htmlspecialchars($tool['title']) ?>">

                                <span class="tool-icon-box">
                                    <?php if (!empty($tool['icon'])): ?>
                                        <img src="<?= htmlspecialchars($tool['icon']) ?>" alt="">
                                    <?php else: ?>
                                        <?= htmlspecialchars($tool['emoji'] ?? '•') ?>
                                    <?php endif; ?>
                                </span>

                                <span class="tool-link-title"><?= htmlspecialchars($tool['title']) ?></span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </section>
            <?php endforeach; ?>
        </div>

        <div id="menuEmptyState" class="menu-empty-state">
            لا توجد أداة مطابقة لبحثك.
        </div>

        <div class="side-account-box dx-side-language">
            <div class="side-account-label">اللغة</div>
            <div class="dx-side-lang-grid">
                <a class="dx-side-lang <?= (!$dxInEn && !$dxInTr) ? 'active' : '' ?>" href="<?=htmlspecialchars($dxBasePrefix.$dxCurrentPage)?>"><span>🌐</span><b>AR</b><small>العربية</small></a>
                <a class="dx-side-lang <?= $dxInEn ? 'active' : '' ?>" href="<?=htmlspecialchars(($dxInEn ? '' : ($dxInTr ? '../en/' : 'en/')).$dxCurrentPage)?>"><span>🌐</span><b>EN</b><small>English</small></a>
                <a class="dx-side-lang <?= $dxInTr ? 'active' : '' ?>" href="<?=htmlspecialchars(($dxInTr ? '' : ($dxInEn ? '../tr/' : 'tr/')).$dxCurrentPage)?>"><span>🌐</span><b>TR</b><small>Türkçe</small></a>
            </div>
        </div>

        <div class="side-account-box">
            <div class="side-account-label">الحساب</div>

            <?php if ($isLoggedIn): ?>
                <a href="profile.php" class="account-link">
                    <span class="account-icon">👤</span>
                    <span>حسابي</span>
                </a>

                <?php if ($plan === 'free'): ?>
                    <a href="payment.php" class="account-link premium">
                        <span class="account-icon">⭐</span>
                        <span>الترقية إلى Premium</span>
                    </a>
                <?php endif; ?>

                <a href="logout.php" class="account-link danger" onclick="return confirm('هل تريد تسجيل الخروج؟');">
                    <span class="account-icon">🚪</span>
                    <span>تسجيل الخروج</span>
                </a>
            <?php else: ?>
                <button type="button" class="account-link" onclick="openAuth('tool')" style="width:100%;border:0;background:transparent;font-family:inherit;cursor:pointer;text-align:right;">
                    <span class="account-icon">🔑</span>
                    <span>تسجيل الدخول</span>
                </button>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
window.isLoggedIn = <?= $isLoggedIn ? 'true' : 'false' ?>;
window.userPlan = <?= json_encode($plan, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;
</script>

<script>
function toggleToolGroup(button) {
    const group = button.closest('.tool-group');
    if (!group) return;

    const isOpen = group.classList.toggle('open');
    button.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
}

function normalizeToolSearch(text) {
    return String(text || '')
        .toLowerCase()
        .trim()
        .replace(/[أإآ]/g, 'ا')
        .replace(/ة/g, 'ه')
        .replace(/ى/g, 'ي');
}

function filterToolMenu(value) {
    const query = normalizeToolSearch(value);
    const groups = document.querySelectorAll('#toolGroupsContainer .tool-group');
    let totalVisible = 0;

    groups.forEach(group => {
        const links = group.querySelectorAll('.tool-link');
        let visibleInGroup = 0;

        links.forEach(link => {
            const name = normalizeToolSearch(link.dataset.toolName || link.textContent);
            const matches = !query || name.includes(query);

            link.style.display = matches ? 'flex' : 'none';

            if (matches) {
                visibleInGroup++;
                totalVisible++;
            }
        });

        group.style.display = visibleInGroup > 0 ? '' : 'none';

        if (query && visibleInGroup > 0) {
            group.classList.add('open');
            const header = group.querySelector('.tool-group-header');
            if (header) header.setAttribute('aria-expanded', 'true');
        }
    });

    const homeLink = document.querySelector('.nav-home-link');
    if (homeLink) {
        const homeMatches = !query || normalizeToolSearch(homeLink.dataset.toolName).includes(query);
        homeLink.style.display = homeMatches ? 'flex' : 'none';
        if (query && homeMatches) totalVisible++;
    }

    const emptyState = document.getElementById('menuEmptyState');
    if (emptyState) {
        emptyState.style.display = totalVisible === 0 ? 'block' : 'none';
    }
}

// عند فتح القائمة، ضع المؤشر في البحث فقط على الشاشات الكبيرة.


</script>
