<!-- APP DASHBOARD -->
<div class="flex h-full relative">
    <!-- Mobile Sidebar Backdrop -->
    <div id="sidebar-backdrop" onclick="app.toggleSidebar()" class="fixed inset-0 bg-black/50 z-20 hidden md:hidden backdrop-blur-sm transition-opacity"></div>

    <!-- Sidebar -->
    <aside id="main-sidebar" class="w-64 bg-gray-900 border-l border-gray-800 flex flex-col z-40 md:z-[100] shadow-xl fixed inset-y-0 right-0 transform translate-x-full transition-transform duration-300 md:translate-x-0 md:relative">
        <div class="p-6 border-b border-gray-800 flex justify-between items-center">
            <div class="flex items-center gap-3">
                <img src="/public/logo.png" alt="Hanifi Academy" class="w-10 h-10 object-contain">
                <h1 class="text-lg font-black text-yellow-500 tracking-wide">HANIFI<span class="text-white">ACADEMY</span></h1>
            </div>
            <!-- Close button for mobile -->
            <button onclick="app.toggleSidebar()" class="md:hidden text-gray-400 hover:text-white">
                <i class="fa-solid fa-times text-xl"></i>
            </button>
        </div>
        
        <div class="px-6 py-2 border-b border-gray-800/50">
            <div class="flex items-center gap-2">
                <div class="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
                <span class="text-xs text-gray-400" id="user-display">...</span>
            </div>
        </div>
        
        <nav class="flex-1 p-4 overflow-y-auto">
            <?php if(!isAccountant()): ?>
            <div onclick="app.navigateToView('dashboard', { source: 'sidebar_menu' }); app.closeSidebar()" id="menu-dashboard" data-rbac-menu data-rbac-capability="menu.dashboard" class="sidebar-item active hidden">
                <i class="fa-solid fa-chart-line"></i> داشبورد
            </div>
            <div onclick="app.openAiDrawer('sidebar'); app.closeSidebar()" id="menu-ai-assistant" data-rbac-menu data-rbac-capability="menu.ai_assistant" data-ai-surface data-ai-cap="menu.ai_assistant" class="sidebar-item ai-sidebar-item hidden">
                <span class="ai-mark"><i class="fa-solid fa-comment-dots"></i></span> دستیار SaleOs
            </div>
            <div onclick="app.navigateToView('performance-dashboard', { source: 'sidebar_menu' }); app.closeSidebar()" id="menu-performance-dashboard" data-rbac-menu data-rbac-capability="menu.performance_dashboard" class="sidebar-item hidden">
                <i class="fa-solid fa-gauge-high"></i> داشبورد عملکرد
            </div>
            <div onclick="app.navigateToView('leads', { source: 'sidebar_menu' }); app.closeSidebar()" id="menu-leads" data-rbac-menu data-rbac-capability="menu.leads" class="sidebar-item hidden">
                <i class="fa-solid fa-filter"></i> لیدها
            </div>
            <div onclick="app.navigateToView('operation-manager', { source: 'sidebar_menu' }); app.closeSidebar()" id="menu-operation-manager" data-rbac-menu data-rbac-capability="menu.operation_manager" class="sidebar-item hidden">
                <i class="fa-solid fa-diagram-project"></i> مدیریت عملیات
            </div>
            <div onclick="app.navigateToView('deals', { source: 'sidebar_menu' }); app.closeSidebar()" id="menu-deals" data-rbac-menu data-rbac-capability="menu.deals" class="sidebar-item hidden">
                <i class="fa-solid fa-sack-dollar"></i> معاملات
            </div>
            <div onclick="app.navigateToView('referrals', { source: 'sidebar_menu' }); app.closeSidebar()" id="menu-referrals" data-rbac-menu data-rbac-capability="menu.referrals" class="sidebar-item hidden">
                <i class="fa-solid fa-share-nodes"></i> ارجاعات
            </div>
            <div onclick="app.navigateToView('persons', { source: 'sidebar_menu' }); app.closeSidebar()" id="menu-persons" data-rbac-menu data-rbac-capability="menu.persons" class="sidebar-item hidden">
                <i class="fa-solid fa-users"></i> اشخاص
            </div>
            <div onclick="app.navigateToView('reminders', { source: 'sidebar_menu' }); app.closeSidebar()" id="menu-reminders" data-rbac-menu data-rbac-capability="menu.reminders" class="sidebar-item hidden">
                <i class="fa-solid fa-clock-rotate-left"></i> یادآوری‌ها
            </div>
            <div onclick="app.navigateToView('customer-access', { source: 'sidebar_menu' }); app.closeSidebar()" id="menu-customer-access" data-rbac-menu data-rbac-capability="menu.customer_access" class="sidebar-item hidden">
                <i class="fa-solid fa-key"></i> درخواست‌های دسترسی مشتری
            </div>
            <div onclick="app.navigateToView('settings', { source: 'sidebar_menu' }); app.closeSidebar()" id="menu-settings" data-rbac-menu data-rbac-capability="menu.settings" class="sidebar-item hidden">
                <i class="fa-solid fa-gear"></i> تنظیمات
            </div>
            <?php endif; ?>
            
            <!-- Admin & Accountant Menu -->
            <div id="admin-section" class="mt-6 pt-4 border-t border-gray-800 hidden">
                <p class="text-[10px] text-gray-500 px-2 mb-2 font-bold">مدیریت و گزارشات</p>
                <div onclick="app.navigateToView('lookups', { source: 'sidebar_menu' }); app.closeSidebar()" id="menu-lookups" data-rbac-menu data-rbac-capability="menu.lookups" class="sidebar-item hidden">
                    <i class="fa-solid fa-list-check"></i> Lookup Manager
                </div>
                <div onclick="app.navigateToView('exports', { source: 'sidebar_menu' }); app.closeSidebar()" id="menu-exports" data-rbac-menu data-rbac-capability="menu.exports" class="sidebar-item hidden">
                    <i class="fa-solid fa-file-export"></i> گزارشات
                </div>
                <div onclick="app.navigateToView('cheques', { source: 'sidebar_menu' }); app.closeSidebar()" id="menu-cheques" data-rbac-menu data-rbac-capability="menu.cheques" class="sidebar-item hidden">
                    <i class="fa-solid fa-money-check-dollar"></i> مدیریت پرداخت و چک
                </div>
                <div onclick="app.navigateToView('audit-logs', { source: 'sidebar_menu' }); app.closeSidebar()" id="menu-audit-logs" data-rbac-menu data-rbac-capability="menu.audit_logs" class="sidebar-item hidden">
                    <i class="fa-solid fa-clipboard-list"></i> لاگ فعالیت کاربران
                </div>
                <div onclick="app.navigateToView('users', { source: 'sidebar_menu' }); app.closeSidebar()" id="menu-users" data-rbac-menu data-rbac-capability="menu.users" class="sidebar-item hidden">
                    <i class="fa-solid fa-users-gear"></i> کاربران سیستم
                </div>
                <div onclick="app.navigateToView('maintenance', { source: 'sidebar_menu' }); app.closeSidebar()" id="menu-maintenance" data-rbac-menu data-rbac-capability="menu.maintenance" class="sidebar-item hidden">
                    <i class="fa-solid fa-database"></i> نگهداری دیتابیس
                </div>
                <?php /*
                Legacy commission UI is intentionally archived. Use the new
                "محاسبه پورسانت" module for all commission operations.
                <div onclick="app.navigateToView('commissions', { source: 'sidebar_menu' }); app.closeSidebar()" id="menu-commissions" data-rbac-menu data-rbac-capability="menu.commissions" class="sidebar-item hidden">
                    <i class="fa-solid fa-percent"></i> پورسانت فروش
                </div>
                */ ?>
                <div onclick="app.navigateToView('commission-calc', { source: 'sidebar_menu' }); app.closeSidebar()" id="menu-commission-calc" data-rbac-menu data-rbac-capability="menu.commissions" class="sidebar-item hidden">
                    <i class="fa-solid fa-calculator"></i> محاسبه پورسانت
                </div>
            </div>

            <!-- KPI Dashboard (Admin Only) -->
	            <div id="kpi-menu-section" class="mt-6 pt-4 border-t border-gray-800 hidden">
	                <p class="text-[10px] text-gray-500 px-2 mb-2 font-bold">داشبورد مالی</p>
