const fs = require('fs');
let content = fs.readFileSync('public_html/js/admin-panel.js', 'utf8');

// I need to find where the `function checkMobile()` starts or something close.
// Let's just restore the file up to line 290 and then append the correct functions, 
// then append from filterOrders() onwards.

const parts = content.split('function filterOrders() {');
if(parts.length === 2) {
    let top = parts[0].substring(0, parts[0].lastIndexOf('// 4. Stop spinning'));
    // We add the rest of the missing code
    const missing = `        // 4. Stop spinning
        if (icon) {
            icon.classList.remove('fa-spin');
            btn.disabled = false;
            btn.style.opacity = '1';
        }
    }
}

function toggleMobileSidebar() {
    document.getElementById('gvSidebar').classList.toggle('mobile-open');
}

// ── Dashboard / Overview ──
async function loadDashboard() {
    try {
        const res = await fetch(\`\${BASE}/api/admin/dashboard\`, { headers: headers() });
        if (!res.ok) throw new Error('Failed');
        const data = await res.json();

        document.getElementById('stat-clients').textContent = fmtNum(data.stats.customers);
        document.getElementById('stat-captains').textContent = fmtNum(data.stats.captains);
        document.getElementById('stat-orders').textContent = fmtNum(data.stats.orders);
        document.getElementById('stat-revenue').textContent = fmtNum(data.stats.revenue) + ' ج.س';

        renderStatusBar(data.ordersByStatus || {});
    } catch(e) { console.error('Dashboard error:', e); }

    loadLiveOrders();
    loadOnlineCaptainsCount();
    initMiniMap();
}

function renderStatusBar(counts) {
    const order = ['pending', 'scheduled', 'accepted', 'picked_up', 'delivered', 'cancelled'];
    const total = order.reduce((sum, k) => sum + (counts[k] || 0), 0);

    const bar = document.getElementById('statusBar');
    if (total === 0) {
        bar.innerHTML = '<div class="gv-empty"><i class="fas fa-chart-bar"></i><p>لا توجد طلبات بعد</p></div>';
        return;
    }

    bar.innerHTML = order.map(status => {
        const count = counts[status] || 0;
        const percent = total > 0 ? (count / total * 100) : 0;
        return \`
            <div class="gv-status-bar-row">
                <div class="gv-status-bar-label">
                    <div class="dot gv-color-\${status}"></div>
                    <span>\${statusLabel(status)}</span>
                </div>
                <div class="gv-status-bar-progress">
                    <div class="gv-status-bar-fill gv-color-\${status}" style="width:\${percent}%;"></div>
                </div>
                <div class="gv-status-bar-count">\${fmtNum(count)}</div>
                <div class="gv-status-bar-percent">\${percent.toFixed(1)}%</div>
            </div>
        \`;
    }).join('');
}

async function loadOnlineCaptainsCount() {
    try {
        const res = await fetch(\`\${BASE}/api/admin/active-captains\`, { headers: headers() });
        if (!res.ok) return;
        const captains = await res.json();
        const online = captains.filter(c => c.isActive && c.currentLocation && c.currentLocation.lat).length;
        document.getElementById('stat-online').textContent = online;
    } catch(e) {}
}

async function loadLiveOrders() {
    try {
        const res = await fetch(\`\${BASE}/api/admin/orders/live\`, { headers: headers() });
        if (!res.ok) throw new Error('Failed');
        let live = await res.json();

        const feed = document.getElementById('liveOrdersFeed');
        const counter = document.getElementById('liveOrdersCount');
        if (counter) counter.textContent = \`\${live.length} طلب\`;

        if (live.length === 0) {
            feed.innerHTML = '<div class="gv-empty"><i class="fas fa-inbox"></i><p>لا توجد طلبات نشطة</p></div>';
            return;
        }

        feed.innerHTML = live.slice(0, 30).map(o => \`
            <div class="gv-order-item" onclick="viewOrder('\${o._id}')\">
                <div class="gv-order-status \${o.status}"></div>
                <div class="gv-order-info">
                    <h5>\${window.escapeHtml(o.client?.name || 'عميل')} \${o.captain ? '← ' + window.escapeHtml(o.captain.name) : ''}</h5>
                    <p>\${window.escapeHtml(o.pickup?.address || '?')} → \${window.escapeHtml(o.dropoff?.address || '?')}</p>
                </div>
                <div style="display:flex;flex-direction:column;align-items:flex-end;gap:4px;">
                    <span class="gv-badge \${o.status}">\${statusLabel(o.status)}</span>
                    <div class="gv-order-price">\${o.price} ج.س</div>
                </div>
            </div>
        \`).join('');
    } catch(e) {
        console.error('Live orders error:', e);
    }
}

// ── All Orders ──
async function loadAllOrders() {
    try {
        const res = await fetch(\`\${BASE}/api/admin/orders\`, { headers: headers() });
        if (!res.ok) throw new Error('Failed');
        allOrders = sortByNewest(await res.json()); // ✅ newest first
        renderAllOrders(allOrders);
    } catch(e) { console.error(e); }
}

function filterOrders() {`;
    
    fs.writeFileSync('public_html/js/admin-panel.js', top + missing + parts[1]);
    console.log('Fixed file successfully');
} else {
    console.log('Could not split properly');
}
