<?php
// Start session and check admin authentication
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['admin_id'])) {
    redirect('login.php');
}

$adminId       = $_SESSION['admin_id'];
$adminUsername = $_SESSION['admin_username'] ?? 'Admin';
$adminRole     = $_SESSION['admin_role'] ?? 'admin';

$conn = getConnection();

$stmt = $conn->prepare("SELECT * FROM admins WHERE id = ?");
$stmt->bind_param("i", $adminId);
$stmt->execute();
$adminData = $stmt->get_result()->fetch_assoc();

if (!$adminData) {
    session_destroy();
    redirect('login.php');
}

$currentPage = basename($_SERVER['PHP_SELF']);
$siteName    = getSiteName();
$themeColor  = getSetting('theme_color', '#5B77F5');
$flash       = getFlash();

function hexToRgb($hex) {
    $hex = str_replace('#', '', $hex);
    if (strlen($hex) == 3) {
        $r = hexdec(substr($hex,0,1).substr($hex,0,1));
        $g = hexdec(substr($hex,1,1).substr($hex,1,1));
        $b = hexdec(substr($hex,2,1).substr($hex,2,1));
    } else {
        $r = hexdec(substr($hex,0,2));
        $g = hexdec(substr($hex,2,2));
        $b = hexdec(substr($hex,4,2));
    }
    return "$r, $g, $b";
}
$rgbColor = hexToRgb($themeColor);

function darkenColor($hex, $percent) {
    $hex = str_replace('#', '', $hex);
    $r = max(0, hexdec(substr($hex,0,2)) * (1 - $percent/100));
    $g = max(0, hexdec(substr($hex,2,2)) * (1 - $percent/100));
    $b = max(0, hexdec(substr($hex,4,2)) * (1 - $percent/100));
    return sprintf("#%02x%02x%02x", $r, $g, $b);
}

// ✅ FIX: cap darkening so we never produce a solid-blue background that
// looks like the page broke. 85% of a vivid blue → near-pure-blue tones
// that fill the viewport when content fails to render. Cap at 90%
// effective darkening so even the dark theme uses a desaturated bg.
$darkBg   = darkenColor($themeColor, 92);   // was 85 — too blue
$darkerBg = darkenColor($themeColor, 94);   // was 90
$cardBg   = darkenColor($themeColor, 80);   // was 75

/* ── DIGITAL PRODUCTS STATS (for badges) ── */
$pendingProductOrders = 0;
$totalActiveProducts  = 0;
$npChk = $conn->query("SHOW TABLES LIKE 'digital_products'");
if ($npChk && $npChk->num_rows > 0) {
    $totalActiveProducts = intval($conn->query("SELECT COUNT(*) as c FROM digital_products WHERE status='active'")->fetch_assoc()['c'] ?? 0);
}
$ppChk = $conn->query("SHOW TABLES LIKE 'product_purchases'");
if ($ppChk && $ppChk->num_rows > 0) {
    $pendingProductOrders = intval($conn->query("SELECT COUNT(*) as c FROM product_purchases WHERE status='pending'")->fetch_assoc()['c'] ?? 0);
}

/* ── PENDING WITHDRAWALS badge ── */
$pendingWithdrawals = intval($conn->query("SELECT COUNT(*) as c FROM withdrawals WHERE status='pending'")->fetch_assoc()['c'] ?? 0);

/* ── PENDING TASK APPROVALS badge ── */
$pendingApprovals = intval($conn->query("SELECT COUNT(*) as c FROM task_completions WHERE status='pending'")->fetch_assoc()['c'] ?? 0);

/* ── PENDING SPIN DEPOSITS badge ── */
$pendingSpinDeposits = 0;
$sdChk = $conn->query("SELECT COUNT(*) as c FROM transactions WHERE wallet_type='spin' AND type='credit' AND status='pending'");
if ($sdChk) $pendingSpinDeposits = intval($sdChk->fetch_assoc()['c'] ?? 0);