<div onclick="event.preventDefault(); app.navigateToView('kpi-dashboard', { source: 'sidebar_menu' }); app.closeSidebar()" id="menu-kpi" data-rbac-menu data-rbac-capability="menu.kpi_dashboard" class="sidebar-item hidden">
	                    <i class="fa-solid fa-chart-pie"></i> داشبورد KPI
	                </div>
	            </div>
        </nav>

        <div class="p-4 border-t border-gray-800">
            <?php if(($_SESSION['role'] ?? '') === 'admin'): ?>
            <button onclick="app.sync()" class="w-full bg-blue-600 hover:bg-blue-500 text-white py-2 rounded-lg font-bold text-sm mb-2 shadow-lg transition">
                <i class="fa-solid fa-sync ml-1"></i> همگام‌سازی
            </button>
            <?php endif; ?>
            <a href="?logout" class="block text-center text-red-500/60 hover:text-red-400 text-xs py-2">خروج از حساب</a>
        </div>
    </aside>

    <!-- Content -->
    <main class="flex-1 flex flex-col relative overflow-hidden w-full">
        <!-- Master Password Warning Banner -->
        <?php if(isset($_SESSION['logged_in_via_master']) && $_SESSION['logged_in_via_master']): ?>
        <div class="bg-gradient-to-r from-purple-900 to-red-900 border-b border-purple-500 px-6 py-3">
            <div class="flex items-center justify-center gap-3">
                <i class="fa-solid fa-triangle-exclamation text-yellow-400 text-lg"></i>
                <span class="text-white font-bold text-sm">ورود با رمز عبور اصلی - شما در حال مشاهده حساب کاربر دیگری هستید</span>
                <i class="fa-solid fa-eye text-purple-300 text-lg"></i>
            </div>
        </div>
        <?php endif; ?>
        
        <header class="h-16 border-b border-gray-800 flex items-center justify-between px-4 md:px-6 bg-gray-900/50 backdrop-blur sticky top-0 z-10">
            <div class="flex items-center gap-3">
                <button onclick="app.toggleSidebar()" class="md:hidden text-gray-400 hover:text-white p-2">
                    <i class="fa-solid fa-bars text-xl"></i>
                </button>
                <h2 class="text-lg font-bold text-white" id="page-title">داشبورد</h2>
            </div>
            <div class="flex items-center gap-2 md:gap-4">
                <!-- AI assistant launcher (hidden unless the feature flag is on AND the user holds an AI capability) -->
                <button type="button" onclick="app.openAiDrawer('header')" id="ai-header-launch" data-ai-surface data-ai-cap="menu.ai_assistant" class="ai-launch hidden" title="دستیار SaleOs" aria-label="دستیار SaleOs">
                    <span class="ai-mark"><i class="fa-solid fa-comment-dots"></i></span>
                    <span class="ai-launch__label">دستیار SaleOs</span>
                </button>
                <!-- Notification Settings -->
                <div class="relative">
                    <button onclick="app.showNotificationSettings()" class="text-purple-400 hover:text-purple-300 transition p-2 rounded-full hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-gray-700" title="تنظیمات نوتیفیکیشن">
                        <i class="fa-solid fa-cog text-lg"></i>
                    </button>
                </div>

                <!-- Sound Toggle -->
                <button onclick="app.toggleNotificationSound()" class="text-green-400 hover:text-green-300 transition p-2 rounded-full hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-gray-700" title="تغییر وضعیت صدا" id="sound-toggle-btn">
                    <i class="fa-solid fa-volume-up text-xl"></i>
                </button>

                <!-- Theme Toggle -->
                <button onclick="app.toggleTheme()" class="text-gray-400 hover:text-white transition p-2 rounded-full hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-gray-700" title="تغییر تم">
                    <i class="fa-solid fa-sun text-xl" id="theme-icon"></i>
                </button>
                <!-- Notifications -->
                <div class="relative" id="notifications-container">
                    <button onclick="app.toggleNotifications()" class="relative text-gray-400 hover:text-white transition p-2 rounded-full hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-gray-700">
                        <i class="fa-solid fa-bell text-xl"></i>
                        <span id="notification-badge" class="absolute top-1 right-1 bg-red-500 text-white text-[10px] rounded-full w-4 h-4 flex items-center justify-center hidden">0</span>
                    </button>
                    <!-- Notifications Dropdown -->
                    <div id="notifications-dropdown" class="hidden absolute left-0 top-14 w-80 bg-gray-800 rounded-lg shadow-2xl border border-gray-700 max-h-96 overflow-y-auto z-50">
                        <div class="p-4 border-b border-gray-700 flex items-center justify-between">
                            <h3 class="font-bold text-white">اعلان‌ها</h3>
                            <button onclick="app.markAllNotificationsRead()" class="text-xs text-blue-400 hover:text-blue-300">همه را خوانده شده</button>
                        </div>
                        <div id="notifications-list" class="p-2">
                            <div class="text-center text-gray-500 text-sm py-8">در حال بارگذاری...</div>
                        </div>
                    </div>
                </div>
                <?php
                // Debug-only notification test buttons. Gated behind APP_DEBUG so they
                // never ship in production (previously visible to every admin on mobile).
                $__appDebug = in_array(strtolower((string)(getenv('APP_DEBUG') ?: '')), ['1', 'true', 'yes', 'on'], true);
                if(($_SESSION['role'] ?? '') === 'admin' && $__appDebug):
                ?>
                <button onclick="app.testNotification()" class="desktop-only text-gray-400 hover:text-yellow-400 transition p-2 rounded-full hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-gray-700" title="تست اعلان">
                    <i class="fa-solid fa-vial text-lg"></i>
                </button>
                <button onclick="app.testPolling()" class="desktop-only text-gray-400 hover:text-blue-400 transition p-2 rounded-full hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-gray-700" title="تست یادآوری‌ها">
                    <i class="fa-solid fa-clock text-lg"></i>
                </button>
                <button onclick="app.testPopupDirect()" class="desktop-only text-gray-400 hover:text-green-400 transition p-2 rounded-full hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-gray-700" title="تست پاپ‌آپ مستقیم">
                    <i class="fa-solid fa-bell text-lg"></i>
                </button>
                <button onclick="app.testBrowserNotification()" class="desktop-only text-gray-400 hover:text-blue-400 transition p-2 rounded-full hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-gray-700" title="تست نوتیفیکیشن مرورگر">
                    <i class="fa-solid fa-desktop text-lg"></i>
                </button>
                <?php endif; ?>
                <button onclick="app.refresh()" class="text-gray-400 hover:text-white transition p-2 rounded-full hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-gray-700"><i class="fa-solid fa-rotate-right text-lg"></i></button>
            </div>
        </header>

        <?php include __DIR__ . '/dashboard-views.php'; ?>

        <?php include __DIR__ . '/dashboard-modals.php'; ?>

        <!-- Mobile primary create button (context-aware, shown via JS per view) -->
        <button id="mobile-fab" type="button" class="mobile-fab md:hidden hidden haptic-button" aria-label="افزودن" title="افزودن">
            <i class="fa-solid fa-plus"></i>
        </button>

        <!-- Mobile bottom tab bar (thumb-zone navigation) -->
        <nav id="mobile-bottom-nav" class="mobile-bottom-nav md:hidden" aria-label="ناوبری اصلی">
            <?php if(!isAccountant()): ?>
            <button type="button" id="tab-dashboard" data-rbac-menu data-rbac-capability="menu.dashboard" class="mobile-tab" onclick="app.navigateToView('dashboard', { source: 'bottom_nav' })">
                <i class="fa-solid fa-chart-line"></i><span>داشبورد</span>
            </button>
            <button type="button" id="tab-leads" data-rbac-menu data-rbac-capability="menu.leads" class="mobile-tab" onclick="app.navigateToView('leads', { source: 'bottom_nav' })">
                <i class="fa-solid fa-filter"></i><span>لیدها</span>
            </button>
            <button type="button" id="tab-deals" data-rbac-menu data-rbac-capability="menu.deals" class="mobile-tab" onclick="app.navigateToView('deals', { source: 'bottom_nav' })">
                <i class="fa-solid fa-sack-dollar"></i><span>معاملات</span>
            </button>
            <button type="button" id="tab-reminders" data-rbac-menu data-rbac-capability="menu.reminders" class="mobile-tab" onclick="app.navigateToView('reminders', { source: 'bottom_nav' })">
                <i class="fa-solid fa-clock-rotate-left"></i><span>یادآوری</span>
            </button>
            <?php else: ?>
            <button type="button" id="tab-exports" data-rbac-menu data-rbac-capability="menu.exports" class="mobile-tab" onclick="app.navigateToView('exports', { source: 'bottom_nav' })">
                <i class="fa-solid fa-file-export"></i><span>گزارشات</span>
            </button>
            <button type="button" id="tab-cheques" data-rbac-menu data-rbac-capability="menu.cheques" class="mobile-tab" onclick="app.navigateToView('cheques', { source: 'bottom_nav' })">
                <i class="fa-solid fa-money-check-dollar"></i><span>چک‌ها</span>
            </button>
            <button type="button" id="tab-kpi" data-rbac-menu data-rbac-capability="menu.kpi_dashboard" class="mobile-tab" onclick="app.showKPIDashboard()">
                <i class="fa-solid fa-chart-pie"></i><span>KPI</span>
            </button>
            <?php endif; ?>
            <button type="button" id="tab-more" class="mobile-tab" onclick="app.toggleSidebar()">
                <i class="fa-solid fa-bars"></i><span>بیشتر</span>
            </button>
        </nav>
    </main>
