☰

Discord Mark All Servers As Read

Mark all Discord servers as read in one click. Instantly clears badges and unread dots. Settings panel, exclusions, DMs, auto-run, Arabic/English.

이 스크립트를 설치하려면 Tampermonkey, Greasemonkey 또는 Violentmonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey 또는 Violentmonkey와 같은 확장 프로그램을 먼저 설치해야 합니다.

이 스크립트를 설치하려면 Tampermonkey 또는 Violentmonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey 또는 Userscripts와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 유저 스크립트 관리자 확장 프로그램이 필요합니다.

(이미 유저 스크립트 관리자가 설치되어 있습니다. 설치를 진행합니다!)

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

(이미 유저 스타일 관리자가 설치되어 있습니다. 설치를 진행합니다!)

// ==UserScript==
// @name         Discord Mark All Servers As Read
// @namespace    http://tampermonkey.net/
// @version      4.0
// @license MIT
// @description  Mark all Discord servers as read in one click. Instantly clears badges and unread dots. Settings panel, exclusions, DMs, auto-run, Arabic/English.
// @match        https://discord.com/*
// @grant        GM_addStyle
// @grant        GM_registerMenuCommand
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_notification
// @grant        unsafeWindow
// @run-at       document-idle
// ==/UserScript==

(function () {
    'use strict';

    const API = 'https://discord.com/api/v9';
    const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
    const RING_C = 2 * Math.PI * 28;
    const ACKABLE = new Set([0, 2, 5, 13]);
    let running = false;

    const DEFAULTS = {
        sound: true,
        notify: true,
        skipMuted: false,      
        includeDMs: false,     
        keepUnreadDMs: false,  
        autoHide: false,      
        runOnOpen: false,      
        autoRun: false,        
        autoMinutes: 30,
        confirmAbove: 0,       
        lang: 'auto',         
        excluded: [],         
    };
    const settings = Object.assign({}, DEFAULTS, GM_getValue('settings', {}) || {});
    if (!Array.isArray(settings.excluded)) settings.excluded = [];
    const saveSettings = () => GM_setValue('settings', settings);

    const I18N = {
        en: {
            idle: 'Mark all as read',
            aria: 'Mark all servers as read',
            preparing: 'Preparing…',
            scanning: (d, n) => `Scanning servers ${d}/${n}`,
            scanningDMs: 'Scanning DMs…',
            marking: (d, n) => `Marking as read ${d}/${n}`,
            rate: (s) => `Rate limited — waiting ${s}s…`,
            done: (s) => `Done ✓ ${s}`,
            failed: (m) => `Failed: ${m}`,
            cancelled: 'Cancelled',
            confirm: (n, g) => `About to mark ${n} channels in ${g} servers as read. Continue?`,
            noToken: 'No token available',
            tokenPrompt: 'Could not get your token automatically. Paste it here (it will be deleted automatically when the script finishes):',
            tokenCleared: 'Saved token cleared',
            openServer: 'Open a server first (Ctrl+Alt+S marks the current server)',
            summary: (o) => [
                o.servers ? `${o.servers} servers` : '',
                `${o.channels} channels`,
                o.dms ? `${o.dms} DMs` : '',
                o.skipped ? `${o.skipped} skipped` : '',
                o.skippedServers ? `${o.skippedServers} servers excluded` : '',
            ].filter(Boolean).join(' · '),
            notifyDone: 'Discord — All marked as read ✓',
            notifyFail: 'Discord — Something went wrong',
            lastRun: (ago, n) => `Last run: ${ago} · ${n} channels`,
            unreadInfo: (s, m) => `${s} unread servers · ${m} mentions`,
            ago: (ms) => {
                const m = Math.floor(ms / 60000);
                if (m < 1) return 'just now';
                if (m < 60) return `${m} min ago`;
                const h = Math.floor(m / 60);
                if (h < 24) return `${h} h ago`;
                return `${Math.floor(h / 24)} d ago`;
            },
            mAll: '✓✓ Mark All Servers As Read',
            mCurrent: '✓ Mark Current Server As Read',
            mDMs: '✉ Mark DMs As Read',
            mSettings: '⚙ Settings',
            mDiag: '🩺 Diagnostics',
            mClearToken: '🔑 Clear saved token',
            mReset: '↺ Reset button position',
            pTitle: 'Mark As Read — Settings',
            pGeneral: 'General',
            pSound: 'Sounds',
            pNotify: 'Notifications',
            pSkipMuted: 'Skip muted servers and channels',
            pIncludeDMs: 'Include DMs and group chats in "Mark all"',
            pKeepDMs: 'Leave DMs that still have a red badge untouched',
            pAutoHide: 'Fade the button when nothing is unread',
            pAuto: 'Automatic',
            pRunOnOpen: 'Run silently when Discord opens',
            pAutoRun: 'Run silently every…',
            pEveryMin: 'Minutes between runs',
            pConfirm: 'Ask before marking at least N channels (0 = never)',
            pLang: 'Language',
            pLangAuto: 'Auto',
            pServers: 'Servers to skip',
            pServersHint: 'Checked servers are never touched by "Mark all".',
            pSearch: 'Search servers…',
            pLoading: 'Loading…',
            pNone: 'No servers found',
            pActions: 'Run now',
            pBtnAll: 'Mark all',
            pBtnCurrent: 'Current server',
            pBtnDMs: 'DMs only',
            pHistory: 'Recent runs',
            pNoHistory: 'Nothing yet',
            scopeAll: 'All',
            scopeCurrent: 'Server',
            scopeDMs: 'DMs',
        },
        ar: {
            idle: 'تعليم الكل كمقروء',
            aria: 'تعليم كل السيرفرات كمقروءة',
            preparing: 'جارٍ التحضير…',
            scanning: (d, n) => `فحص السيرفرات ${d}/${n}`,
            scanningDMs: 'فحص الرسائل الخاصة…',
            marking: (d, n) => `تعليم كمقروء ${d}/${n}`,
            rate: (s) => `تم تقييد الطلبات — انتظار ${s} ثانية…`,
            done: (s) => `تم ✓ ${s}`,
            failed: (m) => `فشل: ${m}`,
            cancelled: 'تم الإلغاء',
            confirm: (n, g) => `سيتم تعليم ${n} قناة في ${g} سيرفر كمقروءة. متابعة؟`,
            noToken: 'لا يوجد توكن',
            tokenPrompt: 'مقدرتش أجيب التوكن تلقائيًا. الصقه هنا (هيتمسح تلقائيًا لما السكربت يخلص):',
            tokenCleared: 'تم مسح التوكن المحفوظ',
            openServer: 'افتح سيرفر الأول (Ctrl+Alt+S بيعلّم السيرفر الحالي)',
            summary: (o) => [
                o.servers ? `${o.servers} سيرفر` : '',
                `${o.channels} قناة`,
                o.dms ? `${o.dms} محادثة خاصة` : '',
                o.skipped ? `${o.skipped} تم تخطيها` : '',
                o.skippedServers ? `${o.skippedServers} سيرفر مستثنى` : '',
            ].filter(Boolean).join(' · '),
            notifyDone: 'ديسكورد — تم تعليم الكل كمقروء ✓',
            notifyFail: 'ديسكورد — حصلت مشكلة',
            lastRun: (ago, n) => `آخر تشغيل: ${ago} · ${n} قناة`,
            unreadInfo: (s, m) => `${s} سيرفر غير مقروء · ${m} منشن`,
            ago: (ms) => {
                const m = Math.floor(ms / 60000);
                if (m < 1) return 'الآن';
                if (m < 60) return `منذ ${m} د`;
                const h = Math.floor(m / 60);
                if (h < 24) return `منذ ${h} س`;
                return `منذ ${Math.floor(h / 24)} يوم`;
            },
            mAll: '✓✓ تعليم كل السيرفرات كمقروءة',
            mCurrent: '✓ تعليم السيرفر الحالي كمقروء',
            mDMs: '✉ تعليم الرسائل الخاصة كمقروءة',
            mSettings: '⚙ الإعدادات',
            mDiag: '🩺 تشخيص',
            mClearToken: '🔑 مسح التوكن المحفوظ',
            mReset: '↺ إعادة مكان الزرار',
            pTitle: 'تعليم كمقروء — الإعدادات',
            pGeneral: 'عام',
            pSound: 'الأصوات',
            pNotify: 'الإشعارات',
            pSkipMuted: 'تخطي السيرفرات والقنوات المكتومة',
            pIncludeDMs: 'تضمين الرسائل الخاصة والجروبات في "تعليم الكل"',
            pKeepDMs: 'ماتلمسش الرسائل الخاصة اللي عليها عداد أحمر',
            pAutoHide: 'إخفاء الزرار (شفاف) لما مفيش غير مقروء',
            pAuto: 'تلقائي',
            pRunOnOpen: 'تشغيل صامت أول ما ديسكورد يفتح',
            pAutoRun: 'تشغيل صامت كل فترة',
            pEveryMin: 'الدقائق بين كل تشغيل',
            pConfirm: 'اسأل قبل تعليم N قناة أو أكتر (0 = مايسألش)',
            pLang: 'اللغة',
            pLangAuto: 'تلقائي',
            pServers: 'سيرفرات يتم تخطيها',
            pServersHint: 'السيرفرات المعلّمة عمرها ما هتتلمس من "تعليم الكل".',
            pSearch: 'ابحث عن سيرفر…',
            pLoading: 'جارٍ التحميل…',
            pNone: 'مفيش سيرفرات',
            pActions: 'شغّل دلوقتي',
            pBtnAll: 'تعليم الكل',
            pBtnCurrent: 'السيرفر الحالي',
            pBtnDMs: 'الخاص بس',
            pHistory: 'آخر التشغيلات',
            pNoHistory: 'لسه مفيش',
            scopeAll: 'الكل',
            scopeCurrent: 'سيرفر',
            scopeDMs: 'خاص',
        },
    };
    function lang() {
        const l = settings.lang === 'auto'
            ? (document.documentElement.lang || navigator.language || 'en')
            : settings.lang;
        return /^ar/i.test(l) ? 'ar' : 'en';
    }
    function t(key, ...args) {
        const v = (I18N[lang()] && I18N[lang()][key] !== undefined) ? I18N[lang()][key] : (I18N.en[key] !== undefined ? I18N.en[key] : key);
        return typeof v === 'function' ? v(...args) : v;
    }
    const idleText = () => `${t('idle')} · Ctrl+Alt+A`;

    let _req = null;
    function getReq() {
        if (_req) return _req;
        try {
            let req;
            unsafeWindow.webpackChunkdiscord_app.push([[Symbol()], {}, (r) => { req = r; }]);
            unsafeWindow.webpackChunkdiscord_app.pop();
            _req = req || null;
        } catch {}
        return _req;
    }

    function findExport(test) {
        const req = getReq();
        if (!req || !req.c) return null;
        for (const id in req.c) {
            let e;
            try { e = req.c[id].exports; } catch { continue; }
            if (!e) continue;
            for (const x of [e, e.default, e.Z, e.ZP]) {
                try { if (x && test(x)) return x; } catch {}
            }
        }
        return null;
    }

    const _cache = {};
    function cached(name, finder) {
        const c = _cache[name];
        if (c && (c.v || Date.now() - c.t < 20000)) return c.v;
        const v = finder() || null;
        _cache[name] = { v, t: Date.now() };
        return v;
    }
    const fn = (x, ...names) => names.every((n) => typeof x[n] === 'function');

    const getDispatcher = () => cached('dispatcher', () =>
        findExport((x) => fn(x, 'dispatch', 'subscribe', 'unsubscribe') && x._actionHandlers) ||
        findExport((x) => fn(x, 'dispatch', 'subscribe', 'unsubscribe', 'isDispatching')));
    const getReadStateStore = () => cached('readState', () =>
        findExport((x) => fn(x, 'hasUnread', 'getMentionCount', 'ackMessageId')) ||
        findExport((x) => fn(x, 'hasUnread', 'getMentionCount', 'lastMessageId')));
    const getGuildReadStore = () => cached('guildRead', () =>
        findExport((x) => fn(x, 'hasAnyUnread', 'getMentionCount')));
    const getGuildStore = () => cached('guildStore', () =>
        findExport((x) => fn(x, 'getGuilds', 'getGuild', 'getGuildIds')) ||
        findExport((x) => fn(x, 'getGuilds', 'getGuild')));
    const getMuteStore = () => cached('muteStore', () =>
        findExport((x) => fn(x, 'isMuted', 'isChannelMuted')));

    function isGuildMuted(id) {
        try { const s = getMuteStore(); return !!(s && s.isMuted(id)); } catch { return false; }
    }
    function isChannelMuted(gid, cid) {
        try { const s = getMuteStore(); return !!(s && s.isChannelMuted(gid, cid)); } catch { return false; }
    }
    function mentionCount(cid) {
        try { const s = getReadStateStore(); return s ? (s.getMentionCount(cid) || 0) : 0; } catch { return 0; }
    }

    function tokenFromIframe() {
        try {
            const f = document.createElement('iframe');
            f.style.display = 'none';
            document.body.appendChild(f);
            const raw = f.contentWindow.localStorage.getItem('token');
            f.remove();
            if (!raw) return null;
            try { return JSON.parse(raw); } catch { return raw.replace(/"/g, ''); }
        } catch { return null; }
    }

    function tokenFromWebpack() {
        try {
            const req = getReq();
            if (!req || !req.c) return null;
            for (const id in req.c) {
                let e;
                try { e = req.c[id].exports; } catch { continue; }
                if (!e) continue;
                for (const x of [e, e.default, e.Z, e.ZP]) {
                    if (x && typeof x.getToken === 'function') {
                        const tk = x.getToken();
                        if (typeof tk === 'string' && tk.length > 20) return tk;
                    }
                }
            }
        } catch {}
        return null;
    }

    function getToken(silent = false) {
        let tok = tokenFromIframe() || tokenFromWebpack() || GM_getValue('manual_token', null);
        if (!tok && !silent) {
            tok = prompt(t('tokenPrompt'));
            if (tok) GM_setValue('manual_token', tok.trim().replace(/"/g, ''));
        }
        return tok;
    }

    function clearSavedToken() { GM_setValue('manual_token', null); }
    function playTones(freqs, step = 0.14) {
        if (!settings.sound) return;
        try {
            const Ctx = window.AudioContext || window.webkitAudioContext;
            const ctx = new Ctx();
            ctx.resume && ctx.resume();
            const t0 = ctx.currentTime;
            freqs.forEach((f, i) => {
                const o = ctx.createOscillator();
                const g = ctx.createGain();
                const s = t0 + i * step;
                o.type = 'sine';
                o.frequency.value = f;
                g.gain.setValueAtTime(0.0001, s);
                g.gain.exponentialRampToValueAtTime(0.18, s + 0.02);
                g.gain.exponentialRampToValueAtTime(0.0001, s + 0.38);
                o.connect(g); g.connect(ctx.destination);
                o.start(s); o.stop(s + 0.42);
            });
            setTimeout(() => ctx.close && ctx.close(), 2000);
        } catch {}
    }
    const soundBlip = () => playTones([880], 0);
    const soundSuccess = () => playTones([659.25, 880, 1318.5]);
    const soundError = () => playTones([440, 311.13]);

    function notify(title, text) {
        if (!settings.notify) return;
        try {
            GM_notification({ title, text, timeout: 6000, silent: true });
        } catch {
            try {
                if (Notification.permission === 'granted') new Notification(title, { body: text });
                else if (Notification.permission !== 'denied') {
                    Notification.requestPermission().then((p) => {
                        if (p === 'granted') new Notification(title, { body: text });
                    });
                }
            } catch {}
        }
    }

    GM_addStyle(`
        #dsb-root{position:fixed;bottom:28px;right:28px;z-index:999999;width:64px;height:64px;
            font-family:'gg sans','Segoe UI',Tahoma,sans-serif;user-select:none;-webkit-user-select:none;
            transition:opacity .3s}
        #dsb-root.faded{opacity:.28}
        #dsb-root.faded:hover,#dsb-root.busy,#dsb-root.flash,#dsb-root.dragging{opacity:1}
        #dsb-btn{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;cursor:pointer;
            border-radius:50%;color:#fff;
            background:radial-gradient(circle at 30% 25%,#7c87ff 0%,#5865F2 55%,#4752c4 100%);
            box-shadow:0 6px 18px rgba(88,101,242,.45),0 2px 6px rgba(0,0,0,.45),inset 0 1px 0 rgba(255,255,255,.25);
            transition:transform .18s cubic-bezier(.3,1.4,.6,1),box-shadow .2s,background .3s}
        #dsb-btn:hover{transform:translateY(-2px) scale(1.06);
            box-shadow:0 10px 24px rgba(88,101,242,.55),0 3px 8px rgba(0,0,0,.5),inset 0 1px 0 rgba(255,255,255,.3)}
        #dsb-btn:active{transform:scale(.95)}
        #dsb-root.dragging #dsb-btn{cursor:grabbing;transform:scale(1.04)}
        #dsb-root.done #dsb-btn{background:radial-gradient(circle at 30% 25%,#5fd88a 0%,#3ba55c 60%,#2d7d46 100%);
            box-shadow:0 6px 18px rgba(59,165,92,.5),0 2px 6px rgba(0,0,0,.45),inset 0 1px 0 rgba(255,255,255,.25)}
        #dsb-root.error #dsb-btn{background:radial-gradient(circle at 30% 25%,#ff7a7c 0%,#ed4245 60%,#b02d30 100%);
            box-shadow:0 6px 18px rgba(237,66,69,.5),0 2px 6px rgba(0,0,0,.45),inset 0 1px 0 rgba(255,255,255,.25)}
        #dsb-root.busy #dsb-btn{cursor:progress}
        #dsb-root.busy .dsb-icon{animation:dsb-pulse 1.2s ease-in-out infinite}
        .dsb-icon{display:flex;pointer-events:none;filter:drop-shadow(0 1px 1px rgba(0,0,0,.25))}
        @keyframes dsb-pulse{0%,100%{opacity:1;transform:scale(1)}50%{opacity:.6;transform:scale(.9)}}
        .dsb-ring{position:absolute;inset:-6px;width:76px;height:76px;transform:rotate(-90deg);pointer-events:none;
            opacity:0;transition:opacity .25s}
        #dsb-root.busy .dsb-ring{opacity:1}
        .dsb-track{fill:none;stroke:rgba(255,255,255,.12);stroke-width:3}
        .dsb-bar{fill:none;stroke:#fff;stroke-width:3;stroke-linecap:round;
            stroke-dasharray:${RING_C};stroke-dashoffset:${RING_C};transition:stroke-dashoffset .3s ease;
            filter:drop-shadow(0 0 3px rgba(255,255,255,.6))}
        #dsb-badge{position:absolute;top:-4px;right:-4px;min-width:24px;height:24px;padding:0 6px;
            box-sizing:border-box;border-radius:12px;background:#ed4245;color:#fff;font-size:12px;font-weight:700;
            display:none;align-items:center;justify-content:center;border:3px solid #1e1f22;
            pointer-events:none;z-index:2}
        #dsb-pill{position:absolute;right:76px;top:50%;transform:translateY(-50%) translateX(8px);
            white-space:nowrap;padding:8px 14px;border-radius:10px;font-size:13px;font-weight:600;
            color:#f2f3f5;background:#111214;border:1px solid rgba(255,255,255,.08);
            box-shadow:0 6px 20px rgba(0,0,0,.5);opacity:0;pointer-events:none;
            transition:opacity .2s,transform .2s}
        #dsb-pill::after{content:'';position:absolute;left:100%;top:50%;margin-top:-5px;
            border:5px solid transparent;border-left-color:#111214}
        #dsb-root:hover #dsb-pill,#dsb-root.busy #dsb-pill,#dsb-root.flash #dsb-pill{opacity:1;transform:translateY(-50%)}
        #dsb-root.dragging #dsb-pill{opacity:0}

        #dsb-back{position:fixed;inset:0;z-index:1000000;background:rgba(0,0,0,.6);display:flex;
            align-items:center;justify-content:center;font-family:'gg sans','Segoe UI',Tahoma,sans-serif}
        #dsb-panel{width:460px;max-width:94vw;max-height:88vh;overflow:auto;background:#313338;color:#f2f3f5;
            border-radius:12px;box-shadow:0 12px 40px rgba(0,0,0,.6);padding:18px 20px;font-size:14px;line-height:1.4}
        #dsb-panel .dsb-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:10px}
        #dsb-panel h2{margin:0;font-size:18px;font-weight:700;color:#fff}
        #dsb-panel .dsb-x{cursor:pointer;background:none;border:none;color:#b5bac1;font-size:22px;line-height:1;padding:0 4px}
        #dsb-panel .dsb-x:hover{color:#fff}
        #dsb-panel .dsb-sec{margin:16px 0 4px;font-size:12px;font-weight:700;text-transform:uppercase;
            letter-spacing:.04em;color:#b5bac1}
        #dsb-panel .dsb-hint{font-size:12px;color:#949ba4;margin:0 0 4px}
        #dsb-panel .dsb-row{display:flex;align-items:center;gap:10px;padding:5px 2px;cursor:pointer}
        #dsb-panel .dsb-row.inline{justify-content:space-between}
        #dsb-panel input[type=checkbox]{width:16px;height:16px;accent-color:#5865F2;flex:none;cursor:pointer}
        #dsb-panel input[type=number],#dsb-panel input[type=text],#dsb-panel select{
            background:#1e1f22;color:#f2f3f5;border:1px solid #1e1f22;border-radius:6px;padding:6px 8px;
            font-size:14px;outline:none}
        #dsb-panel input[type=number]{width:80px}
        #dsb-panel input[type=text]{width:100%;box-sizing:border-box}
        #dsb-panel input:focus,#dsb-panel select:focus{border-color:#5865F2}
        #dsb-panel .dsb-list{max-height:180px;overflow:auto;background:#2b2d31;border-radius:8px;padding:4px 10px;margin-top:6px}
        #dsb-panel .dsb-btns{display:flex;gap:8px;flex-wrap:wrap;margin-top:6px}
        #dsb-panel .dsb-b{flex:1;min-width:110px;padding:9px 12px;border:none;border-radius:8px;cursor:pointer;
            background:#4e5058;color:#fff;font-weight:600;font-size:14px}
        #dsb-panel .dsb-b.pri{background:#5865F2}
        #dsb-panel .dsb-b:hover{filter:brightness(1.12)}
        #dsb-panel .dsb-hist{font-size:12px;color:#b5bac1;line-height:1.7}
    `);

    const NS = 'http://www.w3.org/2000/svg';
    function svgEl(tag, attrs) {
        const el = document.createElementNS(NS, tag);
        for (const k in attrs) el.setAttribute(k, attrs[k]);
        return el;
    }
    function h(tag, props, ...kids) {
        const el = document.createElement(tag);
        for (const k in (props || {})) {
            const v = props[k];
            if (v === undefined || v === null || v === false) continue;
            if (k === 'class') el.className = v;
            else if (k === 'checked' || k === 'value' || k === 'disabled') el[k] = v;
            else if (k.startsWith('on')) el.addEventListener(k.slice(2), v);
            else el.setAttribute(k, v === true ? '' : v);
        }
        for (const kid of kids.flat()) if (kid !== null && kid !== undefined && kid !== false) el.append(kid);
        return el;
    }

    let rootEl, pillEl, btnEl, badgeEl, barEl, iconEl, pillText = '', flashTimer = null;
    let lastUnread = null;

    function setPill(text) {
        pillText = text;
        if (pillEl) pillEl.textContent = text;
    }
    function setProgress(p) {
        if (barEl) barEl.style.strokeDashoffset = String(RING_C * (1 - Math.max(0, Math.min(1, p))));
    }
    function setState(state) {
        if (!rootEl) return;
        rootEl.classList.remove('busy', 'done', 'error');
        if (state !== 'idle') rootEl.classList.add(state);
    }
    function setIcon(kind) {
        iconEl.replaceChildren();
        const s = svgEl('svg', { viewBox: '0 0 24 24', width: 26, height: 26, fill: 'none', stroke: 'currentColor',
            'stroke-width': 2.4, 'stroke-linecap': 'round', 'stroke-linejoin': 'round' });
        if (kind === 'error') {
            s.appendChild(svgEl('path', { d: 'M12 6v7' }));
            s.appendChild(svgEl('path', { d: 'M12 17.5v.01' }));
        } else {
            s.appendChild(svgEl('path', { d: 'M2 12.5l4.5 4.5L15 8.5' }));
            s.appendChild(svgEl('path', { d: 'M11 15.5l1.5 1.5L22 8.5' }));
        }
        iconEl.appendChild(s);
    }
    function flashResult(state, text, ms = 4500) {
        setState(state);
        setIcon(state === 'error' ? 'error' : 'check');
        setPill(text);
        setProgress(state === 'done' ? 1 : 0);
        rootEl.classList.add('flash');
        clearTimeout(flashTimer);
        flashTimer = setTimeout(() => {
            rootEl.classList.remove('flash');
            setState('idle');
            setIcon('check');
            setProgress(0);
            setPill(idleText());
        }, ms);
    }

    function computeUnread() {
        const gs = getGuildStore(), grs = getGuildReadStore();
        if (!gs || !grs) return null;
        try {
            const ids = gs.getGuildIds();
            let servers = 0, mentions = 0;
            for (const id of ids) {
                if (settings.excluded.includes(id)) continue;
                if (isGuildMuted(id)) continue; 
                const m = grs.getMentionCount(id) || 0;
                if (grs.hasAnyUnread(id) || m > 0) { servers++; mentions += m; }
            }
            return { servers, mentions };
        } catch { return null; }
    }

    function updateTooltip() {
        if (!btnEl) return;
        const hist = GM_getValue('history', []) || [];
        const parts = [];
        if (hist[0]) parts.push(t('lastRun', t('ago', Date.now() - hist[0].t), (hist[0].channels || 0) + (hist[0].dms || 0)));
        if (lastUnread) parts.push(t('unreadInfo', lastUnread.servers, lastUnread.mentions));
        btnEl.title = parts.join('\n');
    }

    function refreshBadge() {
        if (!rootEl || !badgeEl) return;
        const u = computeUnread();
        lastUnread = u;
        if (!u) {
            badgeEl.style.display = 'none';
            rootEl.classList.remove('faded');
        } else {
            badgeEl.textContent = u.servers > 99 ? '99+' : String(u.servers);
            badgeEl.style.display = u.servers > 0 ? 'flex' : 'none';
            rootEl.classList.toggle('faded', !!settings.autoHide && u.servers === 0 && u.mentions === 0);
        }
        updateTooltip();
    }

    function applyLang() {
        if (!rootEl) return;
        pillEl.dir = lang() === 'ar' ? 'rtl' : 'ltr';
        btnEl.setAttribute('aria-label', t('aria'));
        if (!running && !rootEl.classList.contains('flash')) setPill(idleText());
        updateTooltip();
    }

    function buildUI() {
        if (document.getElementById('dsb-root') || !document.body) return;

        rootEl = document.createElement('div');
        rootEl.id = 'dsb-root';

        pillEl = document.createElement('div');
        pillEl.id = 'dsb-pill';

        btnEl = document.createElement('div');
        btnEl.id = 'dsb-btn';
        btnEl.setAttribute('role', 'button');

        badgeEl = document.createElement('div');
        badgeEl.id = 'dsb-badge';

        const ring = svgEl('svg', { class: 'dsb-ring', viewBox: '0 0 64 64' });
        ring.appendChild(svgEl('circle', { class: 'dsb-track', cx: 32, cy: 32, r: 28 }));
        barEl = svgEl('circle', { class: 'dsb-bar', cx: 32, cy: 32, r: 28 });
        ring.appendChild(barEl);

        iconEl = document.createElement('span');
        iconEl.className = 'dsb-icon';

        btnEl.appendChild(iconEl);
        rootEl.append(pillEl, ring, btnEl, badgeEl);
        document.body.appendChild(rootEl);

        setIcon('check');
        setPill(idleText());

        const pos = GM_getValue('pos', null);
        if (pos) {
            rootEl.style.left = Math.min(pos.left, window.innerWidth - 64) + 'px';
            rootEl.style.top = Math.min(pos.top, window.innerHeight - 64) + 'px';
            rootEl.style.right = 'auto';
            rootEl.style.bottom = 'auto';
        }
        makeDraggable(rootEl, btnEl);
        btnEl.addEventListener('contextmenu', (e) => { e.preventDefault(); openPanel(); });

        applyLang();
        refreshBadge();
    }

    function makeDraggable(root, handle) {
        let down = false, moved = false, ox = 0, oy = 0, sx = 0, sy = 0;
        handle.addEventListener('mousedown', (e) => {
            if (e.button !== 0) return;
            down = true; moved = false;
            const r = root.getBoundingClientRect();
            ox = e.clientX - r.left; oy = e.clientY - r.top;
            sx = e.clientX; sy = e.clientY;
        });
        document.addEventListener('mousemove', (e) => {
            if (!down) return;
            if (!moved && Math.hypot(e.clientX - sx, e.clientY - sy) < 5) return;
            moved = true;
            root.classList.add('dragging');
            const left = Math.max(0, Math.min(window.innerWidth - 64, e.clientX - ox));
            const top = Math.max(0, Math.min(window.innerHeight - 64, e.clientY - oy));
            root.style.left = left + 'px';
            root.style.top = top + 'px';
            root.style.right = 'auto';
            root.style.bottom = 'auto';
        });
        document.addEventListener('mouseup', () => {
            if (!down) return;
            down = false;
            root.classList.remove('dragging');
            if (moved) {
                const r = root.getBoundingClientRect();
                GM_setValue('pos', { left: r.left, top: r.top });
            }
        });
        handle.addEventListener('click', () => { if (!moved) run({ scope: 'all' }); });
    }

    async function api(token, method, path, body) {
        for (let attempt = 0; attempt < 5; attempt++) {
            const res = await fetch(API + path, {
                method,
                headers: { Authorization: token, 'Content-Type': 'application/json' },
                body: body ? JSON.stringify(body) : undefined,
                signal: AbortSignal.timeout(20000),
            });
            if (res.status === 429) {
                const j = await res.json().catch(() => ({}));
                const wait = (j.retry_after || 1) + 0.2;
                const prev = pillText;
                setPill(t('rate', Math.ceil(wait)));
                await sleep(wait * 1000);
                setPill(prev);
                continue;
            }
            if (res.status === 401) throw new Error('Invalid or expired token');
            if (!res.ok) throw new Error(`${method} ${path} → ${res.status}`);
            return res.status === 204 ? null : res.json().catch(() => null);
        }
        throw new Error('Repeated rate limiting');
    }

    const pool = async (items, n, worker) => {
        let idx = 0;
        await Promise.all(Array.from({ length: n }, async () => {
            while (idx < items.length) await worker(items[idx++]);
        }));
    };

    function applyLocalAck(items) {
        const d = getDispatcher();
        if (!d || !items.length) return false;
        try {
            d.dispatch({
                type: 'BULK_ACK',
                context: 'APP',
                channels: items.map((s) => ({
                    channelId: s.channel_id,
                    messageId: s.message_id,
                    readStateType: s.read_state_type,
                })),
            });
            return true;
        } catch (e) {
            console.warn('[MarkRead] local ack failed', e);
            return false;
        }
    }

    function countStillUnread(items) {
        const store = getReadStateStore();
        if (!store) return -1;
        try {
            let n = 0;
            for (const s of items) if (store.hasUnread(s.channel_id)) n++;
            return n;
        } catch { return -1; }
    }

    async function ackBatch(token, chunk) {
        try {
            await api(token, 'POST', '/read-states/ack-bulk', { read_states: chunk });
            return chunk;
        } catch (e) {
            console.warn('[MarkRead] batch failed, retrying one by one:', e.message);
            if (!/→ \d+$/.test(e.message)) return [];
            const ok = [];
            for (const s of chunk) {
                try {
                    await api(token, 'POST', `/channels/${s.channel_id}/messages/${s.message_id}/ack`,
                        { token: null, manual: true, mention_count: 0 });
                    ok.push(s);
                } catch {}
            }
            return ok;
        }
    }

    async function collectDMs(token, states, dmIds) {
        const chans = await api(token, 'GET', '/users/@me/channels');
        for (const c of chans || []) {
            if ((c.type !== 1 && c.type !== 3) || !c.last_message_id) continue;
            if (settings.keepUnreadDMs && mentionCount(c.id) > 0) continue;
            if (settings.skipMuted && isChannelMuted(null, c.id)) continue;
            states.set(c.id, { channel_id: c.id, message_id: c.last_message_id, read_state_type: 0 });
            dmIds.add(c.id);
        }
    }

    const currentGuildId = () => {
        const m = location.pathname.match(/^\/channels\/(\d+)/);
        return m ? m[1] : null;
    };

    function saveHistory(entry) {
        const hist = GM_getValue('history', []) || [];
        hist.unshift(entry);
        GM_setValue('history', hist.slice(0, 15));
        GM_setValue('lastRun', entry.t);
    }

    async function run(opts = {}) {
        const scope = opts.scope || 'all';
        const silent = !!opts.silent;
        if (running) return;
        running = true;

        try {
            let gid = null;
            if (scope === 'current') {
                gid = currentGuildId();
                if (!gid) { flashResult('error', t('openServer'), 4500); if (!silent) soundError(); return; }
            }

            const token = getToken(silent);
            if (!token) {
                if (silent) return;
                throw new Error(t('noToken'));
            }

            clearTimeout(flashTimer);
            rootEl.classList.remove('flash');
            setIcon('check');
            setState('busy');
            setProgress(0.02);
            setPill(t('preparing'));

            let guilds = [], skippedServers = 0;
            if (scope === 'all') {
                const all = await api(token, 'GET', '/users/@me/guilds');
                guilds = all.filter((g) => !settings.excluded.includes(g.id) && !(settings.skipMuted && isGuildMuted(g.id)));
                skippedServers = all.length - guilds.length;
            } else if (scope === 'current') {
                guilds = [{ id: gid }];
            }
            const wantDMs = scope === 'dms' || (scope === 'all' && settings.includeDMs);
            const skipMutedCh = settings.skipMuted && scope === 'all';

            const states = new Map();
            const dmIds = new Set();
            const steps = (guilds.length + (wantDMs ? 1 : 0)) || 1;
            let done = 0;

            await pool(guilds, 8, async (g) => {
                try {
                    const channels = await api(token, 'GET', `/guilds/${g.id}/channels`);
                    for (const c of channels) {
                        if (!ACKABLE.has(c.type) || !c.last_message_id) continue;
                        if (skipMutedCh && isChannelMuted(g.id, c.id)) continue;
                        states.set(c.id, { channel_id: c.id, message_id: c.last_message_id, read_state_type: 0 });
                    }
                } catch (e) { console.warn('[MarkRead] skip guild', g.id, e.message); }

                try {
                    const j = await api(token, 'GET', `/guilds/${g.id}/threads/active`);
                    const joined = new Set(((j && j.members) || []).map((m) => m.id));
                    for (const th of (j && j.threads) || []) {
                        if (!joined.has(th.id) || !th.last_message_id) continue;
                        if (skipMutedCh && isChannelMuted(g.id, th.parent_id)) continue;
                        states.set(th.id, { channel_id: th.id, message_id: th.last_message_id, read_state_type: 0 });
                    }
                } catch {}

                done++;
                setPill(t('scanning', Math.min(done, guilds.length), guilds.length));
                setProgress((done / steps) * 0.5);
            });

            if (wantDMs) {
                setPill(t('scanningDMs'));
                try { await collectDMs(token, states, dmIds); } catch (e) { console.warn('[MarkRead] DMs failed', e.message); }
                done++;
                setProgress((done / steps) * 0.5);
            }
            soundBlipIf(!silent);

            const list = [...states.values()];

            if (!silent && settings.confirmAbove > 0 && list.length >= settings.confirmAbove) {
                if (!confirm(t('confirm', list.length, guilds.length))) {
                    clearSavedToken();
                    flashResult('idle', t('cancelled'), 2500);
                    return;
                }
            }

            const chunks = [];
            for (let i = 0; i < list.length; i += 100) chunks.push(list.slice(i, i + 100));

            const acked = [];
            let sent = 0, localOk = chunks.length === 0;
            await pool(chunks, 3, async (chunk) => {
                const ok = await ackBatch(token, chunk);
                if (ok.length) {
                    acked.push(...ok);
                    if (applyLocalAck(ok)) localOk = true;
                }
                sent++;
                setPill(t('marking', sent, chunks.length));
                setProgress(0.5 + (sent / chunks.length) * 0.5);
            });

            clearSavedToken();

            const dmAcked = acked.filter((s) => dmIds.has(s.channel_id)).length;
            const summary = t('summary', {
                servers: guilds.length,
                channels: acked.length - dmAcked,
                dms: dmAcked,
                skipped: list.length - acked.length,
                skippedServers,
            });

            saveHistory({ t: Date.now(), scope, servers: guilds.length, channels: acked.length - dmAcked, dms: dmAcked });
            flashResult('done', t('done', summary), silent ? 2500 : 4500);
            if (!silent) {
                soundSuccess();
                notify(t('notifyDone'), summary);
            }
            setTimeout(refreshBadge, 700);

            if (!silent) {
                const leftover = countStillUnread(acked);
                if (!localOk || leftover !== 0) {
                    console.log('[MarkRead] UI not fully cleared (leftover:', leftover, ') → reloading');
                    setTimeout(() => location.reload(), 1800);
                }
            }
        } catch (e) {
            console.error('[MarkRead]', e);
            clearSavedToken();
            flashResult('error', t('failed', e.message), 6000);
            if (!silent) {
                soundError();
                notify(t('notifyFail'), e.message);
            }
        } finally {
            running = false;
        }
    }
    function soundBlipIf(cond) { if (cond) soundBlip(); }

    let autoTimer = null;
    function scheduleAuto() {
        clearInterval(autoTimer);
        autoTimer = null;
        if (!settings.autoRun) return;
        autoTimer = setInterval(() => {
            if (running || document.hidden) return;
            const last = GM_getValue('lastRun', 0);
            if (Date.now() - last < Math.max(1, settings.autoMinutes) * 60000) return;
            // nothing unread (and no DMs requested)? skip the whole scan
            if (!settings.includeDMs) {
                const u = computeUnread();
                if (u && u.servers === 0 && u.mentions === 0) return;
            }
            run({ scope: 'all', silent: true });
        }, 30000);
    }

    let backEl = null;
    function closePanel() {
        if (backEl) { backEl.remove(); backEl = null; }
    }

    function onChanged(key) {
        if (key === 'autoRun' || key === 'autoMinutes') scheduleAuto();
        if (key === 'autoHide' || key === 'skipMuted') refreshBadge();
        if (key === 'lang') { applyLang(); openPanel(); }
    }

    async function loadGuilds() {
        const byName = (a, b) => a.name.localeCompare(b.name);
        const gs = getGuildStore();
        if (gs) {
            try {
                const arr = Object.values(gs.getGuilds()).map((g) => ({ id: g.id, name: g.name }));
                if (arr.length) return arr.sort(byName);
            } catch {}
        }
        const token = getToken(true);
        if (token) {
            try {
                const arr = await api(token, 'GET', '/users/@me/guilds');
                return arr.map((g) => ({ id: g.id, name: g.name })).sort(byName);
            } catch {}
        }
        return [];
    }

    function openPanel() {
        closePanel();
        if (!document.body) return;
        const s = settings;

        const toggle = (key, label) => h('label', { class: 'dsb-row' },
            h('input', { type: 'checkbox', checked: !!s[key], onchange: (e) => { s[key] = e.target.checked; saveSettings(); onChanged(key); } }),
            h('span', {}, label));

        const number = (key, label, min, max) => h('label', { class: 'dsb-row inline' },
            h('span', {}, label),
            h('input', {
                type: 'number', min, max, value: s[key],
                onchange: (e) => {
                    let v = parseInt(e.target.value, 10);
                    if (isNaN(v)) v = DEFAULTS[key];
                    v = Math.max(min, Math.min(max, v));
                    e.target.value = v;
                    s[key] = v; saveSettings(); onChanged(key);
                },
            }));

        const langSel = h('select', { onchange: (e) => { s.lang = e.target.value; saveSettings(); onChanged('lang'); } },
            [['auto', t('pLangAuto')], ['en', 'English'], ['ar', 'العربية']].map(([v, l]) => {
                const o = h('option', { value: v }, l);
                if (s.lang === v) o.selected = true;
                return o;
            }));

        let guilds = [];
        const listEl = h('div', { class: 'dsb-list' }, t('pLoading'));
        const search = h('input', { type: 'text', placeholder: t('pSearch'), oninput: () => renderList() });
        function renderList() {
            const q = search.value.trim().toLowerCase();
            listEl.replaceChildren();
            const shown = guilds.filter((g) => g.name.toLowerCase().includes(q));
            if (!shown.length) { listEl.append(t('pNone')); return; }
            for (const g of shown) {
                listEl.append(h('label', { class: 'dsb-row' },
                    h('input', {
                        type: 'checkbox', checked: s.excluded.includes(g.id),
                        onchange: (e) => {
                            const i = s.excluded.indexOf(g.id);
                            if (e.target.checked) { if (i < 0) s.excluded.push(g.id); }
                            else if (i >= 0) s.excluded.splice(i, 1);
                            saveSettings(); refreshBadge();
                        },
                    }),
                    h('span', {}, g.name)));
            }
        }
        loadGuilds().then((arr) => { guilds = arr; renderList(); });

        const act = (scope, label, pri) => h('button', {
            class: 'dsb-b' + (pri ? ' pri' : ''),
            onclick: () => { closePanel(); run({ scope }); },
        }, label);

        const hist = GM_getValue('history', []) || [];
        const scopeLabel = { all: t('scopeAll'), current: t('scopeCurrent'), dms: t('scopeDMs') };
        const histEl = h('div', { class: 'dsb-hist' },
            hist.length
                ? hist.slice(0, 5).map((e) => h('div', {},
                    `${new Date(e.t).toLocaleString()} — ${scopeLabel[e.scope] || e.scope} — ${t('summary', { servers: e.servers, channels: e.channels, dms: e.dms || 0, skipped: 0, skippedServers: 0 })}`))
                : t('pNoHistory'));

        const panel = h('div', { id: 'dsb-panel', dir: lang() === 'ar' ? 'rtl' : 'ltr' },
            h('div', { class: 'dsb-head' },
                h('h2', {}, t('pTitle')),
                h('button', { class: 'dsb-x', onclick: closePanel }, '×')),

            h('div', { class: 'dsb-sec' }, t('pActions')),
            h('div', { class: 'dsb-btns' },
                act('all', t('pBtnAll'), true),
                act('current', t('pBtnCurrent')),
                act('dms', t('pBtnDMs'))),

            h('div', { class: 'dsb-sec' }, t('pGeneral')),
            toggle('sound', t('pSound')),
            toggle('notify', t('pNotify')),
            toggle('skipMuted', t('pSkipMuted')),
            toggle('includeDMs', t('pIncludeDMs')),
            toggle('keepUnreadDMs', t('pKeepDMs')),
            toggle('autoHide', t('pAutoHide')),
            number('confirmAbove', t('pConfirm'), 0, 5000),
            h('label', { class: 'dsb-row inline' }, h('span', {}, t('pLang')), langSel),

            h('div', { class: 'dsb-sec' }, t('pAuto')),
            toggle('runOnOpen', t('pRunOnOpen')),
            toggle('autoRun', t('pAutoRun')),
            number('autoMinutes', t('pEveryMin'), 1, 1440),

            h('div', { class: 'dsb-sec' }, t('pServers')),
            h('p', { class: 'dsb-hint' }, t('pServersHint')),
            search,
            listEl,

            h('div', { class: 'dsb-sec' }, t('pHistory')),
            histEl);

        backEl = h('div', { id: 'dsb-back', onmousedown: (e) => { if (e.target === backEl) closePanel(); } }, panel);
        document.body.appendChild(backEl);
    }

    function diagnose() {
        const ok = (v) => (v ? '✓' : '✗');
        alert([
            'Dispatcher (instant UI clear): ' + ok(getDispatcher()),
            'ReadStateStore: ' + ok(getReadStateStore()),
            'GuildReadStateStore (counter): ' + ok(getGuildReadStore()),
            'GuildStore (server names): ' + ok(getGuildStore()),
            'Mute settings (skip muted): ' + ok(getMuteStore()),
            'Counter now: ' + JSON.stringify(computeUnread()),
        ].join('\n'));
    }

    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && backEl) { closePanel(); return; }
        if (!(e.ctrlKey && e.altKey)) return;
        if (e.code === 'KeyA') { e.preventDefault(); run({ scope: 'all' }); }
        else if (e.code === 'KeyS') { e.preventDefault(); run({ scope: 'current' }); }
        else if (e.code === 'KeyD') { e.preventDefault(); run({ scope: 'dms' }); }
    });

    GM_registerMenuCommand(t('mAll'), () => run({ scope: 'all' }));
    GM_registerMenuCommand(t('mCurrent'), () => run({ scope: 'current' }));
    GM_registerMenuCommand(t('mDMs'), () => run({ scope: 'dms' }));
    GM_registerMenuCommand(t('mSettings'), openPanel);
    GM_registerMenuCommand(t('mDiag'), diagnose);
    GM_registerMenuCommand(t('mClearToken'), () => { clearSavedToken(); alert(t('tokenCleared')); });
    GM_registerMenuCommand(t('mReset'), () => {
        GM_setValue('pos', null);
        location.reload();
    });

    clearSavedToken();

    buildUI();
    new MutationObserver(buildUI).observe(document.documentElement, { childList: true, subtree: true });
    scheduleAuto();
    setInterval(refreshBadge, 4000);
    if (settings.runOnOpen) setTimeout(() => run({ scope: 'all', silent: true }), 8000);
})();