<!DOCTYPE html>

<html lang="ar" dir="rtl">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>دليل أمة مسلمة | البوابة الشاملة</title>

    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">

    <style>

        :root {

            --bg: #f8fafc;

            --surface: #ffffff;

            --text: #0f172a;

            --text-light: #64748b;

            --border: #e2e8f0;

            --primary: #0f766e;

            --primary-hover: #115e59;

            --danger: #ef4444;

            --warning: #f59e0b;

            --radius: 12px;

            --shadow-sm: 0 1px 3px rgba(0,0,0,0.04);

            --shadow-md: 0 4px 6px -1px rgba(0,0,0,0.06);

        }

        [data-theme="dark"] {

            --bg: #0b0f19;

            --surface: #141c2e;

            --text: #f8fafc;

            --text-light: #94a3b8;

            --border: #1e293b;

            --shadow-sm: 0 1px 3px rgba(0,0,0,0.3);

            --shadow-md: 0 4px 6px rgba(0,0,0,0.4);

        }

        /* تظليل ملون للأقسام وتوريثه للأبناء */

        .theme-emerald {

            --card-color: #0d9488;

            --card-bg: rgba(13, 148, 136, 0.07);

            --card-border: rgba(13, 148, 136, 0.28);

        }

        [data-theme="dark"] .theme-emerald {

            --card-bg: rgba(13, 148, 136, 0.15);

            --card-border: rgba(20, 184, 166, 0.35);

        }

        .theme-blue {

            --card-color: #0284c7;

            --card-bg: rgba(2, 132, 199, 0.07);

            --card-border: rgba(2, 132, 199, 0.28);

        }

        [data-theme="dark"] .theme-blue {

            --card-bg: rgba(2, 132, 199, 0.15);

            --card-border: rgba(56, 189, 248, 0.35);

        }

        .theme-purple {

            --card-color: #7c3aed;

            --card-bg: rgba(124, 58, 237, 0.07);

            --card-border: rgba(124, 58, 237, 0.28);

        }

        [data-theme="dark"] .theme-purple {

            --card-bg: rgba(124, 58, 237, 0.15);

            --card-border: rgba(167, 139, 250, 0.35);

        }

        .theme-amber {

            --card-color: #d97706;

            --card-bg: rgba(217, 119, 6, 0.07);

            --card-border: rgba(217, 119, 6, 0.28);

        }

        [data-theme="dark"] .theme-amber {

            --card-bg: rgba(217, 119, 6, 0.15);

            --card-border: rgba(251, 191, 36, 0.35);

        }

        .theme-rose {

            --card-color: #e11d48;

            --card-bg: rgba(225, 29, 72, 0.07);

            --card-border: rgba(225, 29, 72, 0.28);

        }

        [data-theme="dark"] .theme-rose {

            --card-bg: rgba(225, 29, 72, 0.15);

            --card-border: rgba(251, 113, 133, 0.35);

        }

        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Cairo', sans-serif; }

        body {

            background-color: var(--bg);

            color: var(--text);

            min-height: 100vh;

            display: flex;

            flex-direction: column;

            transition: background 0.3s, color 0.3s;

        }

        header {

            background-color: var(--surface);

            border-bottom: 1px solid var(--border);

            position: sticky;

            top: 0;

            z-index: 40;

            box-shadow: var(--shadow-sm);

        }

        .header-container {

            max-width: 1100px;

            margin: 0 auto;

            padding: 12px 18px;

            display: flex;

            align-items: center;

            justify-content: space-between;

            gap: 12px;

            flex-wrap: wrap;

        }

        .logo-area {

            display: flex;

            align-items: center;

            gap: 10px;

            cursor: pointer;

            user-select: none;

        }

        .logo-icon { font-size: 1.6rem; }

        .logo-text h1 { font-size: 1.15rem; font-weight: 800; line-height: 1.2; }

        .logo-text p { font-size: 0.75rem; color: var(--text-light); }

        .header-actions {

            display: flex;

            align-items: center;

            gap: 10px;

        }

        .search-box {

            position: relative;

            width: 210px;

        }

        .search-box input {

            width: 100%;

            padding: 7px 14px 7px 32px;

            border-radius: 20px;

            border: 1px solid var(--border);

            background-color: var(--bg);

            color: var(--text);

            font-size: 0.85rem;

            outline: none;

        }

        .search-icon {

            position: absolute;

            left: 10px;

            top: 50%;

            transform: translateY(-50%);

            color: var(--text-light);

            font-size: 0.8rem;

        }

        .btn-icon {

            background: var(--bg);

            border: 1px solid var(--border);

            color: var(--text);

            width: 36px;

            height: 36px;

            border-radius: 50%;

            display: flex;

            align-items: center;

            justify-content: center;

            cursor: pointer;

            font-size: 0.95rem;

            transition: all 0.2s;

        }

        .btn-add {

            background-color: var(--primary);

            color: white;

            border: none;

            padding: 7px 14px;

            border-radius: 20px;

            font-size: 0.85rem;

            font-weight: 700;

            display: flex;

            align-items: center;

            gap: 5px;

            cursor: pointer;

            transition: background 0.2s;

        }

        .btn-add:hover { background-color: var(--primary-hover); }

        .nav-bar {

            max-width: 1100px;

            margin: 14px auto 0;

            padding: 0 18px;

            display: flex;

            align-items: center;

            justify-content: space-between;

            width: 100%;

        }

        .breadcrumbs {

            display: flex;

            align-items: center;

            gap: 6px;

            font-size: 0.85rem;

            font-weight: 600;

            color: var(--text-light);

            flex-wrap: wrap;

        }

        .breadcrumb-item { cursor: pointer; transition: color 0.2s; }

        .breadcrumb-item:hover { color: var(--primary); }

        .breadcrumb-item.active { color: var(--text); cursor: default; }

        .btn-back {

            background: var(--surface);

            border: 1px solid var(--border);

            padding: 5px 12px;

            border-radius: 16px;

            font-size: 0.8rem;

            font-weight: 600;

            color: var(--text);

            cursor: pointer;

            display: flex;

            align-items: center;

            gap: 4px;

            transition: all 0.2s;

        }

        main {

            flex: 1;

            max-width: 1100px;

            margin: 12px auto 30px;

            padding: 0 18px;

            width: 100%;

        }

        /* شبكة الكروت بحجم أصغر ومدمج */

        .grid {

            display: grid;

            grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));

            gap: 12px;

        }

        .card {

            background-color: var(--card-bg, var(--surface));

            border: 1px solid var(--card-border, var(--border));

            border-radius: var(--radius);

            padding: 14px 16px;

            display: flex;

            flex-direction: column;

            justify-content: space-between;

            box-shadow: var(--shadow-sm);

            transition: all 0.2s ease;

            cursor: pointer;

            position: relative;

            min-height: 120px;

        }

        .card:hover {

            transform: translateY(-2px);

            box-shadow: var(--shadow-md);

            border-color: var(--card-color, var(--primary));

        }

        .card-top {

            display: flex;

            justify-content: space-between;

            align-items: flex-start;

            margin-bottom: 8px;

        }

        .card-icon {

            font-size: 1.4rem;

            width: 38px;

            height: 38px;

            border-radius: 10px;

            background: var(--surface);

            border: 1px solid var(--card-border, var(--border));

            display: flex;

            align-items: center;

            justify-content: center;

        }

        .card-actions { display: flex; gap: 4px; }

        .card-btn {

            background: var(--surface);

            border: 1px solid var(--border);

            width: 26px;

            height: 26px;

            border-radius: 6px;

            display: flex;

            align-items: center;

            justify-content: center;

            cursor: pointer;

            font-size: 0.75rem;

            color: var(--text-light);

            transition: all 0.2s;

        }

        .card-btn.btn-edit:hover { background-color: var(--warning); color: white; }

        .card-btn.btn-delete:hover { background-color: var(--danger); color: white; }

        .card-title {

            font-size: 0.98rem;

            font-weight: 700;

            color: var(--text);

            margin-bottom: 4px;

            line-height: 1.35;

        }

        .card-desc {

            font-size: 0.75rem;

            color: var(--text-light);

            line-height: 1.4;

            margin-bottom: 10px;

            display: -webkit-box;

            -webkit-line-clamp: 2;

            -webkit-box-orient: vertical;

            overflow: hidden;

        }

        .card-bottom {

            display: flex;

            align-items: center;

            justify-content: space-between;

            font-size: 0.75rem;

            font-weight: 700;

            color: var(--card-color, var(--primary));

            margin-top: auto;

            padding-top: 6px;

            border-top: 1px dashed var(--card-border, var(--border));

        }

        .card-add-placeholder {

            border: 2px dashed var(--border);

            background: transparent;

            min-height: 120px;

            display: flex;

            flex-direction: column;

            align-items: center;

            justify-content: center;

            gap: 6px;

            color: var(--text-light);

            cursor: pointer;

            border-radius: var(--radius);

            font-size: 0.85rem;

            font-weight: 600;

            transition: all 0.2s;

        }

        .card-add-placeholder:hover {

            border-color: var(--primary);

            color: var(--primary);

            background: var(--surface);

        }

        .modal-overlay {

            position: fixed;

            top: 0; left: 0; width: 100%; height: 100%;

            background-color: rgba(0, 0, 0, 0.55);

            backdrop-filter: blur(3px);

            display: none;

            align-items: center;

            justify-content: center;

            z-index: 100;

            padding: 16px;

        }

        .modal-overlay.active { display: flex; }

        .modal {

            background-color: var(--surface);

            border-radius: var(--radius);

            width: 100%;

            max-width: 450px;

            padding: 20px;

            box-shadow: var(--shadow-md);

            border: 1px solid var(--border);

        }

        .modal-header {

            display: flex;

            justify-content: space-between;

            align-items: center;

            margin-bottom: 16px;

        }

        .modal-header h2 { font-size: 1.15rem; font-weight: 800; }

        .close-btn { background: none; border: none; font-size: 1.3rem; color: var(--text-light); cursor: pointer; }

        .form-group { margin-bottom: 12px; }

        .form-group label { display: block; margin-bottom: 4px; font-size: 0.85rem; font-weight: 600; }

        .form-group input, .form-group select {

            width: 100%;

            padding: 8px 12px;

            border-radius: 8px;

            border: 1px solid var(--border);

            background-color: var(--bg);

            color: var(--text);

            font-size: 0.85rem;

            outline: none;

        }

        .emoji-picker { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 6px; }

        .emoji-opt {

            font-size: 1.1rem;

            cursor: pointer;

            padding: 3px 6px;

            border-radius: 6px;

            border: 1px solid var(--border);

            background: var(--bg);

        }

        .modal-footer {

            display: flex;

            justify-content: flex-end;

            gap: 8px;

            margin-top: 18px;

        }

        .btn-cancel {

            background: var(--bg);

            border: 1px solid var(--border);

            color: var(--text);

            padding: 7px 14px;

            border-radius: 6px;

            font-size: 0.85rem;

            font-weight: 600;

            cursor: pointer;

        }

        .btn-save {

            background: var(--primary);

            border: none;

            color: white;

            padding: 7px 18px;

            border-radius: 6px;

            font-size: 0.85rem;

            font-weight: 700;

            cursor: pointer;

        }

        .toast {

            position: fixed;

            bottom: 20px;

            left: 20px;

            background-color: var(--text);

            color: var(--bg);

            padding: 10px 20px;

            border-radius: 20px;

            font-weight: 700;

            font-size: 0.85rem;

            transform: translateY(80px);

            opacity: 0;

            transition: all 0.3s ease;

            z-index: 200;

        }

        .toast.show { transform: translateY(0); opacity: 1; }

        @media (max-width: 600px) {

            .header-container { flex-direction: column; align-items: stretch; }

            .header-actions { justify-content: space-between; }

            .search-box { flex: 1; }

            .grid { grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; }

            .card { padding: 12px; min-height: 110px; }

            .card-title { font-size: 0.9rem; }

        }

    </style>