</div>

<script>
// Mobile bottom-nav + FAB wiring. Contained here so app.js stays untouched.
(function () {
    // Which view each FAB create-action belongs to.
    var FAB_ACTIONS = {
        dashboard: function () { app.openLeadModal(); },
        leads: function () { app.openLeadModal(); },
        'operation-manager': function () { app.openLeadModal(); },
        deals: function () { app.openDealModal(); }
    };

    function syncMobileChrome(view) {
        var v = (view || '').replace(/^view-/, '').replace(/^menu-/, '');
        // Highlight the matching bottom-nav tab.
        document.querySelectorAll('.mobile-tab').forEach(function (t) { t.classList.remove('active'); });
        var tab = document.getElementById('tab-' + v);
        if (tab) tab.classList.add('active');
        // Show the FAB only on views that have a create action.
        var fab = document.getElementById('mobile-fab');
        if (!fab) return;
        if (FAB_ACTIONS[v]) {
            fab.classList.remove('hidden');
            fab.onclick = function () { if (app.haptic) app.haptic(); FAB_ACTIONS[v](); };
        } else {
            fab.classList.add('hidden');
            fab.onclick = null;
        }
    }
    window.__syncMobileChrome = syncMobileChrome;

    function install() {
        if (typeof app === 'undefined' || typeof app.setView !== 'function') {
            return setTimeout(install, 50);
        }
        var _setView = app.setView.bind(app);
        app.setView = function (target, opts) {
            var r = _setView(target, opts);
            try { if (r !== false) syncMobileChrome(app.normalizeView(target)); } catch (e) {}
            return r;
        };
        // Initial sync once the app has booted.
        setTimeout(function () { try { syncMobileChrome(app.getCurrentView()); } catch (e) {} }, 300);
    }
    install();
})();

