<?php
// modules/store/widgets/success_box.php
if (basename($_SERVER['PHP_SELF']) == 'success_box.php') { die('Access Denied'); }

// استخراج ID سرور برای استفاده در توابع دریافت کانفیگ
$targetServerId = 1;
if (!empty($purchasedConfigs)) {
    $sampleUser = $purchasedConfigs[0]['account_username'];
    $stmtSrv = $pdo->prepare("SELECT server_id FROM inventory WHERE account_username = ? LIMIT 1");
    $stmtSrv->execute([$sampleUser]);
    $targetServerId = $stmtSrv->fetchColumn() ?: 1;
}

// آماده‌سازی دیتای اکسپورت برای جاوااسکریپت
$exportData = [];
foreach($purchasedConfigs as $c) {
    $exportData[] = [
        'username' => $c['account_username'],
        'sub_link' => $c['config_link']
    ];
}
?>

<div class="bg-white dark:bg-slate-800 border-2 border-emerald-500 rounded-3xl overflow-hidden mb-12 shadow-2xl animate-pulse-once flex flex-col" id="successContainer">
    
    <div class="bg-emerald-50 dark:bg-emerald-900/30 p-6 border-b border-emerald-100 dark:border-emerald-800 flex flex-col sm:flex-row justify-between items-center gap-4">
        <div>
            <h2 class="text-xl font-black text-emerald-800 dark:text-emerald-400 mb-1">🎉 <?php echo count($purchasedConfigs); ?> اشتراک با موفقیت صادر شد</h2>
            <p class="text-sm text-emerald-700 dark:text-emerald-500 font-bold">رسید خرید و اطلاعات اتصال در زیر قابل مشاهده است.</p>
        </div>
        <div class="flex gap-2">
            <button onclick="downloadConfigsTxt(this)" class="bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-2.5 px-4 rounded-xl shadow transition text-sm flex items-center gap-2">📄 TXT</button>
            <button onclick="downloadConfigsExcel(this)" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2.5 px-4 rounded-xl shadow transition text-sm flex items-center gap-2">📊 Excel</button>
        </div>
    </div>

    <div class="p-0 overflow-x-auto border-b border-gray-100 dark:border-slate-700 bg-white dark:bg-slate-800">
        <table class="w-full text-sm text-left text-gray-600 dark:text-gray-300" dir="ltr">
            <thead class="bg-emerald-100 dark:bg-emerald-900/50 text-emerald-800 dark:text-emerald-400">
                <tr>
                    <th class="px-6 py-4 rounded-tl-xl font-bold">Username</th>
                    <th class="px-6 py-4 font-bold">Subscription Link (Click to Copy)</th>
                    <th class="px-6 py-4 text-center rounded-tr-xl font-bold">Actions</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-emerald-50 dark:divide-emerald-900/20">
                <?php foreach($purchasedConfigs as $index => $c): ?>
                
                <tr class="hover:bg-emerald-50 dark:hover:bg-slate-700 transition relative z-10">
                    <td class="px-6 py-4 font-black text-gray-800 dark:text-gray-100"><?php echo htmlspecialchars($c['account_username']); ?></td>
                    <td class="px-6 py-4">
                        <div class="flex items-center gap-2 cursor-pointer group w-fit" onclick="copyTableLinkNative('<?php echo htmlspecialchars($c['config_link']); ?>', this)">
                            <span class="truncate max-w-[200px] md:max-w-[350px] inline-block font-mono text-xs text-blue-600 dark:text-blue-400"><?php echo htmlspecialchars($c['config_link']); ?></span>
                            <span class="copy-badge opacity-0 group-hover:opacity-100 transition text-emerald-600 dark:text-emerald-400 text-xs bg-emerald-100 dark:bg-emerald-900 px-2 py-1 rounded font-bold">Copy</span>
                        </div>
                    </td>
                    <td class="px-6 py-4">
                        <div class="flex items-center justify-center gap-2">
                           <button type="button" id="btn_toggle_<?php echo $index; ?>" onclick="toggleUserConfigs('<?php echo htmlspecialchars($c['config_link']); ?>', '<?php echo $targetServerId; ?>', <?php echo $index; ?>, this)" class="text-lg hover:scale-110 transition-transform bg-indigo-50 text-indigo-600 dark:bg-indigo-900/30 dark:text-indigo-400 p-1.5 rounded-lg border border-indigo-100 dark:border-indigo-800" title="نمایش لیست کانفیگ‌ها">🔽</button>
                           
                           <button type="button" onclick="copyRowConfigs('<?php echo htmlspecialchars($c['config_link']); ?>', '<?php echo $targetServerId; ?>', this)" class="text-lg hover:scale-110 transition-transform bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400 p-1.5 rounded-lg border border-blue-100 dark:border-blue-800" title="کپی ساب + تمام کانفیگ‌ها">📋</button>
                           
                           <button type="button" onclick="if(typeof showQRModal === 'function') showQRModal('<?php echo htmlspecialchars($c['config_link']); ?>', '<?php echo htmlspecialchars($c['account_username']); ?>')" class="text-lg hover:scale-110 transition-transform bg-gray-100 dark:bg-slate-700 p-1.5 rounded-lg border border-gray-200 dark:border-slate-600" title="کد QR ساب لینک">📱</button>
                        </div>
                    </td>
                </tr>

                <tr id="configs_row_<?php echo $index; ?>" class="hidden bg-[#f8fafc] dark:bg-[#0f172a] shadow-inner relative z-0">
                    <td colspan="3" class="p-0 border-b border-gray-200 dark:border-slate-700">
                        <div class="px-8 py-5" id="configs_container_<?php echo $index; ?>">
                            </div>
                    </td>
                </tr>
                
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <?php if(count($purchasedConfigs) == 1): 
        $singleUser = $purchasedConfigs[0]['account_username'];
    ?>
        <div class="bg-[#f8fafc] dark:bg-[#0f172a] relative min-h-[600px] p-6 md:p-10" id="live_sub_dashboard">
            <div id="sub_loading" class="absolute inset-0 bg-white/90 dark:bg-slate-900/90 z-30 flex flex-col items-center justify-center transition-opacity">
                <div class="animate-spin w-10 h-10 border-4 border-blue-600 border-t-transparent rounded-full mb-4"></div>
                <p class="font-bold text-gray-500 dark:text-gray-400 animate-pulse text-sm" id="sub_loading_text">در حال ارتباط با سرور اصلی...</p>
            </div>

            <div class="flex justify-between items-center mb-10">
                <div class="text-right">
                    <h3 class="text-3xl font-black text-gray-900 dark:text-white mb-2">داشبورد کاربری</h3>
                    <div class="flex items-center gap-3">
                        <span id="sub_online_status" class="text-emerald-500 text-xs font-bold flex items-center gap-1.5">آنلاین <span class="w-2 h-2 bg-emerald-500 rounded-full animate-pulse"></span></span>
                        <span class="text-gray-300 dark:text-slate-700">|</span>
                        <span id="sub_username_display" onclick="copyTextNative('<?php echo $singleUser; ?>', this)" class="text-gray-600 dark:text-slate-400 font-black cursor-pointer hover:text-blue-500 transition" dir="ltr">@<?php echo $singleUser; ?></span>
                    </div>
                </div>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-12 gap-6 mb-10">
                <div id="sub_status_card" class="lg:col-span-8 bg-[#eafbf1] dark:bg-[#064e3b]/50 border border-[#d1f4e0] dark:border-[#065f46] rounded-[2.5rem] p-8 flex flex-col justify-between min-h-[300px]">
                    <div class="flex justify-between items-start">
                        <div>
                            <h2 id="sub_status_text" class="text-5xl font-black text-[#10b981] mb-2">فعال</h2>
                            <span class="text-xs font-bold text-gray-400 dark:text-emerald-200/50 block pr-1">وضعیت اشتراک</span>
                        </div>
                        <div class="text-center">
                            <span class="block text-3xl mb-1 text-gray-400 font-light">∞</span>
                            <span class="font-black text-gray-800 dark:text-white">نامحدود</span>
                        </div>
                    </div>
                    <div class="flex justify-between items-end">
                        <div class="flex flex-col items-center">
                            <div class="sub-pie-wrap" id="sub_pie_chart">
                                <div class="sub-pie-inside" id="sub_percent_val">0%</div>
                            </div>
                            <span class="text-[10px] font-bold text-gray-400 mt-3">مصرف شده</span>
                        </div>
                        <div class="space-y-4 w-full max-w-[240px]">
                            <div class="flex justify-between text-sm font-bold"><span class="text-gray-400">مصرف شده:</span><span id="sub_used_val" class="dark:text-white" dir="ltr">0 MB</span></div>
                            <div class="flex justify-between text-sm font-bold"><span class="text-gray-400">حجم کل:</span><span id="sub_limit_val" class="dark:text-white" dir="ltr">0 GB</span></div>
                            <div class="flex justify-between text-sm font-black pt-2 border-t border-emerald-200 dark:border-emerald-800"><span class="text-gray-500">باقی‌مانده:</span><span id="sub_remain_val" class="text-[#10b981]" dir="ltr">0 MB</span></div>
                        </div>
                    </div>
                </div>

                <div class="lg:col-span-4 flex flex-col gap-4">
                    <div class="bg-white dark:bg-slate-800 rounded-3xl p-6 shadow-sm border border-gray-100 dark:border-slate-700 flex justify-between items-center flex-1">
                        <span class="text-xs font-bold text-gray-400">ترافیک کل</span>
                        <span id="sub_total_stat" class="text-2xl font-black font-mono dark:text-white" dir="ltr">0 MB</span>
                    </div>
                    <div class="bg-white dark:bg-slate-800 rounded-3xl p-6 shadow-sm border border-gray-100 dark:border-slate-700 flex justify-between items-center flex-1">
                        <span class="text-xs font-bold text-gray-400">تاریخ انقضا</span>
                        <span id="sub_expire_stat" class="text-xl font-black font-mono dark:text-white" dir="ltr">∞</span>
                    </div>
                    <div class="bg-white dark:bg-slate-800 rounded-3xl p-6 shadow-sm border border-gray-100 dark:border-slate-700 flex justify-between items-center flex-1">
                        <span class="text-xs font-bold text-gray-400">آخرین اتصال</span>
                        <span id="sub_last_stat" class="text-xs font-bold text-emerald-500" dir="ltr">--</span>
                    </div>
                </div>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-12 gap-8">
                <div class="lg:col-span-7">
                    <div class="flex justify-between items-center mb-6 px-1">
                        <h4 class="font-black text-gray-800 dark:text-white flex items-center gap-2">لینک‌های اتصال</h4>
                        <div class="flex flex-col sm:flex-row gap-2">
                            <button onclick="copyAllSubConfigs(this)" class="bg-[#3b5998] text-white text-[10px] font-black px-4 py-2.5 rounded-xl shadow-lg hover:bg-blue-700 transition flex items-center justify-center gap-2 min-w-[130px]">کپی همه 📋</button>
                        </div>
                    </div>
                    <div id="sub_configs_container" class="space-y-3 max-h-[400px] overflow-y-auto custom-scrollbar pe-2"></div>
                </div>
                <div class="lg:col-span-5 bg-white dark:bg-slate-800 rounded-[2rem] p-6 shadow-sm border border-gray-100 dark:border-slate-700 flex flex-col">
                    <h4 class="font-black text-gray-800 dark:text-white text-sm mb-6">آمار مصرف</h4>
                    <div class="flex-1 min-h-[250px]"><canvas id="subChartCanvas"></canvas></div>
                </div>
            </div>
        </div>

        <style>
            .sub-pie-wrap { width: 120px; height: 120px; background: #c6f6d5; border-radius: 50%; position: relative; transition: background 0.5s; }
            .sub-pie-inside { width: 96px; height: 96px; background: #eafbf1; border-radius: 50%; position: absolute; top: 12px; left: 12px; display: flex; align-items: center; justify-content: center; font-weight: 900; font-size: 1.5rem; color: #1f2937; }
            html.dark .sub-pie-wrap { background: #065f46; }
            html.dark .sub-pie-inside { background: #064e3b; color: #fff; }
        </style>
    <?php endif; ?>
</div>

<script>
    // موتور استخراج هوشمند JSON برای مقابله با خطاهای احتمالی خروجی
    async function apiCall(action, params) {
        let url = `store.php?store_ajax=${action}`;
        for(let key in params) { url += `&${key}=${encodeURIComponent(params[key])}`; }
        const res = await fetch(url);
        const text = await res.text();
        try {
            return JSON.parse(text);
        } catch(e) {
            const match = text.match(/\{[\s\S]*\}|\[[\s\S]*\]/);
            if (match) { try { return JSON.parse(match[0]); } catch(err) {} }
            throw new Error("پاسخ سرور نامعتبر است.");
        }
    }

    const exportConfigsArr = <?php echo json_encode($exportData); ?>;
    const globalServerId = '<?php echo $targetServerId; ?>';

    // توابع دانلود TXT و Excel
    window.downloadConfigsTxt = async function(btn) {
        let oldHtml = btn.innerHTML;
        btn.innerHTML = '<span class="animate-spin inline-block w-4 h-4 border-2 border-white border-t-transparent rounded-full"></span> دریافت...';
        btn.disabled = true;
        let txtContent = "";
        for (let item of exportConfigsArr) {
            txtContent += "Username: " + item.username + "\nSub Link: " + item.sub_link + "\nConfigs:\n";
            if (item.sub_link && item.sub_link.trim() !== '') {
                try {
                    let links = await apiCall('get_sub_links', { sub_url: item.sub_link, server_id: globalServerId });
                    if(Array.isArray(links)) txtContent += links.join("\n") + "\n";
                } catch(e) {}
            }
            txtContent += "\n";
        }
        let blob = new Blob([txtContent], { type: "text/plain;charset=utf-8" });
        let link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = "configs.txt"; link.click();
        btn.innerHTML = '✔ دانلود شد';
        setTimeout(() => { btn.innerHTML = oldHtml; btn.disabled = false; }, 2000);
    };

    window.downloadConfigsExcel = async function(btn) {
        let oldHtml = btn.innerHTML;
        btn.innerHTML = '<span class="animate-spin inline-block w-4 h-4 border-2 border-white border-t-transparent rounded-full"></span> دریافت...';
        btn.disabled = true;
        let csvContent = "\uFEFFUsername,Sub Link,Configs\n";
        for (let item of exportConfigsArr) {
            let configsStr = "";
            try {
                let links = await apiCall('get_sub_links', { sub_url: item.sub_link, server_id: globalServerId });
                if(Array.isArray(links)) configsStr = links.join(" | ");
            } catch(e) {}
            csvContent += `"${item.username}","${item.sub_link}","${configsStr.replace(/"/g, '""')}"\n`;
        }
        let blob = new Blob([csvContent], { type: "text/csv;charset=utf-8" });
        let link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = "configs.csv"; link.click();
        btn.innerHTML = '✔ دانلود شد';
        setTimeout(() => { btn.innerHTML = oldHtml; btn.disabled = false; }, 2000);
    };

    // کپی تمام کانفیگ‌ها از روی دکمه در جدول اصلی
    window.copyRowConfigs = async function(subUrl, serverId, btn) {
        let originalHtml = btn.innerHTML;
        btn.innerHTML = '<span class="animate-spin inline-block w-4 h-4 border-2 border-blue-600 border-t-transparent rounded-full"></span>';
        try {
            let links = await apiCall('get_sub_links', { sub_url: subUrl, server_id: serverId });
            let allText = "Sub Link: " + subUrl + '\n\n' + (Array.isArray(links) ? links.join('\n') : '');
            await navigator.clipboard.writeText(allText);
            btn.innerHTML = '<span class="text-emerald-500 text-sm">✔</span>';
        } catch (e) { btn.innerHTML = '<span class="text-rose-500 text-sm">❌</span>'; }
        setTimeout(() => { btn.innerHTML = originalHtml; }, 2000);
    };

    // ----------------------------------------------------
    // سیستم ساخت المنت‌های گرافیکی مشترک کانفیگ‌ها
    // ----------------------------------------------------
    window.createConfigRowHtml = function(type, name, link) {
        return `
        <div class="bg-white dark:bg-slate-800 border border-gray-100 dark:border-slate-700 rounded-2xl p-4 flex justify-between items-center shadow-sm">
            <div class="flex items-center gap-3">
                <span class="bg-[#336699] text-white text-[9px] font-black px-2 py-1 rounded uppercase">${type}</span>
                <span class="text-[11px] font-bold text-gray-700 dark:text-gray-300 truncate max-w-[150px] sm:max-w-[300px] lg:max-w-[400px]" dir="ltr">${name}</span>
            </div>
            <div class="flex gap-1.5">
                <button onclick="if(typeof showQRModal==='function') showQRModal('${link}', '${name}')" class="w-8 h-8 flex items-center justify-center bg-gray-50 dark:bg-slate-700 rounded-xl text-gray-400 hover:text-blue-500 transition shadow-sm border border-gray-200 dark:border-slate-600">📱</button>
                <button onclick="copyTextNative('${link}', this)" class="w-8 h-8 flex items-center justify-center bg-gray-50 dark:bg-slate-700 rounded-xl text-gray-400 hover:text-blue-500 transition shadow-sm border border-gray-200 dark:border-slate-600">📋</button>
            </div>
        </div>`;
    };

    // ----------------------------------------------------
    // آکاردئون نمایش کانفیگ‌ها با سیستم Retry هوشمند
    // ----------------------------------------------------
    window.toggleUserConfigs = async function(subUrl, serverId, index, btn) {
        const tr = document.getElementById('configs_row_' + index);
        const container = document.getElementById('configs_container_' + index);
        
        // اگر تابع توسط کلیک روی دکمه اصلی آکاردئون فراخوانی شده بود
        if (btn && btn.id === 'btn_toggle_' + index) {
            if (!tr.classList.contains('hidden')) {
                tr.classList.add('hidden');
                btn.innerHTML = '🔽';
                return;
            }
            tr.classList.remove('hidden');
            btn.innerHTML = '🔼';
        }
        
        if (container.dataset.loaded === 'true') return;
        
        container.innerHTML = `
            <div class="flex flex-col justify-center items-center py-8 gap-3">
                <div class="animate-spin w-8 h-8 border-4 border-indigo-600 border-t-transparent rounded-full"></div>
                <span class="text-xs text-indigo-600 dark:text-indigo-400 font-bold" id="loading_text_${index}">در حال ارتباط با سرور و دریافت کانفیگ‌ها...</span>
            </div>
        `;
        
        let maxRetries = 3;
        let success = false;
        let links = [];
        
        // مکانیزم Retry هوشمند
        for(let attempt = 1; attempt <= maxRetries; attempt++) {
            try {
                if (attempt > 1) {
                    let loadingText = document.getElementById('loading_text_' + index);
                    if(loadingText) {
                        loadingText.innerText = `سرور پاسخ نداد! تلاش مجدد (${attempt} از ${maxRetries})...`;
                        loadingText.classList.replace('text-indigo-600', 'text-amber-500');
                    }
                }
                
                links = await apiCall('get_sub_links', { sub_url: subUrl, server_id: serverId });
                
                if (Array.isArray(links) && links.length > 0) {
                    success = true;
                    break; // با موفقیت دریافت شد
                } else {
                    // آرایه خالی بود (کانفیگ‌ها هنوز تولید نشده‌اند)، صبر کن و دوباره تلاش کن
                    if (attempt < maxRetries) await new Promise(r => setTimeout(r, 2000));
                }
            } catch (e) {
                // خطای شبکه، صبر کن و دوباره تلاش کن
                if (attempt < maxRetries) await new Promise(r => setTimeout(r, 2000));
            }
        }
        
        let html = '<div class="space-y-2 max-h-[350px] overflow-y-auto custom-scrollbar pr-2 pl-1 pb-2">';
        html += window.createConfigRowHtml('SUB', 'Subscription Link', subUrl);
        
        if (success && links.length > 0) {
            links.forEach(l => {
                let type = l.split('://')[0].toUpperCase();
                let name = decodeURIComponent(l.split('#')[1] || 'Config');
                html += window.createConfigRowHtml(type, name, l);
            });
            html += '</div>';
            container.innerHTML = html;
            container.dataset.loaded = 'true';
        } else {
            // در صورت شکست در تمامی تلاش‌ها، نمایش دکمه Retry به کاربر
            html += `
                <div class="text-sm text-rose-600 font-bold p-5 text-center bg-rose-50 dark:bg-rose-900/20 rounded-xl border border-rose-200 dark:border-rose-800 flex flex-col items-center gap-3">
                    <span>❌ خطا در دریافت کانفیگ‌ها! اینترنت شما ضعیف است یا کانفیگ‌ها هنوز تولید نشده‌اند.</span>
                    <button type="button" onclick="window.toggleUserConfigs('${subUrl}', '${serverId}', ${index}, null)" class="bg-rose-600 hover:bg-rose-700 text-white px-5 py-2 rounded-xl transition text-xs shadow-md mt-2 flex items-center gap-2">
                        🔄 تلاش مجدد
                    </button>
                </div>
            </div>`;
            container.innerHTML = html;
            container.dataset.loaded = 'false'; // اجازه تلاش مجدد
        }
    };

    <?php if(count($purchasedConfigs) == 1): ?>
    (function() {
        const user = '<?php echo addslashes($singleUser); ?>';
        const srv = '<?php echo $targetServerId; ?>';
        let fullLinks = [];
        let loadedSubUrl = '';

        function formatSize(b) {
            if (!b || b <= 0) return '0 MB';
            const k = 1024, i = Math.floor(Math.log(b) / Math.log(k));
            return parseFloat((b / Math.pow(k, i)).toFixed(2)) + ' ' + ['B', 'KB', 'MB', 'GB', 'TB'][i];
        }

        async function initLiveDashboard() {
            try {
                await new Promise(r => setTimeout(r, 1200));
                const data = await apiCall('get_user', { username: user, server_id: srv });
                
                const serverError = data.error || (data.data && data.data.detail) || data.detail;
                if (serverError && data.code !== 200) throw new Error(serverError);

                const u = data.data || (data.username ? data : null);

                if (u && u.username) {
                    document.getElementById('sub_loading')?.remove();
                    document.getElementById('sub_limit_val').innerText = u.data_limit > 0 ? formatSize(u.data_limit) : '∞';
                    document.getElementById('sub_used_val').innerText = formatSize(u.used_traffic);
                    document.getElementById('sub_remain_val').innerText = u.data_limit > 0 ? formatSize(Math.max(0, u.data_limit - u.used_traffic)) : 'نامحدود';
                    
                    let p = u.data_limit > 0 ? Math.round((u.used_traffic / u.data_limit) * 100) : 0;
                    document.getElementById('sub_percent_val').innerText = p + '%';
                    document.getElementById('sub_pie_chart').style.background = `conic-gradient(#10b981 ${p * 3.6}deg, transparent 0)`;

                    if(u.subscription_url) {
                        loadedSubUrl = u.subscription_url;
                        
                        // اضافه شدن یک تلاش مجدد ساده برای داشبورد تکی نیز جهت اطمینان بیشتر
                        for(let att=0; att<3; att++){
                            fullLinks = await apiCall('get_sub_links', { sub_url: u.subscription_url, server_id: srv });
                            if(fullLinks && fullLinks.length > 0) break;
                            await new Promise(r => setTimeout(r, 1500));
                        }
                        
                        renderConfigs(fullLinks, u.subscription_url);
                    }
                } else { throw new Error('کاربر یافت نشد یا پاسخ نامعتبر است.'); }
            } catch(e) { 
                let el = document.getElementById('sub_loading_text');
                if(el) el.innerText = '❌ ' + e.message; 
            }
        }

        function renderConfigs(links, subUrl) {
            let html = '<div class="space-y-3">';
            if(subUrl) html += window.createConfigRowHtml('SUB', 'Subscription Link', subUrl);
            
            if(Array.isArray(links)) {
                links.forEach(l => {
                    let type = l.split('://')[0].toUpperCase();
                    let name = decodeURIComponent(l.split('#')[1] || 'Config');
                    html += window.createConfigRowHtml(type, name, l);
                });
            }
            html += '</div>';
            document.getElementById('sub_configs_container').innerHTML = html;
        }

        window.copyAllSubConfigs = (btn) => {
            let allText = (loadedSubUrl ? "Sub Link: " + loadedSubUrl + '\n\n' : "") + fullLinks.join('\n');
            navigator.clipboard.writeText(allText).then(() => {
                let old = btn.innerHTML; btn.innerHTML = 'کپی شد! ✔';
                setTimeout(() => btn.innerHTML = old, 2000);
            });
        };

        initLiveDashboard();
    })();
    <?php endif; ?>

    window.copyTextNative = function(t, btn) {
        navigator.clipboard.writeText(t).then(() => {
            let old = btn.innerHTML; btn.innerHTML = '<span class="text-emerald-500 text-[10px]">✔</span>';
            setTimeout(() => btn.innerHTML = old, 2000);
        });
    }

    window.copyTableLinkNative = function(t, el) {
        navigator.clipboard.writeText(t).then(() => {
            let b = el.querySelector('.copy-badge');
            if(b) { 
                b.innerText = 'کپی شد!'; b.classList.add('opacity-100', 'bg-emerald-500', 'text-white');
                setTimeout(() => { b.innerText = 'Copy'; b.classList.remove('bg-emerald-500', 'text-white'); }, 2000); 
            }
        });
    }
</script>