</head>

<body>

    <header>

        <div class="header-container">

            <div class="logo-area" onclick="navigateTo([])">

                <span class="logo-icon">🕌</span>

                <div class="logo-text">

                    <h1>دليل أمة مسلمة</h1>

                    <p>البوابة الشاملة للشيتات والتطبيقات</p>

                </div>

            </div>

            <div class="header-actions">

                <div class="search-box">

                    <span class="search-icon">🔍</span>

                    <input type="text" id="searchInput" placeholder="بحث سريع..." oninput="filterCards()">

                </div>

                <button class="btn-icon" onclick="toggleTheme()" id="themeBtn" title="تبديل المظهر">🌙</button>

                <button class="btn-add" onclick="openAddModal()">

                    <span>➕</span> إضافة جديد

                </button>

            </div>

        </div>

    </header>

    <div class="nav-bar">

        <div class="breadcrumbs" id="breadcrumbs"></div>

        <button class="btn-back" id="backBtn" onclick="goBack()" style="display: none;">

            <span>➡️</span> رجوع

        </button>

    </div>

    <main>

        <div class="grid" id="itemsGrid"></div>

    </main>

    <div class="modal-overlay" id="itemModal">

        <div class="modal">

            <div class="modal-header">

                <h2 id="modalTitle">إضافة عنصر جديد</h2>

                <button class="close-btn" onclick="closeModal()">✕</button>

            </div>

            <input type="hidden" id="editItemId">

            <div class="form-group">

                <label>النوع</label>

                <select id="itemType" onchange="toggleTypeFields()">

                    <option value="link">رابط مباشر (شيت، تطبيق، موقع)</option>

                    <option value="folder">مجلد / قسم فرعي</option>

                </select>

            </div>

            <div class="form-group">

                <label>العنوان</label>

                <input type="text" id="itemTitle" placeholder="مثال: شيت أمة 1">

            </div>

            <div class="form-group" id="urlGroup">

                <label>الرابط (URL)</label>

                <input type="url" id="itemUrl" placeholder="https://docs.google.com/...">

            </div>

            <div class="form-group">

                <label>الأيقونة</label>

                <input type="text" id="itemIcon" placeholder="📊" maxlength="5">

                <div class="emoji-picker">

                    <span class="emoji-opt" onclick="setIcon('📊')">📊</span>

                    <span class="emoji-opt" onclick="setIcon('📄')">📄</span>

                    <span class="emoji-opt" onclick="setIcon('📋')">📋</span>

                    <span class="emoji-opt" onclick="setIcon('📁')">📁</span>

                    <span class="emoji-opt" onclick="setIcon('🕌')">🕌</span>

                    <span class="emoji-opt" onclick="setIcon('💡')">💡</span>

                    <span class="emoji-opt" onclick="setIcon('🖥️')">🖥️</span>

                    <span class="emoji-opt" onclick="setIcon('📱')">📱</span>

                    <span class="emoji-opt" onclick="setIcon('🎓')">🎓</span>

                    <span class="emoji-opt" onclick="setIcon('👨‍🏫')">👨‍🏫</span>

                    <span class="emoji-opt" onclick="setIcon('📜')">📜</span>

                    <span class="emoji-opt" onclick="setIcon('💸')">💸</span>

                    <span class="emoji-opt" onclick="setIcon('📧')">📧</span>

                    <span class="emoji-opt" onclick="setIcon('🤝')">🤝</span>

                </div>

            </div>

            <div class="form-group">

                <label>الوصف (اختياري)</label>

                <input type="text" id="itemDesc" placeholder="ملاحظة سريعة">

            </div>

            <div class="modal-footer">

                <button class="btn-cancel" onclick="closeModal()">إلغاء</button>

                <button class="btn-save" onclick="saveItem()">حفظ</button>

            </div>

        </div>

    </div>

    <div class="toast" id="toast">✅ تم الحفظ</div>

    <!-- Firebase SDK -->

    <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js"></script>

    <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-database.js"></script>

    <script>

        const firebaseConfig = {

            apiKey: "AIzaSyC6up8sbxjUVSvJGjFcRXomT8DeZcq99uk",

            authDomain: "beso-1a325.firebaseapp.com",

            databaseURL: "https://beso-1a325-default-rtdb.firebaseio.com",

            projectId: "beso-1a325",

            storageBucket: "beso-1a325.firebasestorage.app",

            messagingSenderId: "336091712074",

            appId: "1:336091712074:web:f207ceaa5b14e783e034b3"

        };

        firebase.initializeApp(firebaseConfig);

        const db = firebase.database();

        const colorThemes = ['theme-emerald', 'theme-blue', 'theme-purple', 'theme-amber', 'theme-rose'];

        const initialDirectory = {

            title: "الرئيسية",

            items: [

                {

                    id: "sheets_section",

                    title: "الشيتات",

                    icon: "📊",

                    type: "folder",

                    theme: "theme-emerald",

                    desc: "شيتات المتابعة والطلاب والمعلمين",

                    items: [

                        {

                            id: "ummah_sheets",

                            title: "أمة مسلمة",

                            icon: "🕌",

                            type: "folder",

                            desc: "شيتات أمة مسلمة (1 - 6)",

                            items: [

                                { id: "u1", title: "شيت أمة مسلمة 1️⃣", type: "link", icon: "📄", url: "https://docs.google.com/spreadsheets/d/1kWgJgD7JhhjFQoYZvd73oii0dE2o7rbcUM6pWbYiNDY/edit?usp=drivesdk" },

                                { id: "u2", title: "شيت أمة مسلمة 2️⃣", type: "link", icon: "📄", url: "https://docs.google.com/spreadsheets/d/1NS7FQKpDU4ILtiHPG3snWd5APfGl0ItPdYmmxJZE8tY/edit?usp=drivesdk" },

                                { id: "u3", title: "شيت أمة مسلمة 3️⃣", type: "link", icon: "📄", url: "https://docs.google.com/spreadsheets/d/1T8ECCJpMdBeZT9_dw_Q5wbzfHeS7Nzksjf2VzlKXcI4/edit?usp=drivesdk" },

                                { id: "u4", title: "شيت أمة مسلمة 4️⃣", type: "link", icon: "📄", url: "https://docs.google.com/spreadsheets/d/1mNJ3yybtvN3mV3mPxTAl_z1jr_dHLBDF3wBG1zzlCwk/edit?usp=drivesdk" },

                                { id: "u5", title: "شيت أمة مسلمة 5️⃣", type: "link", icon: "📄", url: "https://docs.google.com/spreadsheets/d/1N6eHVlz5H7piDC5mjdUmlaMyJuDPkoRq4F42JNwChYQ/edit?usp=drivesdk" },

                                { id: "u6", title: "شيت أمة مسلمة 6️⃣", type: "link", icon: "📄", url: "https://docs.google.com/spreadsheets/d/10--PvMia5nu9SYoadP0_ikEl8_EDZxZRjmk44fFslcA/edit?usp=drivesdk" }

                            ]

                        },

                        {

                            id: "nour_sheets",

                            title: "نور العلم",

                            icon: "💡",

                            type: "folder",

                            desc: "شيتات نور العلم",

                            items: [

                                { id: "n1", title: "شيت نور العلم 1️⃣", type: "link", icon: "📄", url: "https://docs.google.com/spreadsheets/d/1kWgJgD7JhhjFQoYZvd73oii0dE2o7rbcUM6pWbYiNDY/edit?usp=drivesdk" },

                                { id: "n2", title: "شيت نور العلم 2️⃣", type: "link", icon: "📄", url: "https://docs.google.com/spreadsheets/d/1NS7FQKpDU4ILtiHPG3snWd5APfGl0ItPdYmmxJZE8tY/edit?usp=drivesdk" },

                                { id: "n3", title: "شيت نور العلم 3️⃣", type: "link", icon: "📄", url: "https://docs.google.com/spreadsheets/d/1T8ECCJpMdBeZT9_dw_Q5wbzfHeS7Nzksjf2VzlKXcI4/edit?usp=drivesdk" },

                                { id: "n4", title: "شيت نور العلم 4️⃣", type: "link", icon: "📄", url: "https://docs.google.com/spreadsheets/d/1mNJ3yybtvN3mV3mPxTAl_z1jr_dHLBDF3wBG1zzlCwk/edit?usp=drivesdk" },

                                { id: "n5", title: "شيت نور العلم 5️⃣", type: "link", icon: "📄", url: "https://docs.google.com/spreadsheets/d/1N6eHVlz5H7piDC5mjdUmlaMyJuDPkoRq4F42JNwChYQ/edit?usp=drivesdk" }

                            ]

                        },

                        { id: "adm_students", title: "الشيت الإداري للطلاب", type: "link", icon: "🎓", desc: "بيانات ومتابعة الطلاب", url: "https://docs.google.com/spreadsheets/d/1sZ9xP0xBsrBQIls-sQWO4IUVG-Imip5UCxDlktS8pNk/edit?usp=drivesdk" },

                        { id: "adm_teachers", title: "الشيت الإداري للمعلمين", type: "link", icon: "👨‍🏫", desc: "بيانات ومواعيد المعلمين", url: "https://docs.google.com/spreadsheets/d/1wgPzZxQkrDgl0Mtfs_n09-lPAAPQBBupFeGgCDnkQdo/edit?usp=drivesdk" },

                        { id: "sup_new", title: "شيت تنظيم المشرفات جدد", type: "link", icon: "📋", desc: "توزيع المشرفات الجدد", url: "https://docs.google.com/spreadsheets/d/12nzB3eOsnqwyxVtHrpvpTSiGw7S2YlpyWllj3WI-kNU/edit?usp=sharing" },

                        { id: "sup_current", title: "شيت تنظيم المشرفات الحاليين", type: "link", icon: "🗂️", desc: "متابعة المشرفات الحاليين", url: "https://docs.google.com/spreadsheets/d/1NEpEkPyxxc1jekkSLmItdOdncvvOisaUrneTDjmTikw/edit?gid=0#gid=0" },

                        { id: "agents", title: "شيت الوسطاء", type: "link", icon: "🤝", desc: "حسابات الوسطاء", url: "https://docs.google.com/spreadsheets/d/1q1gdL9yNWhdGAKrq7UoD2g-vaQNr9C6cZSJ-KuxtCUY/edit?usp=sharing" }

                    ]

                },

                {

                    id: "system_link",

                    title: "السيستم",

                    icon: "🖥️",

                    type: "link",

                    theme: "theme-blue",

                    desc: "نظام إدارة الأكاديمية",

                    url: "https://system.muslimsummah.com/"

                },

                {

                    id: "apps_section",

                    title: "تطبيقات الأكاديمية",

                    icon: "📱",

                    type: "folder",

                    theme: "theme-purple",

                    desc: "الشهادات والرواتب والخدمات",

                    items: [

                        { id: "app_u_cert", title: "شهادات أمة", type: "link", icon: "📜", desc: "شهادات أمة مسلمة", url: "https://ummahcerts.vercel.app/" },

                        { id: "app_n_cert", title: "شهادات نور", type: "link", icon: "🎖️", desc: "شهادات نور العلم", url: "https://nourcerts.vercel.app/" },

                        { id: "app_salary", title: "تحويل رواتب", type: "link", icon: "💸", desc: "مساعد الرواتب وفودافون كاش", url: "https://vodafone-cash-helper.ahmedenoo.workers.dev/" },

                        { id: "app_fake_email", title: "ايميلات فيك", type: "link", icon: "📧", desc: "توليد الإيميلات المؤقتة", url: "https://emailummah.vercel.app/" }

                    ]

                }

            ]

        };

        let directoryData = null;

        let currentPath = [];

        window.addEventListener('load', () => {

            history.replaceState({ path: [] }, '', '');

        });

        // زر الرجوع في الهاتف

        window.addEventListener('popstate', (e) => {

            const modal = document.getElementById('itemModal');

            if (modal.classList.contains('active')) {

                closeModal();

                return;

            }

            if (e.state && Array.isArray(e.state.path)) {

                navigateTo(e.state.path, false);

            } else {

                navigateTo([], false);

            }

        });

        db.ref('portal_directory').on('value', (snapshot) => {

            const data = snapshot.val();

            if (!data) {

                db.ref('portal_directory').set(initialDirectory);

            } else {

                directoryData = data;

                renderView();

            }

        });

        function getCurrentFolder() {

            if (!directoryData) return null;

            let folder = directoryData;

            for (const id of currentPath) {

                if (!folder.items) folder.items = [];

                const next = folder.items.find(item => item.id === id);

                if (next && next.type === 'folder') {

                    folder = next;

                } else {

                    currentPath = [];

                    return directoryData;

                }

            }

            return folder;

        }

        function getInheritedTheme() {

            if (currentPath.length === 0 || !directoryData) return null;

            const rootItem = directoryData.items.find(x => x.id === currentPath[0]);

            if (rootItem && rootItem.theme) return rootItem.theme;

            const idx = directoryData.items.indexOf(rootItem);

            return colorThemes[idx % colorThemes.length];

        }

        function renderView() {

            const folder = getCurrentFolder();

            if (!folder) return;

            renderBreadcrumbs();

            const grid = document.getElementById('itemsGrid');

            grid.innerHTML = '';

            const inheritedTheme = getInheritedTheme();

            const items = folder.items || [];

            items.forEach((item, index) => {

                const card = document.createElement('div');

               

                let themeClass = inheritedTheme;

                if (!themeClass) {

                    themeClass = item.theme || colorThemes[index % colorThemes.length];

                }

                card.className = `card ${themeClass}`;

                card.setAttribute('data-title', (item.title || '').toLowerCase());

                card.setAttribute('data-desc', (item.desc || '').toLowerCase());

                const isFolder = item.type === 'folder';

                const count = isFolder ? (item.items ? item.items.length : 0) : null;

                card.innerHTML = `

                    <div class="card-top">

                        <div class="card-icon">${item.icon || (isFolder ? '📁' : '📄')}</div>

                        <div class="card-actions" onclick="event.stopPropagation()">

                            <button class="card-btn btn-edit" title="تعديل" onclick="openEditModal('${item.id}')">✏️</button>

                            <button class="card-btn btn-delete" title="حذف" onclick="deleteItem('${item.id}')">🗑️</button>

                        </div>

                    </div>

                    <div>

                        <h3 class="card-title">${item.title}</h3>

                        <p class="card-desc">${item.desc || (isFolder ? `${count} عناصر` : 'فتح مباشر')}</p>

                    </div>

                    <div class="card-bottom">

                        <span>${isFolder ? 'استعراض' : 'فتح الرابط'}</span>

                        <span>${isFolder ? '←' : '↗'}</span>

                    </div>

                `;

                card.onclick = () => {

                    if (isFolder) {

                        navigateTo([...currentPath, item.id], true);

                    } else if (item.url) {

                        window.open(item.url, '_blank');

                    }

                };

                grid.appendChild(card);

            });

            const addCard = document.createElement('div');

            addCard.className = 'card-add-placeholder';

            addCard.innerHTML = `

                <span style="font-size: 1.3rem;">➕</span>

                <p>إضافة هنا</p>

            `;

            addCard.onclick = openAddModal;

            grid.appendChild(addCard);

            document.getElementById('backBtn').style.display = currentPath.length > 0 ? 'flex' : 'none';

        }

        function renderBreadcrumbs() {

            const container = document.getElementById('breadcrumbs');

            container.innerHTML = '';

            const rootItem = document.createElement('span');

            rootItem.className = `breadcrumb-item ${currentPath.length === 0 ? 'active' : ''}`;

            rootItem.innerHTML = '<span>🏠</span> الرئيسية';

            rootItem.onclick = () => navigateTo([], true);

            container.appendChild(rootItem);

            let temp = directoryData;

            const pathIds = [];

            for (let i = 0; i < currentPath.length; i++) {

                const sep = document.createElement('span');

                sep.innerText = ' / ';

                sep.style.color = 'var(--text-light)';

                container.appendChild(sep);

                const id = currentPath[i];

                pathIds.push(id);

                const next = temp.items.find(x => x.id === id);

                if (next) {

                    const isLast = (i === currentPath.length - 1);

                    bItem = document.createElement('span');

                    bItem.className = `breadcrumb-item ${isLast ? 'active' : ''}`;

                    bItem.innerText = next.title;

                    const target = [...pathIds];

                    if (!isLast) {

                        bItem.onclick = () => navigateTo(target, true);

                    }

                    container.appendChild(bItem);

                    temp = next;

                }

            }

        }

        function navigateTo(path, pushState = true) {

            currentPath = path;

            if (pushState) {

                history.pushState({ path: currentPath }, '', '');

            }

            document.getElementById('searchInput').value = '';

            renderView();

            window.scrollTo({ top: 0, behavior: 'smooth' });

        }

        function goBack() {

            history.back();

        }

        function filterCards() {

            const q = document.getElementById('searchInput').value.toLowerCase().trim();

            document.querySelectorAll('.grid .card').forEach(card => {

                const title = card.getAttribute('data-title') || '';

                const desc = card.getAttribute('data-desc') || '';

                card.style.display = (title.includes(q) || desc.includes(q)) ? 'flex' : 'none';

            });

        }

        function openAddModal() {

            document.getElementById('modalTitle').innerText = 'إضافة جديد';

            document.getElementById('editItemId').value = '';

            document.getElementById('itemType').value = 'link';

            document.getElementById('itemTitle').value = '';

            document.getElementById('itemUrl').value = '';

            document.getElementById('itemIcon').value = '📄';

            document.getElementById('itemDesc').value = '';

            toggleTypeFields();

            document.getElementById('itemModal').classList.add('active');

        }

        function openEditModal(id) {

            const folder = getCurrentFolder();

            const item = folder.items.find(x => x.id === id);

            if (!item) return;

            document.getElementById('modalTitle').innerText = 'تعديل';

            document.getElementById('editItemId').value = item.id;

            document.getElementById('itemType').value = item.type;

            document.getElementById('itemTitle').value = item.title || '';

            document.getElementById('itemUrl').value = item.url || '';

            document.getElementById('itemIcon').value = item.icon || '';

            document.getElementById('itemDesc').value = item.desc || '';

            toggleTypeFields();

            document.getElementById('itemModal').classList.add('active');

        }

        function closeModal() {

            document.getElementById('itemModal').classList.remove('active');

        }

        function toggleTypeFields() {

            const isFolder = document.getElementById('itemType').value === 'folder';

            document.getElementById('urlGroup').style.display = isFolder ? 'none' : 'block';

            if (isFolder && document.getElementById('itemIcon').value === '📄') {

                document.getElementById('itemIcon').value = '📁';

            }

        }

        function setIcon(emoji) {

            document.getElementById('itemIcon').value = emoji;

        }

        function saveItem() {

            const id = document.getElementById('editItemId').value;

            const type = document.getElementById('itemType').value;

            const title = document.getElementById('itemTitle').value.trim();

            const url = document.getElementById('itemUrl').value.trim();

            const icon = document.getElementById('itemIcon').value.trim() || (type === 'folder' ? '📁' : '📄');

            const desc = document.getElementById('itemDesc').value.trim();

            if (!title) { alert('يرجى كتابة العنوان'); return; }

            if (type === 'link' && !url) { alert('يرجى وضع الرابط'); return; }

            const folder = getCurrentFolder();

            if (!folder.items) folder.items = [];

            if (id) {

                const item = folder.items.find(x => x.id === id);

                if (item) {

                    item.title = title;

                    item.type = type;

                    item.icon = icon;

                    item.desc = desc;

                    if (type === 'link') item.url = url;

                    else if (!item.items) item.items = [];

                }

            } else {

                const newItem = {

                    id: 'item_' + Date.now(),

                    title,

                    type,

                    icon,

                    desc,

                    url: type === 'link' ? url : '',

                    items: type === 'folder' ? [] : undefined,

                    theme: currentPath.length === 0 ? colorThemes[folder.items.length % colorThemes.length] : undefined

                };

                folder.items.push(newItem);

            }

            db.ref('portal_directory').set(directoryData)

              .then(() => {

                  showToast('☁️ تم الحفظ');

                  closeModal();

              })

              .catch(() => showToast('❌ فشل الحفظ'));

        }

        function deleteItem(id) {

            if (!confirm('هل أنت متأكد من الحذف؟')) return;

            const folder = getCurrentFolder();

            folder.items = folder.items.filter(x => x.id !== id);

            db.ref('portal_directory').set(directoryData)

              .then(() => showToast('🗑️ تم الحذف'))

              .catch(() => showToast('❌ حدث خطأ'));

        }

        function showToast(msg) {

            const toast = document.getElementById('toast');

            toast.innerText = msg;

            toast.classList.add('show');

            setTimeout(() => toast.classList.remove('show'), 2000);

        }

        function toggleTheme() {

            const isDark = document.body.getAttribute('data-theme') === 'dark';

            if (isDark) {

                document.body.removeAttribute('data-theme');

                localStorage.setItem('portal_theme', 'light');

                document.getElementById('themeBtn').innerText = '🌙';

            } else {

                document.body.setAttribute('data-theme', 'dark');

                localStorage.setItem('portal_theme', 'dark');

                document.getElementById('themeBtn').innerText = '☀️';

            }

        }

        if (localStorage.getItem('portal_theme') === 'dark') {

            document.body.setAttribute('data-theme', 'dark');

            document.getElementById('themeBtn').innerText = '☀️';

        }

    </script>

</body>

</html>