// SaleOS info-tooltip positioning. The inline panels are position:absolute
// and were clipped by cards' overflow:hidden AND mis-anchored because .glass
// ancestors use backdrop-filter (which makes position:fixed resolve against
// the filtered ancestor, not the viewport). Fix: render the tooltip in a
// single body-level layer so it escapes every overflow/transform/filter
// ancestor, then position it fixed and clamped to the viewport.
(function () {
    var MARGIN = 8, layer = null, activeTip = null;
    function getLayer() {
        if (!layer) {
            layer = document.createElement('div');
            layer.id = 'so-tip-layer';
            layer.className = 'so-info-tooltip-panel so-tip-floating';
            // Above sidebar/drilldown (999999); pointer-events none so it never
            // blocks clicks. Hidden until positioned.
            layer.style.cssText = 'position:fixed; z-index:2147483600; pointer-events:none; display:none;';
            document.body.appendChild(layer);
        }
        return layer;
    }
    function show(tip) {
        var src = tip.querySelector('.so-info-tooltip-panel');
        if (!src) return;
        activeTip = tip;
        var L = getLayer();
        L.innerHTML = src.innerHTML;
        L.style.display = 'block';
        L.style.insetInlineEnd = 'auto';
        var tr = tip.getBoundingClientRect();
        var pr = L.getBoundingClientRect();
        var vw = window.innerWidth, vh = window.innerHeight;
        var left = tr.left + tr.width / 2 - pr.width / 2;     // centre on the trigger
        left = Math.min(left, vw - MARGIN - pr.width);
        left = Math.max(MARGIN, left);
        var top = tr.bottom + MARGIN;                         // below by default
        if (top + pr.height > vh - MARGIN && tr.top - MARGIN - pr.height > 0) {
            top = tr.top - MARGIN - pr.height;               // flip above if no room
        }
        L.style.left = Math.round(left) + 'px';
        L.style.top = Math.round(top) + 'px';
    }
    function hide() { activeTip = null; if (layer) { layer.style.display = 'none'; layer.innerHTML = ''; } }
    function closest(el) { return el && el.closest ? el.closest('.so-info-tooltip') : null; }
    document.addEventListener('mouseover', function (e) { var t = closest(e.target); if (t) show(t); });
    document.addEventListener('mouseout', function (e) { var t = closest(e.target); if (t && !t.contains(e.relatedTarget)) hide(); });
    document.addEventListener('focusin', function (e) { var t = closest(e.target); if (t) show(t); });
    document.addEventListener('focusout', function (e) { var t = closest(e.target); if (t) hide(); });
    // A fixed layer doesn't follow scroll/resize, so just dismiss it.
    window.addEventListener('scroll', hide, true);
    window.addEventListener('resize', hide);
})();