/* ── PENDING CHAT FOREIGNERS PAYMENTS badge ── */
$pendingCfPayments = 0;
$cfChk = $conn->query("SHOW TABLES LIKE 'chat_foreigners_payments'");
if ($cfChk && $cfChk->num_rows > 0) {
    $cfPQ = $conn->query("SELECT COUNT(*) as c FROM chat_foreigners_payments WHERE status='pending'");
    if ($cfPQ) $pendingCfPayments = intval($cfPQ->fetch_assoc()['c'] ?? 0);
}
$chatSpinBadge = $pendingSpinDeposits + $pendingCfPayments;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo isset($pageTitle) ? htmlspecialchars($pageTitle).' - ' : ''; ?>Admin — <?php echo htmlspecialchars($siteName); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap">

    <!-- INSTANT THEME LOADER (no flash) -->
    <script>(function(){document.documentElement.setAttribute('data-theme',localStorage.getItem('adminTheme')||'dark');})();</script>

    <style>
        :root {
            --theme-color: <?php echo $themeColor; ?>;
            --theme-rgb:   <?php echo $rgbColor; ?>;
        }
        * { margin:0; padding:0; box-sizing:border-box; }
        html, body { font-family:'Inter',-apple-system,sans-serif; min-height:100vh; transition:background .3s,color .3s; }

        /* ── HARDCODED BACKGROUND LOCKDOWN ──────────────────────────────
           Always paint body with a literal neutral color (not a CSS var),
           with !important, so no child page CSS, gradient, or broken theme
           variable can ever turn the whole viewport solid blue. The theme
           color is still used for accents (logo, badges, etc.) via vars.  */
        html { background:#0f172a !important; }
        body { background:#0f172a !important; color:#f1f5f9; }
        html[data-theme="light"]      { background:#ffffff !important; }
        html[data-theme="light"] body { background:#ffffff !important; color:#0f172a; }

        /* ── DARK ── using neutral dark, not theme-darkened, to avoid solid-blue washout ── */
        html[data-theme="dark"], html[data-theme="dark"] body { background:#0f172a !important; color:#f1f5f9; }
        html[data-theme="dark"] {
            --dark-bg:#0f172a;
            --darker-bg:#0b1120;
            --card-bg:#1e293b;
            --border-color:rgba(255,255,255,.1);
            --text-primary:#f1f5f9;
            --text-secondary:#94a3b8;
        }
        /* ── LIGHT ── */
        html[data-theme="light"] {
            --dark-bg:#fff;
            --darker-bg:#f8f9fa;
            --card-bg:#fff;
            --border-color:#e2e8f0;
            --text-primary:#0f172a;
            --text-secondary:#475569;
        }

        /* ── HEADER ── */
        .top-header {
            position:fixed; top:0; left:0; right:0; height:70px;
            background:var(--darker-bg); border-bottom:1px solid var(--border-color);
            display:flex; align-items:center; justify-content:space-between;
            padding:0 24px; z-index:1000; transition:all .3s;
        }
        .header-left  { display:flex; align-items:center; gap:20px; }
        .header-right { display:flex; align-items:center; gap:12px; }

        .mobile-menu-btn {
            display:none; width:40px; height:40px;
            background:var(--card-bg); border:1px solid var(--border-color); border-radius:8px;
            color:var(--text-primary); cursor:pointer;
            align-items:center; justify-content:center; font-size:18px; transition:all .3s;
        }

        .site-brand { font-size:24px; font-weight:900; display:flex; align-items:center; gap:12px; }
        .brand-logo {
            width:40px; height:40px;
            background:linear-gradient(135deg,<?php echo $themeColor; ?>,#ec4899);
            border-radius:10px; display:flex; align-items:center; justify-content:center;
            color:#fff; font-size:20px;
        }
        .brand-text {
            background:linear-gradient(135deg,<?php echo $themeColor; ?>,#ec4899);
            -webkit-background-clip:text; -webkit-text-fill-color:transparent; background-clip:text;
        }
        .admin-badge {
            padding:4px 10px;
            background:linear-gradient(135deg,<?php echo $themeColor; ?>,#ec4899);
            color:#fff; border-radius:6px; font-size:11px; font-weight:700;
            text-transform:uppercase; letter-spacing:.5px;
        }

        .header-icon {
            position:relative; width:40px; height:40px;
            background:var(--card-bg); border:1px solid var(--border-color); border-radius:8px;
            display:flex; align-items:center; justify-content:center;
            cursor:pointer; transition:all .3s; color:var(--text-secondary);
            text-decoration:none;
        }
        .header-icon:hover { background:var(--border-color); color:var(--text-primary); transform:translateY(-2px); }

        .hbadge {
            position:absolute; top:-5px; right:-5px;
            min-width:17px; height:17px; border-radius:9px;
            background:#ef4444; color:#fff; font-size:9px; font-weight:800;
            display:flex; align-items:center; justify-content:center;
            padding:0 3px; border:2px solid var(--darker-bg); line-height:1;
        }

        .notification-dot {
            position:absolute; top:8px; right:8px;
            width:8px; height:8px; background:#ef4444; border-radius:50%;
            border:2px solid var(--darker-bg);
        }

        .profile-btn {
            display:flex; align-items:center; gap:8px; padding:6px 12px;
            background:var(--card-bg); border:1px solid var(--border-color); border-radius:8px;
            cursor:pointer; transition:all .3s; text-decoration:none; color:var(--text-primary);
        }
        .profile-btn:hover { background:var(--border-color); transform:translateY(-2px); }
        .profile-avatar {
            width:32px; height:32px;
            background:linear-gradient(135deg,<?php echo $themeColor; ?>,#ec4899);
            border-radius:50%; display:flex; align-items:center; justify-content:center;
            font-weight:700; font-size:14px; color:#fff;
        }
        .profile-name { font-size:14px; font-weight:600; }

        /* ── SIDEBAR ── */
        .sidebar {
            position:fixed; left:0; top:70px; width:260px;
            height:calc(100vh - 70px); background:var(--darker-bg);
            border-right:1px solid var(--border-color);
            padding:16px 0 40px; overflow-y:auto; z-index:999; transition:all .3s;
        }
        .sidebar::-webkit-scrollbar { width:4px; }
        .sidebar::-webkit-scrollbar-thumb { background:var(--border-color); border-radius:2px; }

        .sidebar-section { margin-bottom:6px; }
        .section-label {
            padding:10px 20px 5px;
            font-size:10px; font-weight:700; text-transform:uppercase;
            letter-spacing:1.2px; color:var(--text-secondary);
        }

        .nav-item {
            display:flex; align-items:center; gap:12px;
            padding:10px 20px; color:var(--text-secondary);
            text-decoration:none; transition:all .2s;
            font-size:13.5px; font-weight:500; position:relative;
        }
        .nav-item:hover { background:var(--card-bg); color:var(--text-primary); }
        .nav-item.active {
            background:linear-gradient(90deg,rgba(<?php echo $rgbColor; ?>,.15),transparent);
            color:var(--text-primary); border-left:3px solid <?php echo $themeColor; ?>;
            font-weight:600;
        }
        .nav-item i { width:18px; text-align:center; font-size:14px; flex-shrink:0; }

        .nbadge {
            margin-left:auto; padding:1px 7px; border-radius:20px;
            font-size:10px; font-weight:700; white-space:nowrap;
        }
        .nbadge.red   { background:rgba(239,68,68,.12);  color:#ef4444; }
        .nbadge.amber { background:rgba(245,158,11,.12); color:#d97706; animation:pulse 2s infinite; }
        .nbadge.green { background:rgba(16,185,129,.12); color:#059669; }
        .nbadge.blue  { background:rgba(99,102,241,.12); color:#6366f1; }
        html[data-theme="dark"] .nbadge.red   { background:rgba(239,68,68,.2); }
        html[data-theme="dark"] .nbadge.amber { background:rgba(245,158,11,.2); color:#fbbf24; }
        html[data-theme="dark"] .nbadge.green { background:rgba(16,185,129,.2); color:#34d399; }
        html[data-theme="dark"] .nbadge.blue  { background:rgba(99,102,241,.2); color:#818cf8; }
        @keyframes pulse { 0%,100%{opacity:1} 50%{opacity:.4} }

        .sdiv { height:1px; background:var(--border-color); margin:4px 16px; }

        /* ── MAIN CONTENT ── */
        .main-content {
            margin-left:260px; margin-top:70px;
            padding:28px 24px; min-height:calc(100vh - 70px);
            background:#0f172a;
            position:relative; z-index:1;
        }
        html[data-theme="light"] .main-content { background:#ffffff; }

        /* ── FLASH ── */
        .flash-message {
            background:var(--card-bg); border:1px solid var(--border-color);
            border-radius:12px; padding:14px 16px; margin-bottom:20px;
            display:flex; align-items:center; gap:12px;
            font-size:14px; font-weight:500;
        }
        .flash-message i { font-size:18px; }
        .flash-success { border-color:#10b981; background:rgba(16,185,129,.08); color:#10b981; }
        .flash-error   { border-color:#ef4444; background:rgba(239,68,68,.08);  color:#ef4444; }
        .flash-warning { border-color:#f59e0b; background:rgba(245,158,11,.08); color:#f59e0b; }
        .flash-info    { border-color:#3b82f6; background:rgba(59,130,246,.08); color:#3b82f6; }

        /* ── RESPONSIVE ── */
        @media(max-width:768px){
            .mobile-menu-btn { display:flex; }
            .sidebar { transform:translateX(-100%); }
            .sidebar.active { transform:translateX(0); box-shadow:10px 0 30px rgba(0,0,0,.2); }
            .main-content { margin-left:0; padding:16px 12px; }
            .site-brand { font-size:18px; }
            .brand-logo { width:34px; height:34px; font-size:16px; }
            .header-right { gap:7px; }
            .profile-name,.admin-badge { display:none; }
        }
    </style>
</head>
<body>

<!-- ── HEADER ── -->
<div class="top-header">
    <div class="header-left">
        <div class="mobile-menu-btn" onclick="toggleSidebar()">
            <i class="fas fa-bars" id="mico"></i>
        </div>
        <div class="site-brand">
            <div class="brand-logo"><i class="fas fa-shield-alt"></i></div>
            <span class="brand-text"><?php echo htmlspecialchars($siteName); ?></span>
            <span class="admin-badge">Admin</span>
        </div>
    </div>

    <div class="header-right">
        <a href="admin_products.php" class="header-icon" title="Digital Products">
            <i class="fas fa-store"></i>
            <?php if($totalActiveProducts > 0):?>
            <span class="hbadge" style="background:var(--theme-color)"><?php echo $totalActiveProducts; ?></span>
            <?php endif; ?>
        </a>
        <a href="withdrawals.php" class="header-icon" title="Pending Withdrawals">
            <i class="fas fa-money-bill-wave"></i>
            <?php if($pendingWithdrawals > 0):?>
            <span class="hbadge"><?php echo $pendingWithdrawals; ?></span>
            <?php endif; ?>
        </a>
        <div class="header-icon" title="Notifications">
            <i class="fas fa-bell"></i>
            <span class="notification-dot"></span>
        </div>
        <div class="header-icon" id="themeToggleBtn" title="Toggle Theme" onclick="toggleTheme()">
            <i class="fas fa-moon" id="themeIcon"></i>
        </div>
        <a href="profile.php" class="profile-btn">
            <div class="profile-avatar"><?php echo strtoupper(substr($adminUsername,0,1)); ?></div>
            <span class="profile-name"><?php echo htmlspecialchars($adminUsername); ?></span>
        </a>
        <a href="settings.php" class="header-icon" title="Settings">
            <i class="fas fa-cog"></i>
        </a>
    </div>
</div>

<!-- ── SIDEBAR ── -->
<div class="sidebar" id="sidebar">

    <!-- OVERVIEW -->
    <div class="sidebar-section">
        <div class="section-label">Overview</div>
        <a href="dashboard.php" class="nav-item <?php echo $currentPage==='dashboard.php'?'active':''; ?>">
            <i class="fas fa-th-large"></i> Dashboard
        </a>
    </div>

    <!-- USERS -->
    <div class="sidebar-section">
        <div class="section-label">Users</div>
        <a href="users.php" class="nav-item <?php echo $currentPage==='users.php'?'active':''; ?>">
            <i class="fas fa-users"></i> All Users
        </a>
    </div>

    <!-- CONTENT -->
    <div class="sidebar-section">
        <div class="section-label">Content</div>
        <a href="manage-tasks.php" class="nav-item <?php echo $currentPage==='manage-tasks.php'?'active':''; ?>">
            <i class="fas fa-tasks"></i> Manage Tasks
        </a>
        <a href="task-settings.php" class="nav-item <?php echo $currentPage==='task-settings.php'?'active':''; ?>">
            <i class="fas fa-sliders-h"></i> Task Settings
        </a>
        <a href="task-approvals.php" class="nav-item <?php echo $currentPage==='task-approvals.php'?'active':''; ?>">
            <i class="fas fa-clipboard-check"></i> Task Approvals
            <?php if($pendingApprovals > 0):?>
            <span class="nbadge amber"><?php echo $pendingApprovals; ?></span>
            <?php endif; ?>
        </a>
    </div>

    <!-- EARN & PLAY -->
    <div class="sidebar-section">
        <div class="section-label">Earn &amp; Play</div>
        <a href="chat_spin_admin.php" class="nav-item <?php echo $currentPage==='chat_spin_admin.php'?'active':''; ?>">
            <i class="fas fa-hurricane"></i> Chat &amp; Spin
            <?php if($chatSpinBadge > 0):?>
            <span class="nbadge amber"><?php echo $chatSpinBadge; ?></span>
            <?php endif; ?>
        </a>
        <a href="chat_spin_admin.php?tab=chat" class="nav-item <?php echo ($currentPage==='chat_spin_admin.php'&&($_GET['tab']??'')==='chat')?'active':''; ?>" style="padding-left:36px;font-size:12.5px">
            <i class="fas fa-satellite-dish" style="font-size:12px"></i> Chat Foreigners
            <?php if($pendingCfPayments > 0):?>
            <span class="nbadge red"><?php echo $pendingCfPayments; ?></span>
            <?php endif; ?>
        </a>
        <a href="chat_spin_admin.php?tab=spin" class="nav-item <?php echo ($currentPage==='chat_spin_admin.php'&&($_GET['tab']??'')==='spin')?'active':''; ?>" style="padding-left:36px;font-size:12.5px">
            <i class="fas fa-hurricane" style="font-size:12px"></i> Spin &amp; Win
            <?php if($pendingSpinDeposits > 0):?>
            <span class="nbadge amber"><?php echo $pendingSpinDeposits; ?></span>
            <?php endif; ?>
        </a>
        <a href="chat_spin_admin.php?tab=users" class="nav-item <?php echo ($currentPage==='chat_spin_admin.php'&&($_GET['tab']??'')==='users')?'active':''; ?>" style="padding-left:36px;font-size:12.5px">
            <i class="fas fa-user-check" style="font-size:12px"></i> User Access
        </a>
    </div>

    <!-- DIGITAL STORE -->
    <div class="sidebar-section">
        <div class="section-label">Digital Store</div>
        <a href="admin_products.php" class="nav-item <?php echo $currentPage==='admin_products.php'?'active':''; ?>">
            <i class="fas fa-store"></i> Products
            <?php if($totalActiveProducts > 0):?>
            <span class="nbadge blue"><?php echo $totalActiveProducts; ?></span>
            <?php endif; ?>
        </a>
        <a href="admin_product_form.php" class="nav-item <?php echo $currentPage==='admin_product_form.php'?'active':''; ?>">
            <i class="fas fa-plus-circle"></i> Add Product
        </a>
        <?php if($pendingProductOrders > 0):?>
        <a href="admin_products.php?orders=pending" class="nav-item <?php echo ($currentPage==='admin_products.php'&&($_GET['orders']??'')==='pending')?'active':''; ?>">
            <i class="fas fa-hourglass-half"></i> Pending Orders
            <span class="nbadge amber"><?php echo $pendingProductOrders; ?></span>
        </a>
        <?php endif; ?>
    </div>

    <!-- FINANCE -->
    <div class="sidebar-section">
        <div class="section-label">Finance</div>
        <a href="withdrawals.php" class="nav-item <?php echo $currentPage==='withdrawals.php'?'active':''; ?>">
            <i class="fas fa-money-bill-wave"></i> Withdrawals
            <?php if($pendingWithdrawals > 0):?>
            <span class="nbadge red"><?php echo $pendingWithdrawals; ?></span>
            <?php endif; ?>
        </a>
        <a href="withhistory.php" class="nav-item <?php echo $currentPage==='withhistory.php'?'active':''; ?>">
            <i class="fas fa-clock-rotate-left"></i> Withdrawal History
        </a>
    </div>

    <!-- SYSTEM -->
    <div class="sidebar-section">
        <div class="section-label">System</div>
        <a href="countries.php" class="nav-item <?php echo $currentPage==='countries.php'?'active':''; ?>">
            <i class="fas fa-globe"></i> Countries
        </a>
        <a href="bonuses.php" class="nav-item <?php echo $currentPage==='bonuses.php'?'active':''; ?>">
            <i class="fas fa-gift"></i> Bonus Rules
        </a>
        <a href="announcements.php" class="nav-item <?php echo $currentPage==='announcements.php'?'active':''; ?>">
            <i class="fas fa-bullhorn"></i> Announcements
        </a>
    </div>

    <!-- SETTINGS -->
    <div class="sidebar-section">
        <div class="section-label">Settings</div>
        <a href="settings.php" class="nav-item <?php echo $currentPage==='settings.php'?'active':''; ?>">
            <i class="fas fa-cog"></i> General Settings
        </a>
        <a href="admins.php" class="nav-item <?php echo $currentPage==='admins.php'?'active':''; ?>">
            <i class="fas fa-user-shield"></i> Manage Admins
        </a>
        <div class="sdiv"></div>
        <a href="logout.php" class="nav-item">
            <i class="fas fa-sign-out-alt"></i> Logout
        </a>
    </div>

</div>

<!-- ── MAIN CONTENT ── -->
<div class="main-content">
    <?php if ($flash): ?>
    <div class="flash-message flash-<?php echo $flash['type']; ?>">
        <i class="fas fa-<?php
            echo match($flash['type']) {
                'success' => 'check-circle',
                'error'   => 'exclamation-circle',
                'warning' => 'exclamation-triangle',
                default   => 'info-circle'
            };
        ?>"></i>
        <span><?php echo htmlspecialchars($flash['message']); ?></span>
    </div>
    <?php endif; ?>

<script>
function toggleTheme() {
    var html = document.documentElement;
    var icon = document.getElementById('themeIcon');
    var isDark = html.getAttribute('data-theme') === 'dark';
    html.setAttribute('data-theme', isDark ? 'light' : 'dark');
    icon.className = isDark ? 'fas fa-sun' : 'fas fa-moon';
    localStorage.setItem('adminTheme', isDark ? 'light' : 'dark');
}
document.addEventListener('DOMContentLoaded', function() {
    var t = localStorage.getItem('adminTheme') || 'dark';
    var icon = document.getElementById('themeIcon');
    if (icon) icon.className = t === 'light' ? 'fas fa-sun' : 'fas fa-moon';
});
function toggleSidebar() {
    var sb = document.getElementById('sidebar');
    var ico = document.getElementById('mico');
    var open = sb.classList.toggle('active');
    ico.className = open ? 'fas fa-xmark' : 'fas fa-bars';
}
document.addEventListener('click', function(e) {
    var sb = document.getElementById('sidebar');
    var btn = document.querySelector('.mobile-menu-btn');
    if (window.innerWidth <= 768 && sb && sb.classList.contains('active')) {
        if (!sb.contains(e.target) && btn && !btn.contains(e.target)) {
            sb.classList.remove('active');
            document.getElementById('mico').className = 'fas fa-bars';
        }
    }
});

/* ─────────────────────────────────────────────────────────────────
   PAGE-BROKE DETECTOR
   If the page renders with no real content under .main-content,
   show a visible error message instead of a silent blank screen.
   This catches PHP fatal errors, missing footers, or layout breaks.
   ───────────────────────────────────────────────────────────────── */
window.addEventListener('load', function() {
    setTimeout(function() {
        var main = document.querySelector('.main-content');
        if (!main) return;
        // Count meaningful visible children (ignore flash banner & scripts)
        var realChildren = Array.from(main.children).filter(function(el){
            if (el.tagName === 'SCRIPT' || el.tagName === 'STYLE') return false;
            if (el.classList && el.classList.contains('flash-message')) return false;
            // Element must have visible dimensions
            var r = el.getBoundingClientRect();
            return r.width > 0 && r.height > 0;
        });
        if (realChildren.length === 0) {
            var warn = document.createElement('div');
            warn.style.cssText = 'background:#1e293b;border:2px solid #ef4444;color:#fff;padding:24px;border-radius:14px;margin-top:20px;font-family:Inter,sans-serif';
            warn.innerHTML =
                '<h3 style="color:#f87171;margin-bottom:10px;font-size:18px">⚠️ Page Render Issue</h3>' +
                '<p style="color:#cbd5e1;line-height:1.6;font-size:14px">The page didn\'t render any content. ' +
                'This usually means a PHP error occurred (check your server error_log) or a required include is missing. ' +
                'Try refreshing the page or going back.</p>' +
                '<div style="margin-top:14px;display:flex;gap:8px">' +
                  '<button onclick="location.reload()" style="padding:8px 14px;background:#3b82f6;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:600">Reload</button>' +
                  '<button onclick="history.back()" style="padding:8px 14px;background:#475569;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:600">Go Back</button>' +
                '</div>';
            main.appendChild(warn);
        }
    }, 200);
});
</script>