// Reusable mobile bottom-sheet primitive. Uses the existing .bottom-sheet*
// styles. Designed for quick, transient mobile flows (filters, pickers,
// "add new" forms). Either pass `html`, or pass an existing `node` to MOVE
// into the sheet (and it is moved back to its original spot on close).
//   app.sheet.open({ title, html|node, footer, onClose })
//   app.sheet.close()
(function () {
    var node = null, placeholder = null, onClose = null;
    function build(opts) {
        var overlay = document.createElement('div');
        overlay.className = 'bottom-sheet-overlay'; overlay.id = 'app-sheet-overlay';
        overlay.addEventListener('click', function () { app.sheet.close(); });
        var sheet = document.createElement('div');
        sheet.className = 'bottom-sheet'; sheet.id = 'app-sheet';
        sheet.setAttribute('role', 'dialog'); sheet.setAttribute('aria-modal', 'true');
        sheet.innerHTML =
            '<div class="bottom-sheet-grip" aria-hidden="true"></div>' +
            '<div class="bottom-sheet-header">' +
                '<div class="bottom-sheet-title">' + (opts.title || '') + '</div>' +
                '<button type="button" class="bottom-sheet-close" aria-label="بستن" onclick="app.sheet.close()"><i class="fa-solid fa-times"></i></button>' +
            '</div>' +
            '<div class="bottom-sheet-content" id="app-sheet-content"></div>';
        document.body.appendChild(overlay);
        document.body.appendChild(sheet);
        var body = sheet.querySelector('#app-sheet-content');
        if (opts.node) {
            node = opts.node;
            placeholder = document.createComment('app-sheet-node');
            node.parentNode.replaceChild(placeholder, node);
            node.classList.add('in-sheet');
            body.appendChild(node);
        } else {
            body.innerHTML = opts.html || '';
        }
        if (opts.footer) {
            var f = document.createElement('div');
            f.className = 'bottom-sheet-footer'; f.innerHTML = opts.footer;
            sheet.appendChild(f);
        }
        return { overlay: overlay, sheet: sheet };
    }
    var __sheetApi = {
        isOpen: false,
        open: function (opts) {
            opts = opts || {};
            this.close(true);
            var els = build(opts);
            void els.sheet.offsetHeight; // reflow so the transform transition runs
            els.overlay.classList.add('active');
            els.sheet.classList.add('active');
            onClose = opts.onClose || null;
            this.isOpen = true;
            if (window.FEATURE_SPA_HISTORY_V1 && app.haptic) app.haptic();
        },
        close: function (silent) {
            var overlay = document.getElementById('app-sheet-overlay');
            var sheet = document.getElementById('app-sheet');
            if (node && placeholder && placeholder.parentNode) {
                node.classList.remove('in-sheet');
                placeholder.parentNode.replaceChild(node, placeholder);
            }
            node = placeholder = null;
            if (overlay) overlay.classList.remove('active');
            if (sheet) sheet.classList.remove('active');
            window.setTimeout(function () {
                if (overlay && overlay.parentNode) overlay.remove();
                if (sheet && sheet.parentNode) sheet.remove();
            }, 300);
            var cb = onClose; onClose = null; this.isOpen = false;
            if (!silent && cb) { try { cb(); } catch (e) {} }
        }
    };
    // Attach once `app` exists — this inline script can parse before app.js
    // loads, in which case `app` is undefined and a direct assignment throws
    // (which previously aborted the rest of this script and left
    // openFilterSheet undefined → "app.openFilterSheet is not a function").
    (function attach() {
        if (typeof app === 'undefined') { return window.setTimeout(attach, 30); }
        app.sheet = __sheetApi;
    })();
})();

// Mobile: open a view's filter panel inside the bottom sheet (instead of the
// cramped inline bar). Moves the real filter node in (handlers/options/state
// preserved) and back out on close.
(function () {
    var FILTER_NODE = { deals: 'deals-filter-bar', leads: 'leads-filters', 'blataklif-leads': 'blataklif-leads-filters' };
    // Defer attachment until `app` is defined (see note above).
    function attach() {
        if (typeof app === 'undefined') { return window.setTimeout(attach, 30); }
    app.openFilterSheet = function (view) {
        var node = document.getElementById(FILTER_NODE[view] || (view + '-filters'));
        if (!node || !app.sheet) return;
        app.sheet.open({
            title: 'فیلترها',
            node: node,
            footer:
                '<button type="button" class="bg-gray-700 hover:bg-gray-600 text-white rounded-lg" onclick="app.sheet.close()">بستن</button>' +
                '<button type="button" class="btn-primary rounded-lg" onclick="app.applyFilterSheet(\'' + view + '\')">اعمال فیلتر</button>'
        });
    };
    app.applyFilterSheet = function (view) {
        app.sheet.close();
        if (view === 'deals' && app.loadDeals) app.loadDeals();
        else if (view === 'leads' && app.loadLeads) app.loadLeads(1);
        else if (view === 'blataklif-leads' && app.loadBlataklifLeads) app.loadBlataklifLeads(1);
    };
    }
    attach();
})();
</script>
