미디어위키:Common.js: 두 판 사이의 차이

(Install package: clbiwiki-globe-shared-no-blocking-prewarm-20260710 / js/Common.js)
(Install package: clbiwiki-portal-section-fit-20260721-008 / js/Common.js)
 
(같은 사용자의 중간 판 68개는 보이지 않습니다)
3번째 줄: 3번째 줄:
/* Raw MediaWiki script cache key.
/* Raw MediaWiki script cache key.
   This is not a semantic version. It only prevents stale raw JS during active editing. */
   This is not a semantic version. It only prevents stale raw JS during active editing. */
window.CLBI_RAW_LOAD_BUST = window.CLBI_RAW_LOAD_BUST || 'entry-raw-revision-ledger-20260710';
window.CLBI_RAW_LOAD_BUST = 'portal-frame-section-fit-20260721-008';


/*
/*
65번째 줄: 65번째 줄:


/* =========================================
/* =========================================
  Boot gate prelude
Main-page fresh assets with fallback
  =========================================
========================================= */
  This tiny prelude runs before the full EntryStore/EntryLoader/BootGate implementation.
 
  Its job is only to guarantee that the user sees the separate loading surface before the
/*
  normal wiki shell can paint.  The full BootGate later adopts the same DOM node and keeps
Common.css의 MainPage.css import는 안전망으로 그대로 유지한다.
  it open until the real full-entry readiness contract is satisfied.
대문에서는 새로고침마다 timestamp가 붙은 CSS/JS를 추가로 불러와
브라우저·프록시의 오래된 raw 응답을 우회한다.


  Maintenance rule:
이 보조 로더가 실패해도 기존 정적 import와 기존 화면은 남는다.
  - Do not move first-screen hiding into a late subsystem callback.  If the boot gate is
    meant to protect the first impression, the surface must be activated before sidebars,
    navbars, document wells, nations panels, or other entry surfaces can visibly fill in.
  - New names remain unprefixed.  Existing prefixed names elsewhere are legacy aliases only.
*/
*/
(function installBootGatePrelude(window, document) {
window.MainPageFreshAssets = window.MainPageFreshAssets || (function (window, document, mw) {
     'use strict';
     'use strict';


     var SCREEN_ID = 'boot-gate-screen';
     var sessionToken = String(Date.now());
     var STYLE_ID = 'boot-gate-prelude-style';
     var PORTAL_FRAME_BUILD = '20260721-portal-frame-section-fit-008';
     var START_TIME = Date.now ? Date.now() : new Date().getTime();
     var ASSET_LOAD_TIMEOUT_MS = 5000;
     function hasQueryFlag(name, value) {
     var scriptPromises = {};
        var search = String(window.location && window.location.search || '');
    var styleNode = null;
        var re = new RegExp('[?&]' + name + '=([^&]+)');
        var match = search.match(re);
        return !!(match && decodeURIComponent(match[1]) === value);
    }


     function getMwConfig(name, fallback) {
     function isMainPage() {
        var page = '';
         try {
         try {
             if (window.mw && window.mw.config && typeof window.mw.config.get === 'function') {
             page = String(mw && mw.config ? mw.config.get('wgPageName') || '' : '');
                var value = window.mw.config.get(name);
                return value == null ? fallback : value;
            }
         } catch (err) {}
         } catch (err) {}
         return fallback;
         return page.replace(/_/g, ' ') === '대문';
     }
     }


     function normalizePageName(value) {
     function rawUrl(title, type) {
         return String(value || '').split('?')[0].replace(/^\/index\.php\//, '').replace(/_/g, ' ').trim();
         var ctype = type === 'style' ? 'text/css' : 'text/javascript';
        return '/index.php?title=' + encodeURIComponent(title) +
            '&action=raw&ctype=' + encodeURIComponent(ctype) +
            '&_mainPageFresh=' + encodeURIComponent(sessionToken);
     }
     }


     function isDeveloperOrEditingPage() {
     function loadStyle() {
         var ns = Number(getMwConfig('wgNamespaceNumber', NaN));
         if (!isMainPage()) return Promise.resolve(false);
         var action = String(getMwConfig('wgAction', 'view') || 'view').toLowerCase();
 
         var model = String(getMwConfig('wgPageContentModel', '') || '').toLowerCase();
         if (styleNode && styleNode.parentNode) {
        var name = normalizePageName(getMwConfig('wgPageName', '') || window.location.pathname || '');
            return Promise.resolve(true);
        var systemNamespaces = {
         }
             '-1': true, '4': true, '5': true, '6': true, '7': true, '8': true, '9': true,
 
             '10': true, '11': true, '12': true, '13': true, '14': true, '15': true,
        return new Promise(function (resolve) {
             '828': true, '829': true
            var link = document.createElement('link');
        };
            var settled = false;
             var timeout = 0;
 
             function settle(ok) {
                if (settled) return;
                settled = true;
                window.clearTimeout(timeout);
                resolve(ok);
             }


        /*
            link.rel = 'stylesheet';
        * Developer/system pages must stay practical. Editing MediaWiki:, File:,
            link.href = rawUrl('MediaWiki:MainPage.css', 'style');
        * Project:, Template:, Module:, Category:, or any non-view action already forces
            link.setAttribute('data-main-page-fresh-style', sessionToken);
        * a full page load in MediaWiki, so showing the entry boot screen there only slows
            link.onload = function () {
        * maintenance work and does not improve the public first impression.
                styleNode = link;
        */
                settle(true);
        if (hasQueryFlag('bootGatePreview', '1')) return false;
            };
        if (action && action !== 'view') return true;
            link.onerror = function () {
        if (systemNamespaces[String(ns)]) return true;
                /* Common.css의 정적 import가 그대로 남아 있으므로 화면은 유지된다. */
        if (model === 'css' || model === 'javascript' || model === 'json' || model === 'sanitized-css') return true;
                settle(false);
        if (/\.(?:css|js|json)$/i.test(name)) return true;
            };
        if (/^(?:mediawiki|미디어위키|file|파일|project|프로젝트|template|틀|module|모듈|category|분류|special|특수):/i.test(name)) return true;
            timeout = window.setTimeout(function () { settle(false); }, ASSET_LOAD_TIMEOUT_MS);
         return false;
            (document.head || document.documentElement).appendChild(link);
         });
     }
     }


     var disabled = hasQueryFlag('bootGate', '0') || isDeveloperOrEditingPage();
     function loadScript(title) {
        var key = String(title || '').trim();
 
        if (!key || !isMainPage()) return Promise.resolve(false);
        if (scriptPromises[key]) return scriptPromises[key];
 
        scriptPromises[key] = new Promise(function (resolve) {
            var script = document.createElement('script');
            var settled = false;
            var timeout = 0;


    function injectStyle() {
            function settle(ok) {
        var style;
                if (settled) return;
        if (disabled || document.getElementById(STYLE_ID)) return;
                settled = true;
        style = document.createElement('style');
                window.clearTimeout(timeout);
        style.id = STYLE_ID;
                resolve(ok);
        style.textContent = [
             }
             'html.boot-gate-active,body.boot-gate-active{overflow:hidden!important;}',
 
             'html.boot-gate-active body{background:#080808!important;}',
             script.src = rawUrl(key, 'script');
            'html.boot-gate-active body>:not(#boot-gate-screen){visibility:hidden!important;pointer-events:none!important;}',
             script.async = false;
             'html.boot-gate-active #boot-gate-screen,html.boot-gate-active #boot-gate-screen *{visibility:visible!important;}',
             script.setAttribute('data-main-page-fresh-script', key);
             '#boot-gate-screen{position:fixed!important;inset:0!important;z-index:2147483000!important;display:flex!important;align-items:center!important;justify-content:center!important;background:#080808!important;color:#d8d8d8!important;opacity:1;pointer-events:auto!important;}',
             script.onload = function () { settle(true); };
             '#boot-gate-screen .boot-gate-decoration-layer{position:absolute;inset:0;z-index:1;pointer-events:none;overflow:hidden;}',
             script.onerror = function () { settle(false); };
             '#boot-gate-screen .boot-gate-panel{position:relative;z-index:2;}',
             timeout = window.setTimeout(function () {
             '#boot-gate-screen .boot-gate-close{display:none;position:absolute;right:7px;top:6px;z-index:3;height:18px;min-width:18px;border:1px solid #000;background:#141414;color:#ddd;font-size:11px;line-height:16px;padding:0 5px;cursor:pointer;}',
                if (script.parentNode) script.parentNode.removeChild(script);
            '#boot-gate-screen.is-preview{inset:auto!important;left:18px!important;top:18px!important;width:min(720px,calc(100vw - 380px))!important;height:360px!important;z-index:99990!important;overflow:hidden!important;border:1px solid #000!important;box-shadow:0 10px 28px rgba(0,0,0,.55)!important;pointer-events:none!important;}',
                settle(false);
             '#boot-gate-screen.is-preview .boot-gate-panel,#boot-gate-screen.is-preview .boot-gate-close{pointer-events:auto!important;}',
             }, ASSET_LOAD_TIMEOUT_MS);
            '#boot-gate-screen.is-preview .boot-gate-close{display:block;}'
            (document.head || document.documentElement).appendChild(script);
        ].join('');
        });
        (document.head || document.documentElement).appendChild(style);
    }


    function activate() {
         return scriptPromises[key];
         if (disabled) return;
        injectStyle();
        if (document.documentElement) document.documentElement.classList.add('boot-gate-active');
        if (document.body) document.body.classList.add('boot-gate-active');
     }
     }


     function makeNode() {
     function validatePortalFrameSet() {
         var node;
         var modules = [
        var panel;
            ['PortalFrame', window.PortalFrame],
        var title;
            ['CategoryNav', window.CategoryNav],
        var status;
            ['CategoryPillar', window.CategoryPillar],
         var meter;
            ['PortalSectionNav', window.PortalSectionNav],
         var fill;
            ['BottomGuideNav', window.BottomGuideNav]
        var progress;
         ];
        var detail;
         var mismatches = modules.filter(function (entry) {
        var decoLayer;
            var module = entry[1];
         var close;
            var version = module && (module.frameVersion || module.version);
            return version !== PORTAL_FRAME_BUILD;
         });


         if (disabled || !document.body) return null;
         document.documentElement.toggleAttribute(
         activate();
            'data-portal-frame-build-mismatch',
            mismatches.length > 0
        );
         document.documentElement.setAttribute('data-portal-frame-build', PORTAL_FRAME_BUILD);


        node = document.getElementById(SCREEN_ID);
         if (mismatches.length && window.console && typeof window.console.error === 'function') {
         if (node) return node;
            window.console.error(
 
                '[PortalFrame] 원자적 배포 세트의 버전이 일치하지 않습니다:',
        node = document.createElement('div');
                mismatches.map(function (entry) { return entry[0]; }).join(', ')
        node.id = SCREEN_ID;
            );
        node.className = 'boot-gate-screen is-active';
         }
        node.setAttribute('role', 'status');
        return mismatches.length === 0;
        node.setAttribute('aria-live', 'polite');
    }
         node.setAttribute('data-boot-gate-prelude', '1');


        panel = document.createElement('div');
    function ensure() {
         panel.className = 'boot-gate-panel';
         if (!isMainPage()) return Promise.resolve(false);


         title = document.createElement('div');
         return loadStyle()
         title.className = 'boot-gate-title';
            .then(function () {
         title.textContent = 'ARCHIVE INITIALIZATION';
                return loadScript('MediaWiki:CategoryNav.js');
            })
            .then(function () {
                return loadScript('MediaWiki:CategoryPillar.js');
            })
            .then(function () {
                return loadScript('MediaWiki:PortalSectionNav.js');
            })
            .then(function () {
                return loadScript('MediaWiki:BottomGuideNav.js');
            })
            .then(function () {
                validatePortalFrameSet();
                if (window.CategoryNav && typeof window.CategoryNav.renderAll === 'function') {
                    window.CategoryNav.renderAll(document);
                }
                if (window.CategoryPillar && typeof window.CategoryPillar.renderAll === 'function') {
                    window.CategoryPillar.renderAll(document);
                }
                if (window.PortalSectionNav && typeof window.PortalSectionNav.renderAll === 'function') {
                    window.PortalSectionNav.renderAll(document);
                }
                if (window.BottomGuideNav && typeof window.BottomGuideNav.render === 'function') {
                    window.BottomGuideNav.render();
                }
                return true;
            });
    }
 
    function status() {
         return {
            mainPage: isMainPage(),
            token: sessionToken,
            style: !!document.querySelector('link[data-main-page-fresh-style]'),
            category: !!document.querySelector(
                'script[data-main-page-fresh-script="MediaWiki:CategoryNav.js"]'
            ),
            pillar: !!document.querySelector(
                'script[data-main-page-fresh-script="MediaWiki:CategoryPillar.js"]'
            ),
            section: !!document.querySelector(
                'script[data-main-page-fresh-script="MediaWiki:PortalSectionNav.js"]'
            ),
            guide: !!document.querySelector(
                'script[data-main-page-fresh-script="MediaWiki:BottomGuideNav.js"]'
            ),
            frameBuild: PORTAL_FRAME_BUILD,
            frameConsistent: validatePortalFrameSet()
        };
    }
 
    if (mw && mw.hook) {
         mw.hook('wikipage.content').add(function () {
            ensure();
        });
    }
 
    window.setTimeout(ensure, 0);
 
    return {
        ensure: ensure,
        status: status
    };
}(window, document, window.mw));


        status = document.createElement('div');
        status.className = 'boot-gate-status';
        status.textContent = 'Preparing site entry systems';


        meter = document.createElement('div');
/* =========================================
        meter.className = 'boot-gate-meter';
  Account access page marker
        fill = document.createElement('div');
  =========================================
        fill.className = 'boot-gate-meter-fill';
  New shared systems use unprefixed names. The server body class differs
        meter.appendChild(fill);
  between skins/locales, so the canonical special-page name is normalized
  once and exposed as a stable page-state class for the login surface.
*/
(function markAccountLoginPage(window, document) {
    'use strict';


        progress = document.createElement('div');
    var canonical = '';
        progress.className = 'boot-gate-progress';
    var pageName = '';
        progress.textContent = '0%';
    var isLoginPage = false;


         detail = document.createElement('div');
    try {
         detail.className = 'boot-gate-detail';
         canonical = String(window.mw && mw.config ? mw.config.get('wgCanonicalSpecialPageName') || '' : '').toLowerCase();
        detail.textContent = 'boot gate prelude';
         pageName = String(window.mw && mw.config ? mw.config.get('wgPageName') || '' : '').replace(/_/g, ' ').toLowerCase();
    } catch (err) {}


        close = document.createElement('button');
    isLoginPage = canonical === 'userlogin' || /^(?:special|특수):(?:userlogin|로그인)$/.test(pageName);
        close.type = 'button';
    if (!isLoginPage) return;
        close.className = 'boot-gate-close';
        close.setAttribute('aria-label', 'Close boot preview');
        close.textContent = '×';
        close.addEventListener('click', function () { release(node); });


        decoLayer = document.createElement('div');
    document.documentElement.classList.add('account-login-page-root');
        decoLayer.className = 'boot-gate-decoration-layer';
        decoLayer.setAttribute('data-decoration-target', 'boot-gate');
        decoLayer.setAttribute('aria-hidden', 'true');


        panel.appendChild(title);
    function isCreateAccountTarget(link) {
         panel.appendChild(status);
         var href = '';
         panel.appendChild(meter);
         var title = '';
         panel.appendChild(progress);
         var text = '';
         panel.appendChild(detail);
         var sample = '';
        node.appendChild(decoLayer);
        node.appendChild(panel);
        node.appendChild(close);


         document.body.insertBefore(node, document.body.firstChild || null);
         if (!link) return false;
         return node;
        href = String(link.getAttribute('href') || '');
        title = String(link.getAttribute('title') || '');
        text = String(link.textContent || '');
        try { href = decodeURIComponent(href); } catch (err) {}
        sample = (href + ' ' + title + ' ' + text).replace(/_/g, ' ').toLowerCase();
         return /(?:special|특수)\s*[:%]\s*(?:createaccount|계정\s*(?:만들기|생성))|createaccount|계정\s*(?:만들기|생성)/i.test(sample);
     }
     }


     function onBody(callback) {
     function suppressCreateAccountSurface(root) {
         if (document.body) {
         var scope = root && root.querySelectorAll ? root : document;
             callback();
        var fixedSelectors = [
             return;
            '.mw-createacct-benefits-container',
         }
            '.mw-createacct-benefits-list',
         if (document.readyState === 'loading') {
            '.mw-createaccount-cta',
             document.addEventListener('DOMContentLoaded', callback, { once: true });
            '.mw-createaccount-join',
        }
            '#mw-createaccount-join',
        window.setTimeout(function tick() {
            '.mw-userlogin-create'
             if (document.body) return callback();
        ];
            window.setTimeout(tick, 10);
 
         }, 0);
        fixedSelectors.forEach(function (selector) {
             Array.prototype.forEach.call(scope.querySelectorAll(selector), function (node) {
                node.style.setProperty('display', 'none', 'important');
                node.setAttribute('aria-hidden', 'true');
             });
         });
 
         Array.prototype.forEach.call(scope.querySelectorAll('a[href]'), function (link) {
             var container;
            if (!isCreateAccountTarget(link)) return;
 
            link.style.setProperty('display', 'none', 'important');
            link.setAttribute('aria-hidden', 'true');
            link.setAttribute('tabindex', '-1');
 
            container = link.closest('.mw-ui-vform-field, .oo-ui-fieldLayout, .mw-userlogin-create, p, li');
             if (container && container.querySelectorAll('a').length === 1) {
                container.style.setProperty('display', 'none', 'important');
                container.setAttribute('aria-hidden', 'true');
            }
         });
     }
     }


     function release(node) {
     function applyMarker() {
        node = node || document.getElementById(SCREEN_ID);
         if (!document.body) return;
         if (node) {
         document.body.classList.add('account-login-page');
            node.classList.add('is-complete');
        suppressCreateAccountSurface(document);
            node.classList.remove('is-active');
            window.setTimeout(function () {
                if (node.parentNode) node.parentNode.removeChild(node);
            }, 240);
         }
        window.setTimeout(function () {
            if (document.documentElement) document.documentElement.classList.remove('boot-gate-active');
            if (document.body) document.body.classList.remove('boot-gate-active');
        }, 250);
     }
     }


     activate();
     if (document.readyState === 'loading') {
    onBody(function () {
         document.addEventListener('DOMContentLoaded', applyMarker, { once: true });
         activate();
    } else {
         makeNode();
         applyMarker();
     });
     }


     window.__BootGatePrelude = {
     try {
        startTime: START_TIME,
        if (window.mw && mw.hook) {
        activate: activate,
            mw.hook('wikipage.content').add(function (content) {
        ensure: makeNode,
                suppressCreateAccountSurface(content && content[0] ? content[0] : document);
        release: release,
            });
        node: function () { return document.getElementById(SCREEN_ID); },
         }
         disabled: disabled
     } catch (err) {}
     };
})(window, document);
})(window, document);


/* =========================================
/* =========================================
   Site boot gate and entry artifact contract
   Boot gate prelude
   =========================================
   =========================================
   This is the initial-load full/half entry artifact system.
   This tiny prelude runs before the full EntryStore/EntryLoader/BootGate implementation.
  Its job is only to guarantee that the user sees the separate loading surface before the
  normal wiki shell can paint.  The full BootGate later adopts the same DOM node and keeps
  it open until the real full-entry readiness contract is satisfied.


   Purpose:
   Maintenance rule:
   - The loading screen is not decorative. It exists only during the first site entry in a
   - Do not move first-screen hiding into a late subsystem callback.  If the boot gate is
    tab, before the user is allowed into the normal wiki surface.
    meant to protect the first impression, the surface must be activated before sidebars,
  - A "full" entry must mean that the first view of that system can appear without an
     navbars, document wells, nations panels, or other entry surfaces can visibly fill in.
    additional visible data load. For the nations system, the 1950 entry is full only when
   - New names remain unprefixedExisting prefixed names elsewhere are legacy aliases only.
    its nation list/link-map data and first-view pixel decorations are ready in this tab.
*/
  - A "half" entry is a predictive warm state for the next likely path. It may fetch and
(function installBootGatePrelude(window, document) {
    parse data, but may skip expensive final work such as image/canvas preparation until it
     is promoted to full.
  - This principle is a site-wide design priority, like SPA continuity. New viewers,
    document systems, and information panels should define their entry full/half packs
    before exposing a first screen that can visibly fill in later.
   - SPA navigation is a consumer phase, not a blocking phaseDo not add BootGate holds
    to SPA route changes.  If a route needs seamless first paint, prepare its artifacts
    during the initial boot pack and have the subsystem consume EntryStore synchronously
    before inserting or painting visible DOM.
 
  Naming rule:
  - New public APIs, globals, classes, functions, files, and components must not use a
    project prefix. Old prefixed globals are legacy compatibility surfaces only.
  - New code should use names such as BootGate, EntryLoader, EntryStore, and boot-gate-*.
*/
(function (window, document, mw) {
     'use strict';
     'use strict';


     var MANIFEST_TITLE = 'MediaWiki:EntryManifest.json';
     var SCREEN_ID = 'boot-gate-screen';
    var BUILD_ID = '20260710-globe-shared-no-blocking-prewarm-001';
     var STYLE_ID = 'boot-gate-prelude-style';
     var READY_KEY = 'boot-gate-ready-version';
     var START_TIME = Date.now ? Date.now() : new Date().getTime();
     var DISMISS_PARAM = 'bootGate';
    var bootStarted = false;
    var bootPromise = null;
    var bootNode = null;
    var bootStatusNode = null;
    var bootProgressNode = null;
    var bootDetailNode = null;
    var bootFillNode = null;
    var bootStartTime = 0;
    var earlyBootStyleInjected = false;
 
     function hasQueryFlag(name, value) {
     function hasQueryFlag(name, value) {
         var search = String(window.location && window.location.search || '');
         var search = String(window.location && window.location.search || '');
332번째 줄: 388번째 줄:
     }
     }


     function readConfig(name, fallback) {
     function getMwConfig(name, fallback) {
         try {
         try {
             if (mw && mw.config && typeof mw.config.get === 'function') {
             if (window.mw && window.mw.config && typeof window.mw.config.get === 'function') {
                 var value = mw.config.get(name);
                 var value = window.mw.config.get(name);
                 return value == null ? fallback : value;
                 return value == null ? fallback : value;
             }
             }
342번째 줄: 398번째 줄:
     }
     }


     function normalizeBootPageName(value) {
     function normalizePageName(value) {
         return String(value || '').split('?')[0].replace(/^\/index\.php\//, '').replace(/_/g, ' ').trim();
         return String(value || '').split('?')[0].replace(/^\/index\.php\//, '').replace(/_/g, ' ').trim();
     }
     }


     function isBootExcludedPage() {
     function isDeveloperOrEditingPage() {
         var ns = Number(readConfig('wgNamespaceNumber', NaN));
         var ns = Number(getMwConfig('wgNamespaceNumber', NaN));
         var action = String(readConfig('wgAction', 'view') || 'view').toLowerCase();
         var action = String(getMwConfig('wgAction', 'view') || 'view').toLowerCase();
         var model = String(readConfig('wgPageContentModel', '') || '').toLowerCase();
         var model = String(getMwConfig('wgPageContentModel', '') || '').toLowerCase();
         var name = normalizeBootPageName(readConfig('wgPageName', '') || window.location.pathname || '');
         var name = normalizePageName(getMwConfig('wgPageName', '') || window.location.pathname || '');
         var systemNamespaces = {
         var systemNamespaces = {
             '-1': true, '4': true, '5': true, '6': true, '7': true, '8': true, '9': true,
             '-1': true, '4': true, '5': true, '6': true, '7': true, '8': true, '9': true,
358번째 줄: 414번째 줄:


         /*
         /*
         * The public boot gate is for normal reading surfaces.  Developer/system
         * Developer/system pages must stay practical.  Editing MediaWiki:, File:,
         * namespaces and edit/diff/history actions already reload outside SPA, so
         * Project:, Template:, Module:, Category:, or any non-view action already forces
         * blocking them would turn every maintenance save into another entry boot.
        * a full page load in MediaWiki, so showing the entry boot screen there only slows
         * maintenance work and does not improve the public first impression.
         */
         */
         if (hasQueryFlag('bootGatePreview', '1')) return false;
         if (hasQueryFlag('bootGatePreview', '1')) return false;
371번째 줄: 428번째 줄:
     }
     }


     var BOOT_EXCLUDED_PAGE = isBootExcludedPage();
     function isAnonymousUser() {
        var userName = getMwConfig('wgUserName', null);
        var userId = Number(getMwConfig('wgUserId', 0) || 0);
        return !userName && !userId;
    }


     function injectEarlyBootStyle() {
     function isAuthenticationPage() {
        var canonical = String(getMwConfig('wgCanonicalSpecialPageName', '') || '').toLowerCase();
        var name = normalizePageName(getMwConfig('wgPageName', '') || window.location.pathname || '').toLowerCase();
        var allowed = {
            userlogin: true,
            passwordreset: true,
            resetpass: true,
            confirmemail: true
        };
 
        if (allowed[canonical]) return true;
        return /^(?:special|특수):(?:userlogin|로그인|passwordreset|비밀번호 ?재설정|resetpass|confirmemail)/i.test(name);
    }
 
    var anonymousUser = isAnonymousUser();
    var disabled = isAuthenticationPage() || (!anonymousUser && (hasQueryFlag('bootGate', '0') || isDeveloperOrEditingPage()));
 
    function injectStyle() {
         var style;
         var style;
         if (earlyBootStyleInjected || !document.documentElement) return;
         if (disabled || document.getElementById(STYLE_ID)) return;
        earlyBootStyleInjected = true;
         style = document.createElement('style');
         style = document.createElement('style');
         style.id = 'boot-gate-early-style';
         style.id = STYLE_ID;
         style.textContent = [
         style.textContent = [
             'html.boot-gate-active, body.boot-gate-active{overflow:hidden!important;}',
             'html.boot-gate-active,body.boot-gate-active{overflow:hidden!important;}',
             'html.boot-gate-active body{background:#080808!important;}',
             'html.boot-gate-active body{background:#080808!important;}',
             'html.boot-gate-active body> :not(#boot-gate-screen){visibility:hidden!important;pointer-events:none!important;}',
             'html.boot-gate-active body>:not(#boot-gate-screen){visibility:hidden!important;pointer-events:none!important;}',
             'html.boot-gate-active #boot-gate-screen,html.boot-gate-active #boot-gate-screen *{visibility:visible!important;}'
             'html.boot-gate-active #boot-gate-screen,html.boot-gate-active #boot-gate-screen *{visibility:visible!important;}',
            '#boot-gate-screen{position:fixed!important;inset:0!important;z-index:2147483000!important;display:flex!important;align-items:center!important;justify-content:center!important;background:#080808!important;color:#d8d8d8!important;opacity:1;pointer-events:auto!important;}',
            '#boot-gate-screen .boot-gate-decoration-layer{position:absolute;inset:0;z-index:1;pointer-events:none;overflow:hidden;}',
            '#boot-gate-screen .boot-gate-panel{position:relative;z-index:2;}',
            '#boot-gate-screen .boot-gate-close{display:none;position:absolute;right:7px;top:6px;z-index:3;height:18px;min-width:18px;border:1px solid #000;background:#141414;color:#ddd;font-size:11px;line-height:16px;padding:0 5px;cursor:pointer;}',
            '#boot-gate-screen.is-preview{inset:auto!important;left:18px!important;top:18px!important;width:min(720px,calc(100vw - 380px))!important;height:360px!important;z-index:99990!important;overflow:hidden!important;border:1px solid #000!important;box-shadow:0 10px 28px rgba(0,0,0,.55)!important;pointer-events:none!important;}',
            '#boot-gate-screen.is-preview .boot-gate-panel,#boot-gate-screen.is-preview .boot-gate-close{pointer-events:auto!important;}',
            '#boot-gate-screen.is-preview .boot-gate-close{display:block;}'
         ].join('');
         ].join('');
         (document.head || document.documentElement).appendChild(style);
         (document.head || document.documentElement).appendChild(style);
     }
     }


     function activateBootSurface() {
     function activate() {
         injectEarlyBootStyle();
         if (disabled) return;
        injectStyle();
         if (document.documentElement) document.documentElement.classList.add('boot-gate-active');
         if (document.documentElement) document.documentElement.classList.add('boot-gate-active');
         if (document.body) document.body.classList.add('boot-gate-active');
         if (document.body) document.body.classList.add('boot-gate-active');
     }
     }


     if (!BOOT_EXCLUDED_PAGE) activateBootSurface();
     function makeNode() {
    else if (window.__BootGatePrelude && window.__BootGatePrelude.release) window.__BootGatePrelude.release();
        var node;
        var panel;
        var title;
        var status;
        var meter;
        var fill;
        var progress;
        var detail;
        var decoLayer;
        var close;
 
        if (disabled || !document.body) return null;
        activate();
 
        node = document.getElementById(SCREEN_ID);
        if (node) return node;
 
        node = document.createElement('div');
        node.id = SCREEN_ID;
        node.className = 'boot-gate-screen is-active';
        node.setAttribute('role', 'status');
        node.setAttribute('aria-live', 'polite');
        node.setAttribute('data-boot-gate-prelude', '1');
 
        panel = document.createElement('div');
        panel.className = 'boot-gate-panel';


    var defaultManifest = {
        title = document.createElement('div');
        version: '20260710-globe-vhs-restore-entry-001',
         title.className = 'boot-gate-title';
         boot: {
        title.textContent = 'ARCHIVE INITIALIZATION';
            minDisplayMs: 950,
            cachedMinDisplayMs: 350,
            maxBlockingMs: 15000
        },
        initial: {
            full: [
                {
                    id: 'decorations-registry',
                    label: 'DECORATION REGISTRY',
                    type: 'decorations',
                    ref: 'MediaWiki:Decorations.json',
                    page: '국가 및 조합',
                    era: '1950',
                    preparePixels: true
                },
                {
                    id: 'nations-1950-entry',
                    label: '1950 NATIONS ENTRY',
                    type: 'nations-era',
                    era: '1950',
                    level: 'full'
                }
            ],
            half: [
                {
                    id: 'nations-1960-half',
                    label: '1960 NATIONS HALF',
                    type: 'nations-era',
                    era: '1960',
                    level: 'half'
                }
            ]
        }
    };


    function now() {
        status = document.createElement('div');
         return Date.now ? Date.now() : new Date().getTime();
         status.className = 'boot-gate-status';
    }
        status.textContent = 'Preparing site entry systems';


        meter = document.createElement('div');
        meter.className = 'boot-gate-meter';
        fill = document.createElement('div');
        fill.className = 'boot-gate-meter-fill';
        meter.appendChild(fill);


    var BootPerf = window.BootPerf = window.BootPerf || (function () {
        progress = document.createElement('div');
        var t0 = now();
         progress.className = 'boot-gate-progress';
         var entries = [];
         progress.textContent = '0%';
         var active = {};
        var seq = 0;


         function cloneMeta(meta) {
         detail = document.createElement('div');
            var out = {};
        detail.className = 'boot-gate-detail';
            Object.keys(meta || {}).forEach(function (key) {
        detail.textContent = 'boot gate prelude';
                var value = meta[key];
                if (value == null) return;
                if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') out[key] = value;
                else {
                    try { out[key] = JSON.parse(JSON.stringify(value)); }
                    catch (err) { out[key] = String(value); }
                }
            });
            return out;
        }


         function start(name, meta) {
         close = document.createElement('button');
            var id = String(++seq);
        close.type = 'button';
            active[id] = { id: id, name: String(name || 'entry'), start: now(), meta: cloneMeta(meta) };
        close.className = 'boot-gate-close';
            return id;
        close.setAttribute('aria-label', 'Close boot preview');
        }
        close.textContent = '×';
        close.addEventListener('click', function () { release(node); });


         function end(id, meta) {
         decoLayer = document.createElement('div');
            var item = active[id];
        decoLayer.className = 'boot-gate-decoration-layer';
            var ended = now();
        decoLayer.setAttribute('data-decoration-target', 'boot-gate');
            if (!item) return null;
        decoLayer.setAttribute('aria-hidden', 'true');
            delete active[id];
 
            item.end = ended;
        panel.appendChild(title);
            item.ms = ended - item.start;
        panel.appendChild(status);
            item.offset = item.start - t0;
        panel.appendChild(meter);
            item.meta = Object.assign({}, item.meta || {}, cloneMeta(meta));
        panel.appendChild(progress);
            entries.push(item);
        panel.appendChild(detail);
            return item;
        node.appendChild(decoLayer);
         }
        node.appendChild(panel);
         node.appendChild(close);


         function instant(name, meta) {
         document.body.insertBefore(node, document.body.firstChild || null);
            var t = now();
         return node;
            entries.push({ id: String(++seq), name: String(name || 'mark'), start: t, end: t, ms: 0, offset: t - t0, meta: cloneMeta(meta) });
    }
         }


        function measure(name, meta, fn) {
    function onBody(callback) {
            var id = start(name, meta);
        if (document.body) {
            try {
            callback();
                return Promise.resolve(fn()).then(function (value) {
             return;
                    end(id, { ok: true });
                    return value;
                }, function (err) {
                    end(id, { ok: false, error: err && (err.message || String(err)) });
                    throw err;
                });
             } catch (err) {
                end(id, { ok: false, error: err && (err.message || String(err)) });
                return Promise.reject(err);
            }
         }
         }
 
         if (document.readyState === 'loading') {
         function rows() {
             document.addEventListener('DOMContentLoaded', callback, { once: true });
             return entries.slice().sort(function (a, b) { return a.start - b.start; }).map(function (item) {
                return {
                    offset: item.offset,
                    ms: item.ms,
                    name: item.name,
                    meta: item.meta || {}
                };
            });
         }
         }
        window.setTimeout(function tick() {
            if (document.body) return callback();
            window.setTimeout(tick, 10);
        }, 0);
    }


        function summary() {
    function release(node) {
            var list = rows();
        node = node || document.getElementById(SCREEN_ID);
            var total = list.reduce(function (max, item) { return Math.max(max, item.offset + item.ms); }, 0);
        if (node) {
             return {
            node.classList.add('is-complete');
                 build: BUILD_ID,
            node.classList.remove('is-active');
                startedAt: t0,
             window.setTimeout(function () {
                totalMs: total,
                 if (node.parentNode) node.parentNode.removeChild(node);
                entries: list,
             }, 240);
                active: Object.keys(active).map(function (id) { return active[id]; })
             };
         }
         }
        window.setTimeout(function () {
            if (document.documentElement) document.documentElement.classList.remove('boot-gate-active');
            if (document.body) document.body.classList.remove('boot-gate-active');
        }, 250);
    }


        function print() {
    activate();
            var list = rows();
    onBody(function () {
            if (!window.console || !console.log) return summary();
        activate();
            try {
        makeNode();
                console.groupCollapsed('[BootPerf] entry loading timeline · ' + BUILD_ID);
    });
                if (console.table) console.table(list.map(function (item) {
                    return {
                        offset: item.offset + 'ms',
                        duration: item.ms + 'ms',
                        name: item.name,
                        detail: JSON.stringify(item.meta || {})
                    };
                }));
                else list.forEach(function (item) { console.log(item.offset + 'ms', item.ms + 'ms', item.name, item.meta || {}); });
                console.groupEnd();
            } catch (err) {}
            return summary();
        }


        return {
    window.__BootGatePrelude = {
            start: start,
        startTime: START_TIME,
            end: end,
        activate: activate,
            mark: instant,
        ensure: makeNode,
            measure: measure,
        release: release,
            rows: rows,
        node: function () { return document.getElementById(SCREEN_ID); },
            summary: summary,
        disabled: disabled
            print: print
    };
        };
})(window, document);
    }());


    function toArray(value) {
/* =========================================
        return Array.prototype.slice.call(value || []);
  Site boot gate and entry artifact contract
    }
  =========================================
  This is the initial-load full/half entry artifact system.


    function unique(list) {
  Purpose:
        var seen = {};
  - The loading screen is not decorative. It exists only during the first site entry in a
        var out = [];
    tab, before the user is allowed into the normal wiki surface.
        (list || []).forEach(function (item) {
  - A "full" entry must mean that the first view of that system can appear without an
            item = String(item || '').trim();
    additional visible data load. For the nations system, the 1950 entry is full only when
            if (!item || seen[item]) return;
    its nation list/link-map data and first-view pixel decorations are ready in this tab.
            seen[item] = true;
  - A "half" entry is a predictive warm state for the next likely path. It may fetch and
            out.push(item);
    parse data, but may skip expensive final work such as image/canvas preparation until it
        });
    is promoted to full.
        return out;
  - This principle is a site-wide design priority, like SPA continuity. New viewers,
     }
    document systems, and information panels should define their entry full/half packs
    before exposing a first screen that can visibly fill in later.
  - SPA navigation is a consumer phase, not a blocking phase.  Do not add BootGate holds
    to SPA route changes.  If a route needs seamless first paint, prepare its artifacts
    during the initial boot pack and have the subsystem consume EntryStore synchronously
    before inserting or painting visible DOM.
 
  Naming rule:
  - New public APIs, globals, classes, functions, files, and components must not use a
    project prefix. Old prefixed globals are legacy compatibility surfaces only.
  - New code should use names such as BootGate, EntryLoader, EntryStore, and boot-gate-*.
*/
(function (window, document, mw) {
    'use strict';
 
    var MANIFEST_TITLE = 'MediaWiki:EntryManifest.json';
    var BUILD_ID = '20260711-existing-account-login-001';
    var deferredEntryWarmups = [];
    var READY_KEY = 'boot-gate-ready-version';
    var DISMISS_PARAM = 'bootGate';
    var bootStarted = false;
    var bootPromise = null;
    var bootNode = null;
    var bootStatusNode = null;
    var bootProgressNode = null;
    var bootDetailNode = null;
    var bootFillNode = null;
    var bootStartTime = 0;
    var earlyBootStyleInjected = false;
    var loginGateLocked = false;
     var loginGateActionNode = null;


     function hasBootParam(value) {
     function hasQueryFlag(name, value) {
         var search = String(window.location && window.location.search || '');
         var search = String(window.location && window.location.search || '');
         var re = new RegExp('[?&]' + DISMISS_PARAM + '=([^&]+)');
         var re = new RegExp('[?&]' + name + '=([^&]+)');
         var match = search.match(re);
         var match = search.match(re);
         return match && decodeURIComponent(match[1]) === value;
         return !!(match && decodeURIComponent(match[1]) === value);
     }
     }


     function normalizeTitle(value) {
     function readConfig(name, fallback) {
         return String(value || '')
         try {
             .split('#')[0]
             if (mw && mw.config && typeof mw.config.get === 'function') {
            .replace(/_/g, ' ')
                var value = mw.config.get(name);
             .trim();
                return value == null ? fallback : value;
             }
        } catch (err) {}
        return fallback;
     }
     }


     function extractTitleFromUrl(value) {
     function normalizeBootPageName(value) {
         var text = String(value || '');
         return String(value || '').split('?')[0].replace(/^\/index\.php\//, '').replace(/_/g, ' ').trim();
        var match = text.match(/[?&]title=([^&]+)/i);
        if (match) return normalizeTitle(decodeURIComponent(match[1].replace(/\+/g, ' ')));
        return '';
     }
     }


     function normalizeRefKey(ref) {
     function isCreateAccountPage() {
         var text = String(ref || '').trim();
         var canonical = String(readConfig('wgCanonicalSpecialPageName', '') || '').toLowerCase();
         var title;
         var name = normalizeBootPageName(readConfig('wgPageName', '') || window.location.pathname || '').toLowerCase();
        if (!text) return '';
         return canonical === 'createaccount' || /^(?:special|특수):(?:createaccount|계정 ?(?:만들기|생성))/i.test(name);
        title = extractTitleFromUrl(text);
        if (title) return 'title:' + title.toLowerCase();
         if (text.indexOf('/') === -1 && text.indexOf(':') !== -1) return 'title:' + normalizeTitle(text).toLowerCase();
        return 'url:' + text;
     }
     }


     function rawUrlForRef(ref, ctype) {
     function isAnonymousUser() {
         var text = String(ref || '').trim();
         var userName = readConfig('wgUserName', null);
         var title;
         var userId = Number(readConfig('wgUserId', 0) || 0);
        if (!text) return '';
         return !userName && !userId;
        if (/^(?:https?:)?\/\//i.test(text) || text.charAt(0) === '/') return text;
        title = normalizeTitle(text.indexOf(':') !== -1 ? text : ('MediaWiki:' + text));
        if (mw && mw.util && typeof mw.util.getUrl === 'function') {
            return mw.util.getUrl(title, { action: 'raw', ctype: ctype || 'application/json' });
        }
         return '/index.php?title=' + encodeURIComponent(title) + '&action=raw&ctype=' + encodeURIComponent(ctype || 'application/json');
     }
     }


     function getApiEndpoint() {
     function isAuthenticationPage() {
         return (mw && mw.util && typeof mw.util.wikiScript === 'function') ? mw.util.wikiScript('api') : '/api.php';
         var canonical = String(readConfig('wgCanonicalSpecialPageName', '') || '').toLowerCase();
        var name = normalizeBootPageName(readConfig('wgPageName', '') || window.location.pathname || '').toLowerCase();
        var allowed = {
            userlogin: true,
            passwordreset: true,
            resetpass: true,
            confirmemail: true
        };
 
        if (allowed[canonical]) return true;
        return /^(?:special|특수):(?:userlogin|로그인|passwordreset|비밀번호 ?재설정|resetpass|confirmemail)/i.test(name);
     }
     }


     function fetchApi(params) {
     function requiresLoginGate() {
        var body = new URLSearchParams();
         return isAnonymousUser() && !isAuthenticationPage();
        Object.keys(params || {}).forEach(function (key) {
            body.append(key, params[key]);
        });
         return fetch(getApiEndpoint(), {
            method: 'POST',
            credentials: 'same-origin',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
            body: body.toString()
        }).then(function (res) {
            if (!res.ok) throw new Error('HTTP ' + res.status);
            return res.json();
        });
     }
     }


    function isBootExcludedPage() {
        var ns = Number(readConfig('wgNamespaceNumber', NaN));
        var action = String(readConfig('wgAction', 'view') || 'view').toLowerCase();
        var model = String(readConfig('wgPageContentModel', '') || '').toLowerCase();
        var name = normalizeBootPageName(readConfig('wgPageName', '') || window.location.pathname || '');
        var systemNamespaces = {
            '-1': true, '4': true, '5': true, '6': true, '7': true, '8': true, '9': true,
            '10': true, '11': true, '12': true, '13': true, '14': true, '15': true,
            '828': true, '829': true
        };


    /* =========================================
        /*
      Revision manifest and persistent entry cache
        * The public boot gate is for normal reading surfacesDeveloper/system
      =========================================
        * namespaces and edit/diff/history actions already reload outside SPA, so
      The first boot still prepares current-tab artifacts, but freshness is not guessed from
        * blocking them would turn every maintenance save into another entry boot.
      filenames or old localStorage flagsThe client reads a tiny server-side current-state
        */
      manifest, compares page revisions / file sha1 values, and only keeps cached raw resources
        if (hasQueryFlag('bootGatePreview', '1')) return false;
      whose revision token still matches the server. The manifest is a latest-state table, not
        if (action && action !== 'view') return true;
      an append-only client log.
        if (systemNamespaces[String(ns)]) return true;
    */
        if (model === 'css' || model === 'javascript' || model === 'json' || model === 'sanitized-css') return true;
    var REVISION_MANIFEST_ACTION = 'entryrevisionmanifest';
        if (/\.(?:css|js|json)$/i.test(name)) return true;
    var REVISION_MANIFEST_LOCAL_KEY = 'entry-revision-manifest-current-v1';
        if (/^(?:mediawiki|미디어위키|file|파일|project|프로젝트|template|틀|module|모듈|category|분류|special|특수):/i.test(name)) return true;
    var REVISION_MANIFEST_PRUNE_LOCAL_KEY = 'entry-revision-manifest-last-client-prune-v1';
        return false;
    var ENTRY_CACHE_NAME = 'entry-cache-v1';
     }
    var ENTRY_CACHE_INDEX_KEY = 'entry-cache-index-v1';
    var ENTRY_CACHE_REQUEST_PREFIX = '/__entry-cache__/';
     var ENTRY_CACHE_PACK_KEY = 'entry-cache-pack-state-v1';


     function hasCacheStorage() {
     var LOGIN_REQUIRED = requiresLoginGate();
        return !!(window.caches && typeof window.caches.open === 'function');
    var BOOT_EXCLUDED_PAGE = isBootExcludedPage() && !LOGIN_REQUIRED;
    }


     function safeJsonParse(text, fallback) {
     function injectEarlyBootStyle() {
         try { return JSON.parse(text); } catch (err) { return fallback; }
         var style;
        if (earlyBootStyleInjected || !document.documentElement) return;
        earlyBootStyleInjected = true;
        style = document.createElement('style');
        style.id = 'boot-gate-early-style';
        style.textContent = [
            'html.boot-gate-active, body.boot-gate-active{overflow:hidden!important;}',
            'html.boot-gate-active body{background:#080808!important;}',
            'html.boot-gate-active body> :not(#boot-gate-screen){visibility:hidden!important;pointer-events:none!important;}',
            'html.boot-gate-active #boot-gate-screen,html.boot-gate-active #boot-gate-screen *{visibility:visible!important;}'
        ].join('');
        (document.head || document.documentElement).appendChild(style);
     }
     }


     function readLocalJson(key, fallback) {
     function activateBootSurface() {
         try {
         injectEarlyBootStyle();
            var text = window.localStorage ? window.localStorage.getItem(key) : null;
        if (document.documentElement) document.documentElement.classList.add('boot-gate-active');
            return text ? safeJsonParse(text, fallback) : fallback;
        if (document.body) document.body.classList.add('boot-gate-active');
        } catch (err) {
            return fallback;
        }
     }
     }


     function writeLocalJson(key, value) {
     if (!BOOT_EXCLUDED_PAGE) activateBootSurface();
        try {
    else if (window.__BootGatePrelude && window.__BootGatePrelude.release) window.__BootGatePrelude.release();
            if (window.localStorage) window.localStorage.setItem(key, JSON.stringify(value));
        } catch (err) {}
    }


     function normalizeManifestTitle(value) {
     var defaultManifest = {
        var text = String(value || '').trim();
         version: '20260710-globe-vhs-restore-entry-001',
         var match;
         boot: {
        var i;
             minDisplayMs: 950,
        if (!text) return '';
            cachedMinDisplayMs: 350,
         for (i = 0; i < 3; i += 1) {
             maxBlockingMs: 15000
             try {
         },
                if (/%[0-9a-f]{2}/i.test(text)) text = decodeURIComponent(text);
         initial: {
             } catch (err) { break; }
            full: [
         }
                {
         match = text.match(/[?&]title=([^&#]+)/i);
                    id: 'decorations-registry',
        if (match) text = match[1];
                    label: 'DECORATION REGISTRY',
        text = text.replace(/^https?:\/\/[^/]+/i, '')
                    type: 'decorations',
            .replace(/^\/+/, '')
                    ref: 'MediaWiki:Decorations.json',
            .replace(/^index\.php\/?/i, '')
                    page: '시대',
            .replace(/^wiki\/?/i, '')
                    era: '1950',
            .trim();
                    preparePixels: true
        match = text.match(/(?:^|\/)(?:(?:Special|특수)\s*[:/]\s*)?(?:Redirect|넘겨주기)\s*\/\s*file\s*\/([^?#]+)(?:[?#].*)?$/i);
                },
        if (match) text = 'File:' + match[1];
                {
        text = text.split('#')[0].replace(/_/g, ' ').replace(/\s+/g, ' ').trim();
                    id: 'nations-1950-entry',
        text = text.replace(/^(?:파일|Image|이미지)\s*:/i, 'File:');
                    label: '1950 ERA ENTRY',
        if (/^(?:mediawiki|template|module|manage|file)\s*:/i.test(text)) {
                    type: 'nations-era',
             text = text.replace(/^([^:]+)\s*:\s*/, function (_, ns) { return ns.charAt(0).toUpperCase() + ns.slice(1).toLowerCase() + ':'; });
                    era: '1950',
                    level: 'full'
                }
            ],
            half: [
                {
                    id: 'nations-1960-half',
                    label: '1960 ERA HALF',
                    type: 'nations-era',
                    era: '1960',
                    level: 'half'
                }
             ]
         }
         }
        if (/^File:/i.test(text)) text = 'File:' + text.slice(text.indexOf(':') + 1).trim();
     };
        if (/^Mediawiki:/i.test(text)) text = 'MediaWiki:' + text.slice(text.indexOf(':') + 1).trim();
        return text;
     }


     function resourceToken(resource) {
     function now() {
         if (!resource || typeof resource !== 'object') return '';
         return Date.now ? Date.now() : new Date().getTime();
        return String(resource.revision || resource.sha1 || resource.hash || resource.timestamp || resource.updatedAt || resource.url || '').trim();
     }
     }


    function createEntryCache() {
        var index = readLocalJson(ENTRY_CACHE_INDEX_KEY, { entries: {} }) || { entries: {} };
        var packs = readLocalJson(ENTRY_CACHE_PACK_KEY, { packs: {} }) || { packs: {} };
        var objectUrls = {};
        var stats = {
            textHits: 0,
            blobHits: 0,
            misses: 0,
            networkStores: 0,
            stores: 0,
            deletes: 0
        };


        function ensureIndex() {
    var BootPerf = window.BootPerf = window.BootPerf || (function () {
            if (!index || typeof index !== 'object') index = { entries: {} };
        var t0 = now();
            if (!index.entries || typeof index.entries !== 'object') index.entries = {};
        var entries = [];
         }
        var active = {};
         var seq = 0;


         function compactIndexForLocalStorage() {
         function cloneMeta(meta) {
             var entries;
             var out = {};
            var next = {};
             Object.keys(meta || {}).forEach(function (key) {
             ensureIndex();
                 var value = meta[key];
            entries = index.entries || {};
                 if (value == null) return;
            Object.keys(entries).forEach(function (key) {
                 if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') out[key] = value;
                 var entry = entries[key] || {};
                 else {
                 var kind = String(entry.kind || 'raw').toLowerCase();
                    try { out[key] = JSON.parse(JSON.stringify(value)); }
                /*
                    catch (err) { out[key] = String(value); }
                * CacheStorage already owns image/blob bodies.  Keeping one localStorage
                }
                * metadata row per flag/blob competes with MediaWiki ResourceLoader's own
                * localStorage module store and can trigger QuotaExceededError before our
                * code even runs on the next page load.  Text/json/file URL rows stay indexed
                * because they are small and useful for invalidation diagnostics.
                */
                 if (kind === 'image' || kind === 'blob') return;
                 next[key] = entry;
             });
             });
             index.entries = next;
             return out;
         }
         }


         function ensurePacks() {
         function start(name, meta) {
             if (!packs || typeof packs !== 'object') packs = { packs: {} };
             var id = String(++seq);
            if (!packs.packs || typeof packs.packs !== 'object') packs.packs = {};
            active[id] = { id: id, name: String(name || 'entry'), start: now(), meta: cloneMeta(meta) };
            return id;
         }
         }


         function saveIndex() {
         function end(id, meta) {
             ensureIndex();
             var item = active[id];
             compactIndexForLocalStorage();
            var ended = now();
             writeLocalJson(ENTRY_CACHE_INDEX_KEY, index);
             if (!item) return null;
            delete active[id];
             item.end = ended;
            item.ms = ended - item.start;
            item.offset = item.start - t0;
            item.meta = Object.assign({}, item.meta || {}, cloneMeta(meta));
            entries.push(item);
            return item;
         }
         }


         function savePacks() {
         function instant(name, meta) {
             ensurePacks();
             var t = now();
             writeLocalJson(ENTRY_CACHE_PACK_KEY, packs);
             entries.push({ id: String(++seq), name: String(name || 'mark'), start: t, end: t, ms: 0, offset: t - t0, meta: cloneMeta(meta) });
         }
         }


         function requestForKey(key) {
         function measure(name, meta, fn) {
             return new Request(ENTRY_CACHE_REQUEST_PREFIX + encodeURIComponent(String(key || '')), { credentials: 'same-origin' });
             var id = start(name, meta);
        }
            try {
 
                return Promise.resolve(fn()).then(function (value) {
        function openCache() {
                    end(id, { ok: true });
            if (!hasCacheStorage()) return Promise.resolve(null);
                    return value;
             return window.caches.open(ENTRY_CACHE_NAME).catch(function () { return null; });
                }, function (err) {
                    end(id, { ok: false, error: err && (err.message || String(err)) });
                    throw err;
                });
             } catch (err) {
                end(id, { ok: false, error: err && (err.message || String(err)) });
                return Promise.reject(err);
            }
         }
         }


         function cacheEntry(key, meta) {
         function rows() {
             key = String(key || '');
             return entries.slice().sort(function (a, b) { return a.start - b.start; }).map(function (item) {
            ensureIndex();
                 return {
            index.entries[key] = Object.assign({}, index.entries[key] || {}, {
                    offset: item.offset,
                 key: key,
                    ms: item.ms,
                resourceKey: String(meta && meta.resourceKey || ''),
                    name: item.name,
                token: String(meta && meta.token || ''),
                    meta: item.meta || {}
                kind: String(meta && meta.kind || 'raw'),
                 };
                contentType: String(meta && meta.contentType || ''),
                size: Number(meta && meta.size || 0) || null,
                 createdAt: index.entries[key] && index.entries[key].createdAt ? index.entries[key].createdAt : now(),
                updatedAt: now(),
                lastHitAt: index.entries[key] && index.entries[key].lastHitAt ? index.entries[key].lastHitAt : null,
                hits: Number(index.entries[key] && index.entries[key].hits || 0)
             });
             });
            saveIndex();
         }
         }


         function markHit(key, field) {
         function summary() {
             key = String(key || '');
             var list = rows();
             ensureIndex();
             var total = list.reduce(function (max, item) { return Math.max(max, item.offset + item.ms); }, 0);
            if (index.entries[key]) {
            return {
                index.entries[key].hits = Number(index.entries[key].hits || 0) + 1;
                build: BUILD_ID,
                 index.entries[key].lastHitAt = now();
                startedAt: t0,
                saveIndex();
                totalMs: total,
             }
                 entries: list,
            if (field && stats[field] != null) stats[field] += 1;
                active: Object.keys(active).map(function (id) { return active[id]; })
             };
         }
         }


         function getResponse(key) {
         function print() {
             key = String(key || '');
             var list = rows();
             if (!key || !hasCacheStorage()) return Promise.resolve(null);
             if (!window.console || !console.log) return summary();
             return openCache().then(function (cache) {
             try {
                 if (!cache) return null;
                console.groupCollapsed('[BootPerf] entry loading timeline · ' + BUILD_ID);
                return cache.match(requestForKey(key)).then(function (res) {
                 if (console.table) console.table(list.map(function (item) {
                     if (!res) {
                     return {
                         stats.misses += 1;
                         offset: item.offset + 'ms',
                         return null;
                        duration: item.ms + 'ms',
                    }
                         name: item.name,
                     return res;
                        detail: JSON.stringify(item.meta || {})
                 });
                     };
            }).catch(function () { return null; });
                 }));
                else list.forEach(function (item) { console.log(item.offset + 'ms', item.ms + 'ms', item.name, item.meta || {}); });
                console.groupEnd();
            } catch (err) {}
            return summary();
         }
         }


         function putResponse(key, response, meta) {
         return {
             key = String(key || '');
             start: start,
             if (!key || !response || !hasCacheStorage()) return Promise.resolve(false);
             end: end,
             meta = meta || {};
             mark: instant,
             return openCache().then(function (cache) {
             measure: measure,
                var cloned;
            rows: rows,
                var headers;
            summary: summary,
                var bodyPromise;
            print: print
                if (!cache) return false;
        };
                cloned = response.clone();
    }());
                bodyPromise = cloned.blob().catch(function () { return null; });
 
                return bodyPromise.then(function (blob) {
 
                    if (!blob) return false;
    var InteractionPerf = window.InteractionPerf = window.InteractionPerf || (function () {
                    headers = new Headers(response.headers || {});
        var BUILD = '20260710-interaction-perf-instrument-001';
                    if (!headers.get('Content-Type')) headers.set('Content-Type', meta.contentType || blob.type || 'application/octet-stream');
        var t0 = (window.performance && performance.now ? performance.now() : now());
                    headers.set('X-Entry-Cache-Key', key);
        var entries = [];
                    headers.set('X-Entry-Resource-Key', String(meta.resourceKey || ''));
        var active = {};
                    headers.set('X-Entry-Revision-Token', String(meta.token || ''));
        var seq = 0;
                    headers.set('X-Entry-Cached-At', String(now()));
        var maxEntries = 1600;
                    return cache.put(requestForKey(key), new Response(blob, { status: 200, headers: headers })).then(function () {
                        stats.stores += 1;
                        cacheEntry(key, {
                            resourceKey: meta.resourceKey,
                            token: meta.token,
                            kind: meta.kind || 'blob',
                            contentType: headers.get('Content-Type') || blob.type || '',
                            size: blob.size
                        });
                        return true;
                    });
                });
            }).catch(function () { return false; });
        }


         function getText(key) {
         function perfNow() {
             return getResponse(key).then(function (res) {
             return window.performance && performance.now ? performance.now() : now();
                if (!res) return null;
                markHit(key, 'textHits');
                return res.text();
            }).catch(function () { return null; });
         }
         }


         function putText(key, text, meta) {
         function cloneMeta(meta) {
             key = String(key || '');
             var out = {};
             if (!key || !hasCacheStorage()) return Promise.resolve(false);
             Object.keys(meta || {}).forEach(function (key) {
            meta = meta || {};
                 var value = meta[key];
            return openCache().then(function (cache) {
                 if (value == null) return;
                 var headers;
                 if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') out[key] = value;
                var body = String(text || '');
                else {
                 if (!cache) return false;
                     try { out[key] = JSON.parse(JSON.stringify(value)); }
                 headers = new Headers({
                     catch (err) { out[key] = String(value); }
                    'Content-Type': meta.contentType || 'text/plain; charset=UTF-8',
                 }
                    'X-Entry-Cache-Key': key,
            });
                    'X-Entry-Resource-Key': String(meta.resourceKey || ''),
            return out;
                     'X-Entry-Revision-Token': String(meta.token || ''),
        }
                     'X-Entry-Cached-At': String(now())
 
                 });
        function push(entry) {
                return cache.put(requestForKey(key), new Response(body, { status: 200, headers: headers })).then(function () {
            entries.push(entry);
                    stats.stores += 1;
            if (entries.length > maxEntries) entries.splice(0, entries.length - maxEntries);
                    cacheEntry(key, {
             return entry;
                        resourceKey: meta.resourceKey,
                        token: meta.token,
                        kind: meta.kind || 'text',
                        contentType: headers.get('Content-Type'),
                        size: body.length
                    });
                    return true;
                });
             }).catch(function () { return false; });
         }
         }


         function getBlobUrl(key) {
         function start(name, meta) {
             key = String(key || '');
             var id = String(++seq);
            if (!key) return Promise.resolve('');
             active[id] = { id: id, name: String(name || 'interaction'), start: perfNow(), meta: cloneMeta(meta) };
             if (objectUrls[key]) {
             return id;
                markHit(key, 'blobHits');
                return Promise.resolve(objectUrls[key]);
            }
            return getResponse(key).then(function (res) {
                if (!res) return '';
                return res.blob().then(function (blob) {
                    if (!blob || !blob.size) return '';
                    objectUrls[key] = URL.createObjectURL(blob);
                    markHit(key, 'blobHits');
                    return objectUrls[key];
                });
             }).catch(function () { return ''; });
         }
         }


         function fetchBlobUrl(url, key, meta, options) {
         function end(id, meta) {
             url = String(url || '').trim();
             var item = active[id];
             key = String(key || '').trim();
             var ended = perfNow();
             if (!url || !key) return Promise.resolve('');
             if (!item) return null;
             return getBlobUrl(key).then(function (cachedUrl) {
            delete active[id];
                if (cachedUrl) return cachedUrl;
            item.end = ended;
                return fetch(url, {
             item.ms = Math.round((ended - item.start) * 100) / 100;
                    credentials: 'same-origin',
            item.offset = Math.round((item.start - t0) * 100) / 100;
                    cache: options && options.noStore ? 'no-store' : 'force-cache'
            item.meta = Object.assign({}, item.meta || {}, cloneMeta(meta));
                }).then(function (res) {
            return push(item);
                    if (!res.ok) throw new Error('HTTP ' + res.status);
        }
                    stats.networkStores += 1;
 
                    return putResponse(key, res, Object.assign({}, meta || {}, { kind: meta && meta.kind ? meta.kind : 'blob' })).then(function () {
        function mark(name, meta) {
                        return getBlobUrl(key);
            var t = perfNow();
                    });
            return push({ id: String(++seq), name: String(name || 'mark'), start: t, end: t, ms: 0, offset: Math.round((t - t0) * 100) / 100, meta: cloneMeta(meta) });
                }).catch(function () {
                    return '';
                });
            });
         }
         }


         function deleteKey(key) {
         function measureSync(name, meta, fn) {
             key = String(key || '');
             var id = start(name, meta);
             if (!key || !hasCacheStorage()) return Promise.resolve(false);
             try {
             if (objectUrls[key]) {
                var value = fn();
                 try { URL.revokeObjectURL(objectUrls[key]); } catch (err) {}
                end(id, { ok: true });
                 delete objectUrls[key];
                return value;
             } catch (err) {
                 end(id, { ok: false, error: err && (err.message || String(err)) || String(err) });
                 throw err;
             }
             }
            return openCache().then(function (cache) {
                if (!cache) return false;
                return cache.delete(requestForKey(key)).then(function (ok) {
                    ensureIndex();
                    if (index.entries && index.entries[key]) {
                        delete index.entries[key];
                        stats.deletes += 1;
                        saveIndex();
                    }
                    return ok;
                });
            }).catch(function () { return false; });
         }
         }


         function invalidateResources(resourceKeys) {
         function measureAsync(name, meta, fn) {
             var map = {};
             var id = start(name, meta);
            var entries;
             try {
            var keys = [];
                return Promise.resolve(fn()).then(function (value) {
            ensureIndex();
                    end(id, { ok: true });
             entries = index.entries || {};
                    return value;
            (resourceKeys || []).forEach(function (resourceKey) {
                 }, function (err) {
                 resourceKey = String(resourceKey || '').toLowerCase();
                    end(id, { ok: false, error: err && (err.message || String(err)) || String(err) });
                if (resourceKey) map[resourceKey] = true;
                    throw err;
            });
                });
             Object.keys(entries).forEach(function (cacheKey) {
             } catch (err) {
                 var resourceKey = String(entries[cacheKey] && entries[cacheKey].resourceKey || '').toLowerCase();
                 end(id, { ok: false, error: err && (err.message || String(err)) || String(err) });
                if (map[resourceKey]) keys.push(cacheKey);
                return Promise.reject(err);
            });
            }
            return Promise.all(keys.map(deleteKey)).then(function () { return keys.length; });
         }
         }


         function prune(maxAgeDays) {
         function summary() {
             var days = Math.max(1, Number(maxAgeDays) || 7);
             return {
            var cutoff = now() - days * 24 * 60 * 60 * 1000;
                build: BUILD,
            var entries;
                startedAt: t0,
            var keys;
                totalMs: Math.round((perfNow() - t0) * 100) / 100,
            ensureIndex();
                entries: entries.slice().sort(function (a, b) {
            entries = index.entries || {};
                    if (a.offset !== b.offset) return a.offset - b.offset;
            keys = Object.keys(entries).filter(function (key) {
                    return b.ms - a.ms;
                return Number(entries[key] && entries[key].createdAt || 0) < cutoff;
                }),
            });
                active: Object.keys(active).map(function (id) {
            window.localStorage && window.localStorage.setItem(REVISION_MANIFEST_PRUNE_LOCAL_KEY, String(now()));
                    var item = active[id];
            return Promise.all(keys.map(deleteKey)).then(function () { return keys.length; });
                    return { offset: Math.round((item.start - t0) * 100) / 100, ms: Math.round((perfNow() - item.start) * 100) / 100, name: item.name, meta: item.meta || {} };
                })
            };
         }
         }


         function reset() {
         function table() {
             Object.keys(objectUrls).forEach(function (key) {
             var data = summary().entries.map(function (entry) {
                 try { URL.revokeObjectURL(objectUrls[key]); } catch (err) {}
                 return { offset: entry.offset, ms: entry.ms, name: entry.name, meta: entry.meta };
             });
             });
            objectUrls = {};
             if (window.console && console.table) console.table(data);
            index = { entries: {} };
             return data;
            packs = { packs: {} };
            saveIndex();
            savePacks();
             if (!hasCacheStorage()) return Promise.resolve(false);
             return window.caches.delete(ENTRY_CACHE_NAME).catch(function () { return false; });
         }
         }


         function packReady(key, token) {
         try {
            key = String(key || '');
            if (window.PerformanceObserver && !window.CLBI_InteractionLongTaskObserverBound) {
            token = String(token || '');
                window.CLBI_InteractionLongTaskObserverBound = true;
            ensurePacks();
                new PerformanceObserver(function (list) {
            if (!key || !token) return false;
                    list.getEntries().forEach(function (entry) {
            return !!(packs.packs[key] && String(packs.packs[key].token || '') === token && packs.packs[key].ready);
                        mark('browser long task', {
         }
                            ms: Math.round(entry.duration * 100) / 100,
                            start: Math.round(entry.startTime * 100) / 100,
                            attribution: entry.attribution && entry.attribution.length ? entry.attribution.length : 0
                        });
                    });
                }).observe({ entryTypes: ['longtask'] });
            }
         } catch (ignoreLongTaskObserver) {}


         function setPackReady(key, token, meta) {
         return {
             key = String(key || '');
             build: BUILD,
             token = String(token || '');
             start: start,
             if (!key || !token) return false;
             end: end,
             ensurePacks();
             mark: mark,
             packs.packs[key] = Object.assign({}, meta || {}, {
             measureSync: measureSync,
                key: key,
            measureAsync: measureAsync,
                token: token,
            summary: summary,
                ready: true,
            table: table
                updatedAt: now()
        };
            });
    }());
            savePacks();
            return true;
        }


        function packInfo() {
    function toArray(value) {
            ensurePacks();
        return Array.prototype.slice.call(value || []);
            return Object.assign({}, packs.packs || {});
    }
        }


        function info() {
    function unique(list) {
            var lastClientPrune = 0;
        var seen = {};
            var entries;
        var out = [];
            var byKind = {};
        (list || []).forEach(function (item) {
            try { lastClientPrune = Number(window.localStorage && window.localStorage.getItem(REVISION_MANIFEST_PRUNE_LOCAL_KEY) || 0); } catch (err) {}
            item = String(item || '').trim();
            ensureIndex();
            if (!item || seen[item]) return;
            ensurePacks();
             seen[item] = true;
            entries = index.entries || {};
             out.push(item);
            Object.keys(entries).forEach(function (key) {
        });
                var kind = String(entries[key] && entries[key].kind || 'raw');
        return out;
                byKind[kind] = (byKind[kind] || 0) + 1;
    }
             });
             return {
                supported: hasCacheStorage(),
                name: ENTRY_CACHE_NAME,
                entries: Object.keys(entries).length,
                byKind: byKind,
                packs: Object.keys(packs.packs || {}).length,
                lastClientPruneAt: lastClientPrune || null,
                stats: Object.assign({}, stats)
            };
        }


         /* Trim legacy image/blob metadata rows produced by older builds. */
    function hasBootParam(value) {
         try { saveIndex(); } catch (err) {}
         var search = String(window.location && window.location.search || '');
         var re = new RegExp('[?&]' + DISMISS_PARAM + '=([^&]+)');
        var match = search.match(re);
        return match && decodeURIComponent(match[1]) === value;
    }


         return {
    function normalizeTitle(value) {
            getResponse: getResponse,
         return String(value || '')
            putResponse: putResponse,
             .split('#')[0]
            getText: getText,
             .replace(/_/g, ' ')
            putText: putText,
             .trim();
            getBlobUrl: getBlobUrl,
            fetchBlobUrl: fetchBlobUrl,
            invalidateResources: invalidateResources,
            prune: prune,
             reset: reset,
             packReady: packReady,
             setPackReady: setPackReady,
            packInfo: packInfo,
            info: info
        };
     }
     }


     window.EntryCache = window.EntryCache || createEntryCache();
     function extractTitleFromUrl(value) {
        var text = String(value || '');
        var match = text.match(/[?&]title=([^&]+)/i);
        if (match) return normalizeTitle(decodeURIComponent(match[1].replace(/\+/g, ' ')));
        return '';
    }


     function createRevisionManifestService() {
     function normalizeRefKey(ref) {
         var current = null;
         var text = String(ref || '').trim();
         var previous = readLocalJson(REVISION_MANIFEST_LOCAL_KEY, null);
         var title;
         var loadPromise = null;
        if (!text) return '';
         var changedResources = [];
        title = extractTitleFromUrl(text);
         if (title) return 'title:' + title.toLowerCase();
        if (text.indexOf('/') === -1 && text.indexOf(':') !== -1) return 'title:' + normalizeTitle(text).toLowerCase();
         return 'url:' + text;
    }


        function unwrap(payload) {
    function rawUrlForRef(ref, ctype) {
            return payload && (payload.entryrevisionmanifest || payload.revisionManifest || payload) || null;
        var text = String(ref || '').trim();
        var title;
        if (!text) return '';
        if (/^(?:https?:)?\/\//i.test(text) || text.charAt(0) === '/') return text;
        title = normalizeTitle(text.indexOf(':') !== -1 ? text : ('MediaWiki:' + text));
        if (mw && mw.util && typeof mw.util.getUrl === 'function') {
            return mw.util.getUrl(title, { action: 'raw', ctype: ctype || 'application/json' });
         }
         }
        return '/index.php?title=' + encodeURIComponent(title) + '&action=raw&ctype=' + encodeURIComponent(ctype || 'application/json');
    }


        function resourcesOf(manifest) {
    function getApiEndpoint() {
            return manifest && manifest.resources && typeof manifest.resources === 'object' ? manifest.resources : {};
        return (mw && mw.util && typeof mw.util.wikiScript === 'function') ? mw.util.wikiScript('api') : '/api.php';
         }
    }
 
    function fetchApi(params) {
        var body = new URLSearchParams();
        Object.keys(params || {}).forEach(function (key) {
            body.append(key, params[key]);
        });
        return fetch(getApiEndpoint(), {
            method: 'POST',
            credentials: 'same-origin',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
            body: body.toString()
        }).then(function (res) {
            if (!res.ok) throw new Error('HTTP ' + res.status);
            return res.json();
         });
    }


        function compactRevisionManifest(manifest) {
            var out;
            var resources;
            if (!manifest || typeof manifest !== 'object') return null;
            out = {
                manifestVersion: manifest.manifestVersion || manifest.version || '',
                version: manifest.version || manifest.manifestVersion || '',
                generatedAt: manifest.generatedAt || '',
                pruneDays: manifest.pruneDays,
                clientPruneDays: manifest.clientPruneDays,
                resources: {}
            };
            resources = resourcesOf(manifest);
            Object.keys(resources).forEach(function (title) {
                var src = resources[title];
                var dst;
                if (!src || typeof src !== 'object') return;
                dst = {};
                ['revision', 'sha1', 'hash', 'timestamp', 'updatedAt', 'url'].forEach(function (key) {
                    if (src[key] !== undefined && src[key] !== null && String(src[key]) !== '') dst[key] = src[key];
                });
                out.resources[title] = dst;
            });
            return out;
        }


        function buildLookup(manifest) {
    /* =========================================
            var lookup = {};
      Revision manifest and persistent entry cache
            Object.keys(resourcesOf(manifest)).forEach(function (title) {
      =========================================
                lookup[normalizeManifestTitle(title).toLowerCase()] = resourcesOf(manifest)[title];
      The first boot still prepares current-tab artifacts, but freshness is not guessed from
            });
      filenames or old localStorage flags.  The client reads a tiny server-side current-state
             return lookup;
      manifest, compares page revisions / file sha1 values, and only keeps cached raw resources
      whose revision token still matches the server.  The manifest is a latest-state table, not
      an append-only client log.
    */
    var REVISION_MANIFEST_ACTION = 'entryrevisionmanifest';
    var REVISION_MANIFEST_LOCAL_KEY = 'entry-revision-manifest-current-v1';
    var REVISION_MANIFEST_PRUNE_LOCAL_KEY = 'entry-revision-manifest-last-client-prune-v1';
    var ENTRY_CACHE_NAME = 'entry-cache-v1';
    var ENTRY_CACHE_INDEX_KEY = 'entry-cache-index-v1';
    var ENTRY_CACHE_REQUEST_PREFIX = '/__entry-cache__/';
    var ENTRY_CACHE_PACK_KEY = 'entry-cache-pack-state-v1';
 
    function hasCacheStorage() {
        return !!(window.caches && typeof window.caches.open === 'function');
    }
 
    function safeJsonParse(text, fallback) {
        try { return JSON.parse(text); } catch (err) { return fallback; }
    }
 
    function readLocalJson(key, fallback) {
        try {
            var text = window.localStorage ? window.localStorage.getItem(key) : null;
            return text ? safeJsonParse(text, fallback) : fallback;
        } catch (err) {
             return fallback;
         }
         }
    }


        function computeChanged(prev, next) {
    function writeLocalJson(key, value) {
            var prevLookup = buildLookup(prev);
        try {
             var nextLookup = buildLookup(next);
             if (window.localStorage) window.localStorage.setItem(key, JSON.stringify(value));
            var out = [];
        } catch (err) {}
            Object.keys(nextLookup).forEach(function (key) {
    }
                if (resourceToken(prevLookup[key]) !== resourceToken(nextLookup[key])) out.push(key);
            });
            Object.keys(prevLookup).forEach(function (key) {
                if (!nextLookup[key]) out.push(key);
            });
            return unique(out);
        }


        function load(options) {
    function normalizeManifestTitle(value) {
            if (loadPromise && !(options && options.force)) return loadPromise;
        var text = String(value || '').trim();
            loadPromise = fetchApi({
        var match;
                action: REVISION_MANIFEST_ACTION,
        var i;
                 format: 'json',
        if (!text) return '';
                formatversion: '2'
        for (i = 0; i < 3; i += 1) {
             }).then(function (payload) {
            try {
                var manifest = unwrap(payload);
                 if (/%[0-9a-f]{2}/i.test(text)) text = decodeURIComponent(text);
                if (!manifest || !manifest.resources) throw new Error('invalid revision manifest');
             } catch (err) { break; }
                current = compactRevisionManifest(manifest) || manifest;
        }
                changedResources = computeChanged(previous, current);
        match = text.match(/[?&]title=([^&#]+)/i);
                if (changedResources.length && window.EntryCache && typeof window.EntryCache.invalidateResources === 'function') {
        if (match) text = match[1];
                    window.EntryCache.invalidateResources(changedResources);
        text = text.replace(/^https?:\/\/[^/]+/i, '')
                }
            .replace(/^\/+/, '')
                writeLocalJson(REVISION_MANIFEST_LOCAL_KEY, current);
            .replace(/^index\.php\/?/i, '')
                previous = current;
            .replace(/^wiki\/?/i, '')
                maybePrune();
            .trim();
                return current;
        match = text.match(/(?:^|\/)(?:(?:Special|특수)\s*[:/]\s*)?(?:Redirect|넘겨주기)\s*\/\s*file\s*\/([^?#]+)(?:[?#].*)?$/i);
             }).catch(function () {
        if (match) text = 'File:' + match[1];
                current = previous || null;
        text = text.split('#')[0].replace(/_/g, ' ').replace(/\s+/g, ' ').trim();
                return current;
        text = text.replace(/^(?:파일|Image|이미지)\s*:/i, 'File:');
            });
        if (/^(?:mediawiki|template|module|manage|file)\s*:/i.test(text)) {
            return loadPromise;
             text = text.replace(/^([^:]+)\s*:\s*/, function (_, ns) { return ns.charAt(0).toUpperCase() + ns.slice(1).toLowerCase() + ':'; });
         }
         }
        if (/^File:/i.test(text)) text = 'File:' + text.slice(text.indexOf(':') + 1).trim();
        if (/^Mediawiki:/i.test(text)) text = 'MediaWiki:' + text.slice(text.indexOf(':') + 1).trim();
        return text;
    }


        function ensureLoaded() {
    function resourceToken(resource) {
            return current ? Promise.resolve(current) : load();
        if (!resource || typeof resource !== 'object') return '';
        }
        return String(resource.revision || resource.sha1 || resource.hash || resource.timestamp || resource.updatedAt || resource.url || '').trim();
    }


        function resourceForRef(ref) {
    function createEntryCache() {
            var title = normalizeManifestTitle(ref);
        var index = readLocalJson(ENTRY_CACHE_INDEX_KEY, { entries: {} }) || { entries: {} };
            var lookup;
        var packs = readLocalJson(ENTRY_CACHE_PACK_KEY, { packs: {} }) || { packs: {} };
            if (!title || !current) return null;
        var objectUrls = {};
            lookup = buildLookup(current);
        var stats = {
             return lookup[title.toLowerCase()] || null;
            textHits: 0,
         }
            blobHits: 0,
            misses: 0,
            networkStores: 0,
            stores: 0,
             deletes: 0
         };


         function tokenForRef(ref) {
         function ensureIndex() {
             return resourceToken(resourceForRef(ref));
             if (!index || typeof index !== 'object') index = { entries: {} };
            if (!index.entries || typeof index.entries !== 'object') index.entries = {};
         }
         }


         function resourceKeyForRef(ref) {
         function compactIndexForLocalStorage() {
             var title = normalizeManifestTitle(ref);
             var entries;
             return title ? title.toLowerCase() : '';
            var next = {};
            ensureIndex();
             entries = index.entries || {};
            Object.keys(entries).forEach(function (key) {
                var entry = entries[key] || {};
                var kind = String(entry.kind || 'raw').toLowerCase();
                /*
                * CacheStorage already owns image/blob bodies.  Keeping one localStorage
                * metadata row per flag/blob competes with MediaWiki ResourceLoader's own
                * localStorage module store and can trigger QuotaExceededError before our
                * code even runs on the next page load.  Text/json/file URL rows stay indexed
                * because they are small and useful for invalidation diagnostics.
                */
                if (kind === 'image' || kind === 'blob') return;
                next[key] = entry;
            });
            index.entries = next;
         }
         }


         function cacheKeyForRef(ref, type) {
         function ensurePacks() {
            var resourceKey = resourceKeyForRef(ref);
             if (!packs || typeof packs !== 'object') packs = { packs: {} };
            var token = tokenForRef(ref);
             if (!packs.packs || typeof packs.packs !== 'object') packs.packs = {};
             if (!resourceKey || !token) return '';
             return String(type || 'raw') + ':' + resourceKey + '@' + token;
         }
         }


         function manifestToken(extra) {
         function saveIndex() {
             var base = current && (current.manifestVersion || current.version || current.generatedAt || '') || '';
             ensureIndex();
             return String(base || 'no-manifest') + (extra ? (':' + String(extra)) : '');
             compactIndexForLocalStorage();
            writeLocalJson(ENTRY_CACHE_INDEX_KEY, index);
         }
         }


         function tokenFromUrl(url) {
         function savePacks() {
             var text = String(url || '');
             ensurePacks();
             var match = text.match(/[?&](?:_entryFileRev|_entryAsset|_entryRev)=([^&]+)/);
             writeLocalJson(ENTRY_CACHE_PACK_KEY, packs);
            if (!match) return '';
            try { return decodeURIComponent(match[1]); } catch (err) { return match[1]; }
         }
         }


         function cacheKeyForUrl(url, type) {
         function requestForKey(key) {
             var text = String(url || '').trim();
             return new Request(ENTRY_CACHE_REQUEST_PREFIX + encodeURIComponent(String(key || '')), { credentials: 'same-origin' });
            var token = tokenFromUrl(text) || manifestToken('url');
            var normalized;
            if (!text) return '';
            try {
                normalized = new URL(text, window.location.href);
                text = normalized.pathname + (normalized.search || '');
            } catch (err) {}
            text = text.replace(/[?&](?:_entryFileRev|_entryAsset|_entryRev)=[^&]*/g, '').replace(/[?&]$/, '');
            try { text = decodeURI(text); } catch (err2) {}
            return String(type || 'blob') + ':url:' + text.toLowerCase() + '@' + token;
         }
         }


         function addRevisionParam(url, ref) {
         function openCache() {
             var token = tokenForRef(ref);
             if (!hasCacheStorage()) return Promise.resolve(null);
            var text = String(url || '').trim();
             return window.caches.open(ENTRY_CACHE_NAME).catch(function () { return null; });
             var sep;
            if (!text || !token || /[?&]_entryRev=/.test(text)) return text;
            sep = text.indexOf('?') === -1 ? '?' : '&';
            return text + sep + '_entryRev=' + encodeURIComponent(token);
         }
         }


         function maybePrune() {
         function cacheEntry(key, meta) {
             var days = current && Number(current.pruneDays || current.clientPruneDays) || 7;
             key = String(key || '');
            var last = 0;
            ensureIndex();
            var due;
            index.entries[key] = Object.assign({}, index.entries[key] || {}, {
            try { last = Number(window.localStorage && window.localStorage.getItem(REVISION_MANIFEST_PRUNE_LOCAL_KEY) || 0); } catch (err) {}
                key: key,
             due = !last || (now() - last >= days * 24 * 60 * 60 * 1000);
                resourceKey: String(meta && meta.resourceKey || ''),
             if (due && window.EntryCache && typeof window.EntryCache.prune === 'function') {
                token: String(meta && meta.token || ''),
                 window.EntryCache.prune(days);
                kind: String(meta && meta.kind || 'raw'),
                contentType: String(meta && meta.contentType || ''),
                size: Number(meta && meta.size || 0) || null,
                createdAt: index.entries[key] && index.entries[key].createdAt ? index.entries[key].createdAt : now(),
                updatedAt: now(),
                lastHitAt: index.entries[key] && index.entries[key].lastHitAt ? index.entries[key].lastHitAt : null,
                hits: Number(index.entries[key] && index.entries[key].hits || 0)
            });
            saveIndex();
        }
 
        function markHit(key, field) {
             key = String(key || '');
            ensureIndex();
             if (index.entries[key]) {
                index.entries[key].hits = Number(index.entries[key].hits || 0) + 1;
                 index.entries[key].lastHitAt = now();
                saveIndex();
             }
             }
            if (field && stats[field] != null) stats[field] += 1;
         }
         }


         function countdown() {
         function getResponse(key) {
             var days = current && Number(current.pruneDays || current.clientPruneDays) || 7;
             key = String(key || '');
             var last = 0;
             if (!key || !hasCacheStorage()) return Promise.resolve(null);
             var next;
             return openCache().then(function (cache) {
            var remain;
                if (!cache) return null;
            try { last = Number(window.localStorage && window.localStorage.getItem(REVISION_MANIFEST_PRUNE_LOCAL_KEY) || 0); } catch (err) {}
                return cache.match(requestForKey(key)).then(function (res) {
            if (!last) return { days: days, lastClientPruneAt: null, nextClientPruneAt: null, remainingMs: 0, remainingDays: 0, due: true };
                    if (!res) {
            next = last + days * 24 * 60 * 60 * 1000;
                        stats.misses += 1;
            remain = Math.max(0, next - now());
                        return null;
            return {
                    }
                days: days,
                    return res;
                lastClientPruneAt: last,
                 });
                 nextClientPruneAt: next,
            }).catch(function () { return null; });
                remainingMs: remain,
                remainingDays: Math.ceil(remain / (24 * 60 * 60 * 1000)),
                due: remain <= 0
            };
         }
         }


         function status() {
         function putResponse(key, response, meta) {
             return {
             key = String(key || '');
                 available: !!current,
            if (!key || !response || !hasCacheStorage()) return Promise.resolve(false);
                manifestVersion: current && (current.manifestVersion || current.version || ''),
            meta = meta || {};
                generatedAt: current && current.generatedAt || '',
            return openCache().then(function (cache) {
                changedResources: changedResources.slice(0, 50),
                 var cloned;
                changedCount: changedResources.length,
                var headers;
                prune: countdown(),
                var bodyPromise;
                cache: window.EntryCache && typeof window.EntryCache.info === 'function' ? window.EntryCache.info() : null
                if (!cache) return false;
             };
                cloned = response.clone();
                bodyPromise = cloned.blob().catch(function () { return null; });
                return bodyPromise.then(function (blob) {
                    if (!blob) return false;
                    headers = new Headers(response.headers || {});
                    if (!headers.get('Content-Type')) headers.set('Content-Type', meta.contentType || blob.type || 'application/octet-stream');
                    headers.set('X-Entry-Cache-Key', key);
                    headers.set('X-Entry-Resource-Key', String(meta.resourceKey || ''));
                    headers.set('X-Entry-Revision-Token', String(meta.token || ''));
                    headers.set('X-Entry-Cached-At', String(now()));
                    return cache.put(requestForKey(key), new Response(blob, { status: 200, headers: headers })).then(function () {
                        stats.stores += 1;
                        cacheEntry(key, {
                            resourceKey: meta.resourceKey,
                            token: meta.token,
                            kind: meta.kind || 'blob',
                            contentType: headers.get('Content-Type') || blob.type || '',
                            size: blob.size
                        });
                        return true;
                    });
                });
             }).catch(function () { return false; });
         }
         }


         return {
         function getText(key) {
             load: load,
             return getResponse(key).then(function (res) {
            ensureLoaded: ensureLoaded,
                if (!res) return null;
            current: function () { return current; },
                markHit(key, 'textHits');
            resourceForRef: resourceForRef,
                return res.text();
            tokenForRef: tokenForRef,
             }).catch(function () { return null; });
             cacheKeyForRef: cacheKeyForRef,
        }
            cacheKeyForUrl: cacheKeyForUrl,
            manifestToken: manifestToken,
            resourceKeyForRef: resourceKeyForRef,
            addRevisionParam: addRevisionParam,
            maybePrune: maybePrune,
            countdown: countdown,
            status: status
        };
    }


    window.RevisionManifest = window.RevisionManifest || createRevisionManifestService();
        function putText(key, text, meta) {
 
            key = String(key || '');
    function createEntryStore() {
            if (!key || !hasCacheStorage()) return Promise.resolve(false);
        var jsonCache = {};
            meta = meta || {};
        var flagUrlCache = {};
            return openCache().then(function (cache) {
        var fileUrlCache = {};
                var headers;
        var imageReadyCache = {};
                var body = String(text || '');
        var imageObjectCache = {};
                if (!cache) return false;
        var imageDisplayUrlCache = {};
                headers = new Headers({
        var imagePromiseCache = {};
                    'Content-Type': meta.contentType || 'text/plain; charset=UTF-8',
        var rawPromiseCache = {};
                    'X-Entry-Cache-Key': key,
        var textCache = {};
                    'X-Entry-Resource-Key': String(meta.resourceKey || ''),
         var textPromiseCache = {};
                    'X-Entry-Revision-Token': String(meta.token || ''),
                    'X-Entry-Cached-At': String(now())
                });
                return cache.put(requestForKey(key), new Response(body, { status: 200, headers: headers })).then(function () {
                    stats.stores += 1;
                    cacheEntry(key, {
                        resourceKey: meta.resourceKey,
                        token: meta.token,
                        kind: meta.kind || 'text',
                        contentType: headers.get('Content-Type'),
                        size: body.length
                    });
                    return true;
                });
            }).catch(function () { return false; });
         }


         function fetchJsonRef(ref, options) {
         function getBlobUrl(key) {
             var key = normalizeRefKey(ref);
             key = String(key || '');
            var cacheKey;
             if (!key) return Promise.resolve('');
            var promiseKey;
             if (objectUrls[key]) {
            var url;
                markHit(key, 'blobHits');
            var resourceKey;
                return Promise.resolve(objectUrls[key]);
            var token;
             if (!key) return Promise.reject(new Error('empty json ref'));
             cacheKey = window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForRef === 'function' ? window.RevisionManifest.cacheKeyForRef(ref, 'json') : '';
            promiseKey = cacheKey ? (key + '@' + cacheKey) : key;
            if (jsonCache[promiseKey]) return Promise.resolve(jsonCache[promiseKey].data);
            if (rawPromiseCache[promiseKey]) return rawPromiseCache[promiseKey];
            url = rawUrlForRef(ref, 'application/json');
            if (window.RevisionManifest && typeof window.RevisionManifest.addRevisionParam === 'function') {
                url = window.RevisionManifest.addRevisionParam(url, ref);
             }
             }
             resourceKey = window.RevisionManifest && typeof window.RevisionManifest.resourceKeyForRef === 'function' ? window.RevisionManifest.resourceKeyForRef(ref) : key;
             return getResponse(key).then(function (res) {
            token = window.RevisionManifest && typeof window.RevisionManifest.tokenForRef === 'function' ? window.RevisionManifest.tokenForRef(ref) : '';
                if (!res) return '';
            if (cacheKey && !(options && options.noStore) && window.EntryCache && typeof window.EntryCache.getText === 'function') {
                 return res.blob().then(function (blob) {
                 rawPromiseCache[promiseKey] = window.EntryCache.getText(cacheKey).then(function (cachedText) {
                     if (!blob || !blob.size) return '';
                     if (cachedText !== null && cachedText !== undefined) {
                    objectUrls[key] = URL.createObjectURL(blob);
                        var cachedData = cachedText && cachedText.trim() ? JSON.parse(cachedText) : {};
                    markHit(key, 'blobHits');
                        jsonCache[promiseKey] = { key: promiseKey, ref: ref, url: url, data: cachedData, loadedAt: now(), persistent: true };
                    return objectUrls[key];
                        jsonCache[key] = jsonCache[promiseKey];
                });
                        return cachedData;
            }).catch(function () { return ''; });
                    }
        }
                    return fetch(url, {
 
                        credentials: 'same-origin',
        function fetchBlobUrl(url, key, meta, options) {
                        cache: 'force-cache'
            url = String(url || '').trim();
                    }).then(function (res) {
            key = String(key || '').trim();
                        if (!res.ok) throw new Error('HTTP ' + res.status);
            if (!url || !key) return Promise.resolve('');
                        return res.text();
            return getBlobUrl(key).then(function (cachedUrl) {
                     }).then(function (text) {
                if (cachedUrl) return cachedUrl;
                        var data = text && text.trim() ? JSON.parse(text) : {};
                return fetch(url, {
                        jsonCache[promiseKey] = { key: promiseKey, ref: ref, url: url, data: data, loadedAt: now() };
                    credentials: 'same-origin',
                        jsonCache[key] = jsonCache[promiseKey];
                    cache: options && options.noStore ? 'no-store' : 'force-cache'
                        window.EntryCache.putText(cacheKey, text, { resourceKey: resourceKey, token: token });
                }).then(function (res) {
                         return data;
                    if (!res.ok) throw new Error('HTTP ' + res.status);
                    stats.networkStores += 1;
                     return putResponse(key, res, Object.assign({}, meta || {}, { kind: meta && meta.kind ? meta.kind : 'blob' })).then(function () {
                         return getBlobUrl(key);
                     });
                     });
                }).catch(function () {
                    return '';
                 });
                 });
                return rawPromiseCache[promiseKey];
            }
            rawPromiseCache[promiseKey] = fetch(url, {
                credentials: 'same-origin',
                cache: options && options.noStore ? 'no-store' : 'force-cache'
            }).then(function (res) {
                if (!res.ok) throw new Error('HTTP ' + res.status);
                return res.text();
            }).then(function (text) {
                var data = text && text.trim() ? JSON.parse(text) : {};
                jsonCache[promiseKey] = { key: promiseKey, ref: ref, url: url, data: data, loadedAt: now() };
                jsonCache[key] = jsonCache[promiseKey];
                return data;
             });
             });
            return rawPromiseCache[promiseKey];
         }
         }


         function getJsonSync(ref) {
         function deleteKey(key) {
             var key = normalizeRefKey(ref);
             key = String(key || '');
             return key && jsonCache[key] ? jsonCache[key].data : null;
             if (!key || !hasCacheStorage()) return Promise.resolve(false);
        }
            if (objectUrls[key]) {
 
                try { URL.revokeObjectURL(objectUrls[key]); } catch (err) {}
        function setJsonRef(ref, data) {
                delete objectUrls[key];
            var key = normalizeRefKey(ref);
            }
            if (!key) return;
            return openCache().then(function (cache) {
            jsonCache[key] = { key: key, ref: ref, url: rawUrlForRef(ref, 'application/json'), data: data, loadedAt: now() };
                if (!cache) return false;
                return cache.delete(requestForKey(key)).then(function (ok) {
                    ensureIndex();
                    if (index.entries && index.entries[key]) {
                        delete index.entries[key];
                        stats.deletes += 1;
                        saveIndex();
                    }
                    return ok;
                });
            }).catch(function () { return false; });
         }
         }


         function normalizeFile(value) {
         function invalidateResources(resourceKeys) {
             return String(value || '')
             var map = {};
                 .replace(/^(?:file|파일):/i, '')
            var entries;
                 .trim();
            var keys = [];
            ensureIndex();
            entries = index.entries || {};
            (resourceKeys || []).forEach(function (resourceKey) {
                resourceKey = String(resourceKey || '').toLowerCase();
                 if (resourceKey) map[resourceKey] = true;
            });
            Object.keys(entries).forEach(function (cacheKey) {
                var resourceKey = String(entries[cacheKey] && entries[cacheKey].resourceKey || '').toLowerCase();
                 if (map[resourceKey]) keys.push(cacheKey);
            });
            return Promise.all(keys.map(deleteKey)).then(function () { return keys.length; });
         }
         }


         function fileKey(value) {
         function prune(maxAgeDays) {
             return normalizeFile(value).replace(/_/g, ' ').replace(/\s+/g, ' ').toLowerCase();
             var days = Math.max(1, Number(maxAgeDays) || 7);
            var cutoff = now() - days * 24 * 60 * 60 * 1000;
            var entries;
            var keys;
            ensureIndex();
            entries = index.entries || {};
            keys = Object.keys(entries).filter(function (key) {
                return Number(entries[key] && entries[key].createdAt || 0) < cutoff;
            });
            window.localStorage && window.localStorage.setItem(REVISION_MANIFEST_PRUNE_LOCAL_KEY, String(now()));
            return Promise.all(keys.map(deleteKey)).then(function () { return keys.length; });
         }
         }


         function setFlagUrl(file, url) {
         function reset() {
             var key = fileKey(file);
             Object.keys(objectUrls).forEach(function (key) {
             if (!key) return;
                try { URL.revokeObjectURL(objectUrls[key]); } catch (err) {}
             flagUrlCache[key] = String(url || '');
            });
            objectUrls = {};
            index = { entries: {} };
            packs = { packs: {} };
            saveIndex();
            savePacks();
             if (!hasCacheStorage()) return Promise.resolve(false);
             return window.caches.delete(ENTRY_CACHE_NAME).catch(function () { return false; });
         }
         }


         function getFlagUrl(file) {
         function packReady(key, token) {
             var key = fileKey(file);
             key = String(key || '');
             return key ? (flagUrlCache[key] || '') : '';
            token = String(token || '');
            ensurePacks();
             if (!key || !token) return false;
            return !!(packs.packs[key] && String(packs.packs[key].token || '') === token && packs.packs[key].ready);
         }
         }


         function resolveFlagUrls(files) {
         function setPackReady(key, token, meta) {
             var clean = unique((files || []).map(normalizeFile).filter(Boolean));
             key = String(key || '');
            token = String(token || '');
            if (!key || !token) return false;
            ensurePacks();
            packs.packs[key] = Object.assign({}, meta || {}, {
                key: key,
                token: token,
                ready: true,
                updatedAt: now()
            });
            savePacks();
            return true;
        }


            function cacheKeyForFile(file) {
        function packInfo() {
                return window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForRef === 'function' ? window.RevisionManifest.cacheKeyForRef('File:' + file, 'flagurl') : '';
            ensurePacks();
            }
            return Object.assign({}, packs.packs || {});
        }


            function resourceKeyForFile(file) {
        function info() {
                return window.RevisionManifest && typeof window.RevisionManifest.resourceKeyForRef === 'function' ? window.RevisionManifest.resourceKeyForRef('File:' + file) : ('file:' + fileKey(file));
            var lastClientPrune = 0;
            }
            var entries;
            var byKind = {};
            try { lastClientPrune = Number(window.localStorage && window.localStorage.getItem(REVISION_MANIFEST_PRUNE_LOCAL_KEY) || 0); } catch (err) {}
            ensureIndex();
            ensurePacks();
            entries = index.entries || {};
            Object.keys(entries).forEach(function (key) {
                var kind = String(entries[key] && entries[key].kind || 'raw');
                byKind[kind] = (byKind[kind] || 0) + 1;
            });
            return {
                supported: hasCacheStorage(),
                name: ENTRY_CACHE_NAME,
                entries: Object.keys(entries).length,
                byKind: byKind,
                packs: Object.keys(packs.packs || {}).length,
                lastClientPruneAt: lastClientPrune || null,
                stats: Object.assign({}, stats)
            };
        }


            function tokenForFile(file) {
        /* Trim legacy image/blob metadata rows produced by older builds. */
                return window.RevisionManifest && typeof window.RevisionManifest.tokenForRef === 'function' ? window.RevisionManifest.tokenForRef('File:' + file) : '';
        try { saveIndex(); } catch (err) {}
            }


             function hydrateCachedFlagUrl(file) {
        return {
                var key = fileKey(file);
            getResponse: getResponse,
                var cacheKey = cacheKeyForFile(file);
            putResponse: putResponse,
                if (!key || flagUrlCache[key] !== undefined || !cacheKey || !window.EntryCache || typeof window.EntryCache.getText !== 'function') {
            getText: getText,
                    return Promise.resolve(false);
            putText: putText,
                }
            getBlobUrl: getBlobUrl,
                return window.EntryCache.getText(cacheKey).then(function (cachedUrl) {
            fetchBlobUrl: fetchBlobUrl,
                    if (cachedUrl !== null && cachedUrl !== undefined) {
             invalidateResources: invalidateResources,
                        flagUrlCache[key] = String(cachedUrl || '');
            prune: prune,
                        return true;
            reset: reset,
                    }
            packReady: packReady,
                    return false;
            setPackReady: setPackReady,
                }).catch(function () { return false; });
            packInfo: packInfo,
            }
            info: info
        };
    }
 
    window.EntryCache = window.EntryCache || createEntryCache();
 
    function createRevisionManifestService() {
        var current = null;
        var previous = readLocalJson(REVISION_MANIFEST_LOCAL_KEY, null);
        var loadPromise = null;
        var changedResources = [];
 
        function unwrap(payload) {
            return payload && (payload.entryrevisionmanifest || payload.revisionManifest || payload) || null;
        }
 
        function resourcesOf(manifest) {
            return manifest && manifest.resources && typeof manifest.resources === 'object' ? manifest.resources : {};
        }


             return Promise.all(clean.map(hydrateCachedFlagUrl)).then(function () {
        function compactRevisionManifest(manifest) {
                 var pending = clean.filter(function (file) {
            var out;
                     return getFlagUrl(file) === '' && flagUrlCache[fileKey(file)] === undefined;
             var resources;
            if (!manifest || typeof manifest !== 'object') return null;
            out = {
                manifestVersion: manifest.manifestVersion || manifest.version || '',
                version: manifest.version || manifest.manifestVersion || '',
                generatedAt: manifest.generatedAt || '',
                pruneDays: manifest.pruneDays,
                clientPruneDays: manifest.clientPruneDays,
                resources: {}
            };
            resources = resourcesOf(manifest);
            Object.keys(resources).forEach(function (title) {
                 var src = resources[title];
                var dst;
                if (!src || typeof src !== 'object') return;
                dst = {};
                ['revision', 'sha1', 'hash', 'timestamp', 'updatedAt', 'url'].forEach(function (key) {
                     if (src[key] !== undefined && src[key] !== null && String(src[key]) !== '') dst[key] = src[key];
                 });
                 });
                 var chunks = [];
                 out.resources[title] = dst;
            });
            return out;
        }


                while (pending.length) chunks.push(pending.splice(0, 20));
        function buildLookup(manifest) {
                if (!chunks.length) return flagUrlCache;
            var lookup = {};
            Object.keys(resourcesOf(manifest)).forEach(function (title) {
                lookup[normalizeManifestTitle(title).toLowerCase()] = resourcesOf(manifest)[title];
            });
            return lookup;
        }


                return Promise.all(chunks.map(function (chunk) {
        function computeChanged(prev, next) {
                    var titleToKey = {};
            var prevLookup = buildLookup(prev);
                    var keyToFile = {};
            var nextLookup = buildLookup(next);
                    var titles = [];
            var out = [];
                    chunk.forEach(function (file) {
            Object.keys(nextLookup).forEach(function (key) {
                        var key = fileKey(file);
                if (resourceToken(prevLookup[key]) !== resourceToken(nextLookup[key])) out.push(key);
                        if (!key) return;
            });
                        titleToKey[fileKey('File:' + file)] = key;
            Object.keys(prevLookup).forEach(function (key) {
                        titleToKey[fileKey('파일:' + file)] = key;
                if (!nextLookup[key]) out.push(key);
                        keyToFile[key] = file;
            });
                        titles.push('File:' + file);
            return unique(out);
                        titles.push('파일:' + file);
        }
                    });
 
                    return fetchApi({
        function load(options) {
                        action: 'query',
            if (loadPromise && !(options && options.force)) return loadPromise;
                        format: 'json',
            loadPromise = fetchApi({
                        formatversion: '2',
                action: REVISION_MANIFEST_ACTION,
                        redirects: '1',
                format: 'json',
                        prop: 'imageinfo',
                formatversion: '2'
                        iiprop: 'url|sha1|timestamp|size',
            }).then(function (payload) {
                        iiurlwidth: '16',
                var manifest = unwrap(payload);
                        titles: titles.join('|')
                if (!manifest || !manifest.resources) throw new Error('invalid revision manifest');
                    }).then(function (json) {
                current = compactRevisionManifest(manifest) || manifest;
                        var pages = (json && json.query && json.query.pages) || [];
                changedResources = computeChanged(previous, current);
                        var seen = {};
                if (changedResources.length && window.EntryCache && typeof window.EntryCache.invalidateResources === 'function') {
                        pages.forEach(function (page) {
                    window.EntryCache.invalidateResources(changedResources);
                            var key = titleToKey[fileKey(page && page.title)] || fileKey(page && page.title);
                }
                            var file = keyToFile[key] || (page && page.title || '').replace(/^(?:File|파일):/i, '');
                writeLocalJson(REVISION_MANIFEST_LOCAL_KEY, current);
                            var imageinfo = page && page.imageinfo && page.imageinfo[0];
                previous = current;
                            var url;
                maybePrune();
                            var rev;
                return current;
                            var sep;
            }).catch(function () {
                            var cacheKey;
                current = previous || null;
                            if (!key) return;
                 return current;
                            seen[key] = true;
            });
                            url = imageinfo && (imageinfo.thumburl || imageinfo.url) ? (imageinfo.thumburl || imageinfo.url) : '';
             return loadPromise;
                            if (url) {
                                rev = imageinfo && (imageinfo.sha1 || imageinfo.timestamp || imageinfo.size) ? (imageinfo.sha1 || imageinfo.timestamp || imageinfo.size) : '';
                                if (rev && !/[?&]_entryFileRev=/.test(url)) {
                                    sep = url.indexOf('?') === -1 ? '?' : '&';
                                    url += sep + '_entryFileRev=' + encodeURIComponent(String(rev));
                                }
                            }
                            flagUrlCache[key] = url;
                            cacheKey = cacheKeyForFile(file);
                            if (cacheKey && window.EntryCache && typeof window.EntryCache.putText === 'function') {
                                window.EntryCache.putText(cacheKey, url || '', {
                                    resourceKey: resourceKeyForFile(file),
                                    token: tokenForFile(file),
                                    kind: 'flagurl',
                                    contentType: 'text/plain; charset=UTF-8'
                                });
                            }
                        });
                        chunk.forEach(function (file) {
                            var key = fileKey(file);
                            if (key && !seen[key] && flagUrlCache[key] === undefined) flagUrlCache[key] = '';
                        });
                    }).catch(function () {
                        chunk.forEach(function (file) {
                            var key = fileKey(file);
                            if (key && flagUrlCache[key] === undefined) flagUrlCache[key] = '';
                        });
                    });
                 })).then(function () { return flagUrlCache; });
             });
         }
         }


         function normalizeGenericFileTitle(value) {
         function ensureLoaded() {
             var text = String(value || '').trim();
             return current ? Promise.resolve(current) : load();
            var match;
            var i;
 
            if (!text) return '';
            for (i = 0; i < 4; i += 1) {
                try {
                    if (/%[0-9a-f]{2}/i.test(text)) text = decodeURIComponent(text);
                } catch (err) {
                    break;
                }
            }
            match = text.match(/[?&]title=([^&#]+)/i);
            if (match) text = match[1];
            text = text.replace(/^https?:\/\/[^/]+/i, '').replace(/^\/+/, '').replace(/^index\.php\/?/i, '').replace(/^wiki\/?/i, '').trim();
            match = text.match(/(?:^|\/)(?:(?:Special|특수)\s*[:/]\s*)?(?:Redirect|넘겨주기)\s*\/\s*file\s*\/(.+)$/i);
            if (match) text = match[1];
            text = text.replace(/^(?:File|파일|Image|이미지)\s*:/i, '').replace(/^:+/, '').trim();
            return text;
         }
         }


         function isFileRef(value) {
         function resourceForRef(ref) {
             var text = String(value || '').trim();
             var title = normalizeManifestTitle(ref);
             return /^(?:file|파일)\s*:/i.test(text) || /(?:^|\/)(?:(?:Special|특수)\s*[:/]\s*)?(?:Redirect|넘겨주기)\s*\/\s*file\s*\//i.test(text);
            var lookup;
            if (!title || !current) return null;
            lookup = buildLookup(current);
             return lookup[title.toLowerCase()] || null;
         }
         }


         function fileUrlKey(value) {
         function tokenForRef(ref) {
             return normalizeGenericFileTitle(value).replace(/_/g, ' ').replace(/\s+/g, ' ').toLowerCase();
             return resourceToken(resourceForRef(ref));
         }
         }


         function stableDirectImageUrl(url) {
         function resourceKeyForRef(ref) {
            var title = normalizeManifestTitle(ref);
            return title ? title.toLowerCase() : '';
        }
 
        function cacheKeyForRef(ref, type) {
            var resourceKey = resourceKeyForRef(ref);
            var token = tokenForRef(ref);
            if (!resourceKey || !token) return '';
            return String(type || 'raw') + ':' + resourceKey + '@' + token;
        }
 
        function manifestToken(extra) {
            var base = current && (current.manifestVersion || current.version || current.generatedAt || '') || '';
            return String(base || 'no-manifest') + (extra ? (':' + String(extra)) : '');
        }
 
        function tokenFromUrl(url) {
            var text = String(url || '');
            var match = text.match(/[?&](?:_entryFileRev|_entryAsset|_entryRev)=([^&]+)/);
            if (!match) return '';
            try { return decodeURIComponent(match[1]); } catch (err) { return match[1]; }
        }
 
        function cacheKeyForUrl(url, type) {
             var text = String(url || '').trim();
             var text = String(url || '').trim();
             var separator;
             var token = tokenFromUrl(text) || manifestToken('url');
             var bust;
             var normalized;
             if (!text) return '';
             if (!text) return '';
             if (/[?&]_entryAsset=/.test(text) || /[?&]_=/.test(text)) return text;
             try {
             bust = String(BUILD_ID || 'entry');
                normalized = new URL(text, window.location.href);
             separator = text.indexOf('?') === -1 ? '?' : '&';
                text = normalized.pathname + (normalized.search || '');
             return text + separator + '_entryAsset=' + encodeURIComponent(bust);
            } catch (err) {}
            text = text.replace(/[?&](?:_entryFileRev|_entryAsset|_entryRev)=[^&]*/g, '').replace(/[?&]$/, '');
            try { text = decodeURI(text); } catch (err2) {}
            return String(type || 'blob') + ':url:' + text.toLowerCase() + '@' + token;
        }
 
        function addRevisionParam(url, ref) {
            var token = tokenForRef(ref);
             var text = String(url || '').trim();
            var sep;
            if (!text || !token || /[?&]_entryRev=/.test(text)) return text;
             sep = text.indexOf('?') === -1 ? '?' : '&';
             return text + sep + '_entryRev=' + encodeURIComponent(token);
         }
         }


         function resolveFileUrl(ref) {
         function maybePrune() {
             var original = String(ref || '').trim();
             var days = current && Number(current.pruneDays || current.clientPruneDays) || 7;
             var file;
             var last = 0;
             var key;
             var due;
             var cacheKey;
             try { last = Number(window.localStorage && window.localStorage.getItem(REVISION_MANIFEST_PRUNE_LOCAL_KEY) || 0); } catch (err) {}
            var resourceKey;
             due = !last || (now() - last >= days * 24 * 60 * 60 * 1000);
            var token;
             if (due && window.EntryCache && typeof window.EntryCache.prune === 'function') {
            if (!original) return Promise.resolve('');
                 window.EntryCache.prune(days);
            if (!isFileRef(original)) return Promise.resolve(stableDirectImageUrl(original));
            file = normalizeGenericFileTitle(original);
             key = fileUrlKey(file);
            if (!file || !key) return Promise.resolve(stableDirectImageUrl(original));
            if (fileUrlCache[key]) return Promise.resolve(fileUrlCache[key]);
            cacheKey = window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForRef === 'function' ? window.RevisionManifest.cacheKeyForRef('File:' + file, 'fileurl') : '';
            resourceKey = window.RevisionManifest && typeof window.RevisionManifest.resourceKeyForRef === 'function' ? window.RevisionManifest.resourceKeyForRef('File:' + file) : ('file:' + key);
            token = window.RevisionManifest && typeof window.RevisionManifest.tokenForRef === 'function' ? window.RevisionManifest.tokenForRef('File:' + file) : '';
             if (cacheKey && window.EntryCache && typeof window.EntryCache.getText === 'function') {
                 return window.EntryCache.getText(cacheKey).then(function (cachedUrl) {
                    if (cachedUrl !== null && cachedUrl !== undefined) {
                        fileUrlCache[key] = String(cachedUrl || '');
                        return fileUrlCache[key];
                    }
                    return fetchApi({
                        action: 'query',
                        format: 'json',
                        formatversion: '2',
                        redirects: '1',
                        prop: 'imageinfo',
                        iiprop: 'url|sha1|timestamp|size|mime',
                        titles: 'File:' + file
                    }).then(function (json) {
                        var pages = (json && json.query && json.query.pages) || [];
                        var info = pages[0] && pages[0].imageinfo && pages[0].imageinfo[0] ? pages[0].imageinfo[0] : null;
                        var url = info && info.url ? info.url : original;
                        var rev = info && (info.sha1 || info.timestamp || info.size) ? (info.sha1 || info.timestamp || info.size) : String(BUILD_ID || 'entry-file');
                        var separator = url.indexOf('?') === -1 ? '?' : '&';
                        var resolved = url + separator + '_entryFileRev=' + encodeURIComponent(String(rev));
                        fileUrlCache[key] = resolved;
                        window.EntryCache.putText(cacheKey, resolved, { resourceKey: resourceKey, token: token, kind: 'fileurl', contentType: 'text/plain; charset=UTF-8' });
                        return resolved;
                    });
                }).catch(function () {
                    return stableDirectImageUrl(original);
                });
             }
             }
            return fetchApi({
                action: 'query',
                format: 'json',
                formatversion: '2',
                redirects: '1',
                prop: 'imageinfo',
                iiprop: 'url|sha1|timestamp|size|mime',
                titles: 'File:' + file
            }).then(function (json) {
                var pages = (json && json.query && json.query.pages) || [];
                var info = pages[0] && pages[0].imageinfo && pages[0].imageinfo[0] ? pages[0].imageinfo[0] : null;
                var url = info && info.url ? info.url : original;
                var rev = info && (info.sha1 || info.timestamp || info.size) ? (info.sha1 || info.timestamp || info.size) : String(BUILD_ID || 'entry-file');
                var separator = url.indexOf('?') === -1 ? '?' : '&';
                var resolved = url + separator + '_entryFileRev=' + encodeURIComponent(String(rev));
                fileUrlCache[key] = resolved;
                return resolved;
            }).catch(function () {
                return stableDirectImageUrl(original);
            });
         }
         }


         function preloadImageUrl(url, options) {
         function countdown() {
             var key = String(url || '').trim();
             var days = current && Number(current.pruneDays || current.clientPruneDays) || 7;
             var cacheKey;
             var last = 0;
             var sourcePromise;
             var next;
             var persistent = !(options && options.persistent === false);
             var remain;
             if (!key) return Promise.resolve(false);
            try { last = Number(window.localStorage && window.localStorage.getItem(REVISION_MANIFEST_PRUNE_LOCAL_KEY) || 0); } catch (err) {}
             if (imageReadyCache[key]) return Promise.resolve(true);
             if (!last) return { days: days, lastClientPruneAt: null, nextClientPruneAt: null, remainingMs: 0, remainingDays: 0, due: true };
             if (imagePromiseCache[key]) return imagePromiseCache[key];
            next = last + days * 24 * 60 * 60 * 1000;
            remain = Math.max(0, next - now());
             return {
                days: days,
                lastClientPruneAt: last,
                nextClientPruneAt: next,
                remainingMs: remain,
                remainingDays: Math.ceil(remain / (24 * 60 * 60 * 1000)),
                due: remain <= 0
             };
        }


             cacheKey = persistent && window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForUrl === 'function' ? window.RevisionManifest.cacheKeyForUrl(key, 'image') : '';
        function status() {
            sourcePromise = Promise.resolve('');
             return {
            if (cacheKey && window.EntryCache && typeof window.EntryCache.fetchBlobUrl === 'function') {
                available: !!current,
                sourcePromise = window.EntryCache.fetchBlobUrl(key, cacheKey, {
                manifestVersion: current && (current.manifestVersion || current.version || ''),
                    resourceKey: '',
                generatedAt: current && current.generatedAt || '',
                    token: '',
                changedResources: changedResources.slice(0, 50),
                    kind: 'image'
                changedCount: changedResources.length,
                }).catch(function () { return ''; });
                prune: countdown(),
            }
                cache: window.EntryCache && typeof window.EntryCache.info === 'function' ? window.EntryCache.info() : null
            };
        }


            imagePromiseCache[key] = sourcePromise.then(function (cachedObjectUrl) {
        return {
                return new Promise(function (resolve) {
            load: load,
                    var img = new Image();
            ensureLoaded: ensureLoaded,
                    var settled = false;
            current: function () { return current; },
                    var src = cachedObjectUrl || key;
            resourceForRef: resourceForRef,
                    function finish(ok) {
            tokenForRef: tokenForRef,
                        if (settled) return;
            cacheKeyForRef: cacheKeyForRef,
                        settled = true;
            cacheKeyForUrl: cacheKeyForUrl,
                        if (ok) {
            manifestToken: manifestToken,
                            imageReadyCache[key] = true;
            resourceKeyForRef: resourceKeyForRef,
                            imageReadyCache[src] = true;
            addRevisionParam: addRevisionParam,
                            imageObjectCache[key] = img;
            maybePrune: maybePrune,
                            imageObjectCache[src] = img;
            countdown: countdown,
                            imageDisplayUrlCache[key] = src;
            status: status
                            imageDisplayUrlCache[src] = src;
        };
                        }
    }
                        resolve(!!ok);
                    }
                    img.onload = function () {
                        if (img.decode) {
                            img.decode().then(function () { finish(true); }).catch(function () { finish(true); });
                        } else {
                            finish(true);
                        }
                    };
                    img.onerror = function () {
                        if (src !== key) {
                            src = key;
                            img.src = key;
                            return;
                        }
                        finish(false);
                    };
                    img.decoding = 'async';
                    img.loading = 'eager';
                    img.src = src;
                    if (img.complete && img.naturalWidth) {
                        if (img.decode) img.decode().then(function () { finish(true); }).catch(function () { finish(true); });
                        else finish(true);
                    }
                });
            });
            return imagePromiseCache[key];
        }


        function preloadImages(urls, options) {
    window.RevisionManifest = window.RevisionManifest || createRevisionManifestService();
            var list = unique((urls || []).filter(Boolean));
            var limit = options && Number(options.limit);
            var concurrency = Math.max(1, Math.min(48, Number(options && options.concurrency) || 24));
            var index = 0;
            var ok = 0;
            var fail = 0;
            if (Number.isFinite(limit) && limit > 0) list = list.slice(0, limit);
            if (!list.length) return Promise.resolve({ total: 0, ok: 0, fail: 0 });
            return new Promise(function (resolve) {
                function pump() {
                    while (index < list.length && concurrency > 0) {
                        (function (url) {
                            concurrency -= 1;
                            preloadImageUrl(url, options || {}).then(function (result) {
                                if (result) ok += 1;
                                else fail += 1;
                            }).catch(function () {
                                fail += 1;
                            }).then(function () {
                                concurrency += 1;
                                if (index >= list.length && ok + fail >= list.length) resolve({ total: list.length, ok: ok, fail: fail });
                                else pump();
                            });
                        })(list[index++]);
                    }
                }
                pump();
            });
        }


        function isImageReady(url) {
    function createEntryStore() {
            var key = String(url || '').trim();
        var jsonCache = {};
            return !!(key && imageReadyCache[key]);
        var flagUrlCache = {};
         }
        var fileUrlCache = {};
 
        var imageReadyCache = {};
         function getImageElement(url) {
         var imageObjectCache = {};
            var key = String(url || '').trim();
        var imageDisplayUrlCache = {};
            return key ? (imageObjectCache[key] || null) : null;
         var imagePromiseCache = {};
         }
        var rawPromiseCache = {};
        var textCache = {};
         var textPromiseCache = {};


         function getImageDisplayUrl(url) {
         function fetchJsonRef(ref, options) {
            var key = String(url || '').trim();
             var key = normalizeRefKey(ref);
            return key ? (imageDisplayUrlCache[key] || key) : '';
        }
 
        function normalizeUrlKey(url) {
            var text = String(url || '').trim();
            var a;
            if (!text) return '';
            try {
                a = document.createElement('a');
                a.href = text;
                text = a.pathname + (a.search || '');
            } catch (err) {}
            try {
                text = decodeURI(text);
            } catch (err2) {}
            text = text.replace(/([?&])_=[^&]*/g, '$1').replace(/[?&]$/, '');
            text = text.replace(/_/g, '_');
            return text;
        }
 
        function fetchTextUrl(url, options) {
             var key = normalizeUrlKey(url);
             var cacheKey;
             var cacheKey;
             var resourceRef;
             var promiseKey;
            var url;
             var resourceKey;
             var resourceKey;
             var token;
             var token;
             if (!key) return Promise.reject(new Error('empty text url'));
             if (!key) return Promise.reject(new Error('empty json ref'));
             if (textCache[key]) return Promise.resolve(textCache[key].text);
            cacheKey = window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForRef === 'function' ? window.RevisionManifest.cacheKeyForRef(ref, 'json') : '';
             if (textPromiseCache[key]) return textPromiseCache[key];
            promiseKey = cacheKey ? (key + '@' + cacheKey) : key;
             resourceRef = options && options.resourceRef ? options.resourceRef : (options && options.ref ? options.ref : '');
             if (jsonCache[promiseKey]) return Promise.resolve(jsonCache[promiseKey].data);
            cacheKey = resourceRef && window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForRef === 'function' ? window.RevisionManifest.cacheKeyForRef(resourceRef, 'text') : '';
             if (rawPromiseCache[promiseKey]) return rawPromiseCache[promiseKey];
             if (!cacheKey && window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForUrl === 'function') cacheKey = window.RevisionManifest.cacheKeyForUrl(url, 'text');
             url = rawUrlForRef(ref, 'application/json');
             resourceKey = resourceRef && window.RevisionManifest && typeof window.RevisionManifest.resourceKeyForRef === 'function' ? window.RevisionManifest.resourceKeyForRef(resourceRef) : ('url:' + key);
             if (window.RevisionManifest && typeof window.RevisionManifest.addRevisionParam === 'function') {
             token = resourceRef && window.RevisionManifest && typeof window.RevisionManifest.tokenForRef === 'function' ? window.RevisionManifest.tokenForRef(resourceRef) : '';
                url = window.RevisionManifest.addRevisionParam(url, ref);
            }
             resourceKey = window.RevisionManifest && typeof window.RevisionManifest.resourceKeyForRef === 'function' ? window.RevisionManifest.resourceKeyForRef(ref) : key;
             token = window.RevisionManifest && typeof window.RevisionManifest.tokenForRef === 'function' ? window.RevisionManifest.tokenForRef(ref) : '';
             if (cacheKey && !(options && options.noStore) && window.EntryCache && typeof window.EntryCache.getText === 'function') {
             if (cacheKey && !(options && options.noStore) && window.EntryCache && typeof window.EntryCache.getText === 'function') {
                 textPromiseCache[key] = window.EntryCache.getText(cacheKey).then(function (cachedText) {
                 rawPromiseCache[promiseKey] = window.EntryCache.getText(cacheKey).then(function (cachedText) {
                     if (cachedText !== null && cachedText !== undefined) {
                     if (cachedText !== null && cachedText !== undefined) {
                         textCache[key] = { key: key, url: url, text: cachedText, loadedAt: now(), persistent: true };
                         var cachedData = cachedText && cachedText.trim() ? JSON.parse(cachedText) : {};
                         return cachedText;
                        jsonCache[promiseKey] = { key: promiseKey, ref: ref, url: url, data: cachedData, loadedAt: now(), persistent: true };
                        jsonCache[key] = jsonCache[promiseKey];
                         return cachedData;
                     }
                     }
                     return fetch(url, {
                     return fetch(url, {
1,744번째 줄: 1,805번째 줄:
                         return res.text();
                         return res.text();
                     }).then(function (text) {
                     }).then(function (text) {
                         textCache[key] = { key: key, url: url, text: text, loadedAt: now() };
                         var data = text && text.trim() ? JSON.parse(text) : {};
                         window.EntryCache.putText(cacheKey, text, { resourceKey: resourceKey, token: token, kind: 'text', contentType: 'text/html; charset=UTF-8' });
                        jsonCache[promiseKey] = { key: promiseKey, ref: ref, url: url, data: data, loadedAt: now() };
                         return text;
                        jsonCache[key] = jsonCache[promiseKey];
                         window.EntryCache.putText(cacheKey, text, { resourceKey: resourceKey, token: token });
                         return data;
                     });
                     });
                 });
                 });
                 return textPromiseCache[key];
                 return rawPromiseCache[promiseKey];
             }
             }
             textPromiseCache[key] = fetch(url, {
             rawPromiseCache[promiseKey] = fetch(url, {
                 credentials: 'same-origin',
                 credentials: 'same-origin',
                 cache: options && options.noStore ? 'no-store' : 'force-cache'
                 cache: options && options.noStore ? 'no-store' : 'force-cache'
1,758번째 줄: 1,821번째 줄:
                 return res.text();
                 return res.text();
             }).then(function (text) {
             }).then(function (text) {
                 textCache[key] = { key: key, url: url, text: text, loadedAt: now() };
                 var data = text && text.trim() ? JSON.parse(text) : {};
                 return text;
                jsonCache[promiseKey] = { key: promiseKey, ref: ref, url: url, data: data, loadedAt: now() };
                jsonCache[key] = jsonCache[promiseKey];
                 return data;
             });
             });
             return textPromiseCache[key];
             return rawPromiseCache[promiseKey];
         }
         }


         function getTextSync(url) {
         function getJsonSync(ref) {
             var key = normalizeUrlKey(url);
             var key = normalizeRefKey(ref);
             return key && textCache[key] ? textCache[key].text : '';
             return key && jsonCache[key] ? jsonCache[key].data : null;
         }
         }


         function setTextUrl(url, text) {
         function setJsonRef(ref, data) {
             var key = normalizeUrlKey(url);
             var key = normalizeRefKey(ref);
             if (!key) return;
             if (!key) return;
             textCache[key] = { key: key, url: url, text: String(text || ''), loadedAt: now() };
             jsonCache[key] = { key: key, ref: ref, url: rawUrlForRef(ref, 'application/json'), data: data, loadedAt: now() };
        }
 
        function normalizeFile(value) {
            return String(value || '')
                .replace(/^(?:file|파일):/i, '')
                .trim();
        }
 
        function fileKey(value) {
            return normalizeFile(value).replace(/_/g, ' ').replace(/\s+/g, ' ').toLowerCase();
         }
         }


         function cacheInfo() {
         function setFlagUrl(file, url) {
             return {
             var key = fileKey(file);
                json: Object.keys(jsonCache).length,
            if (!key) return;
                jsonKeys: Object.keys(jsonCache),
            flagUrlCache[key] = String(url || '');
                flags: Object.keys(flagUrlCache).length,
                files: Object.keys(fileUrlCache).length,
                images: Object.keys(imageReadyCache).length,
                retainedImages: Object.keys(imageObjectCache).length,
                displayImages: Object.keys(imageDisplayUrlCache).length,
                text: Object.keys(textCache).length,
                textKeys: Object.keys(textCache)
            };
         }
         }


         return {
         function getFlagUrl(file) {
            fetchJsonRef: fetchJsonRef,
            var key = fileKey(file);
            getJsonSync: getJsonSync,
            return key ? (flagUrlCache[key] || '') : '';
            setJsonRef: setJsonRef,
         }
            normalizeRefKey: normalizeRefKey,
            rawUrlForRef: rawUrlForRef,
            revisionUrlForRef: function (ref, ctype) {
                var url = rawUrlForRef(ref, ctype);
                if (window.RevisionManifest && typeof window.RevisionManifest.addRevisionParam === 'function') {
                    url = window.RevisionManifest.addRevisionParam(url, ref);
                }
                return url;
            },
            resolveFlagUrls: resolveFlagUrls,
            setFlagUrl: setFlagUrl,
            getFlagUrl: getFlagUrl,
            resolveFileUrl: resolveFileUrl,
            preloadImageUrl: preloadImageUrl,
            preloadImages: preloadImages,
            isImageReady: isImageReady,
            getImageElement: getImageElement,
            getImageDisplayUrl: getImageDisplayUrl,
            fetchTextUrl: fetchTextUrl,
            getTextSync: getTextSync,
            setTextUrl: setTextUrl,
            stableDirectImageUrl: stableDirectImageUrl,
            cacheInfo: cacheInfo
         };
    }


    window.EntryStore = window.EntryStore || createEntryStore();
        function resolveFlagUrls(files) {
            var clean = unique((files || []).map(normalizeFile).filter(Boolean));


    function updateBootProgress(done, total, label) {
            function cacheKeyForFile(file) {
        var pct = total ? Math.max(0, Math.min(100, Math.round((done / total) * 100))) : 0;
                return window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForRef === 'function' ? window.RevisionManifest.cacheKeyForRef('File:' + file, 'flagurl') : '';
        if (bootProgressNode) bootProgressNode.textContent = pct + '%';
            }
        if (bootFillNode) bootFillNode.style.width = pct + '%';
        if (bootDetailNode && label) bootDetailNode.textContent = label;
    }


    function adoptBootScreen(node) {
            function resourceKeyForFile(file) {
        if (!node) return null;
                return window.RevisionManifest && typeof window.RevisionManifest.resourceKeyForRef === 'function' ? window.RevisionManifest.resourceKeyForRef('File:' + file) : ('file:' + fileKey(file));
        bootNode = node;
            }
        bootStatusNode = bootNode.querySelector('.boot-gate-status');
        bootProgressNode = bootNode.querySelector('.boot-gate-progress');
        bootDetailNode = bootNode.querySelector('.boot-gate-detail');
        bootFillNode = bootNode.querySelector('.boot-gate-meter-fill');
        bootNode.classList.add('is-active');
        bootNode.classList.remove('is-complete');
        return bootNode;
    }


    function ensureBootScreen(options) {
            function tokenForFile(file) {
        var panel;
                return window.RevisionManifest && typeof window.RevisionManifest.tokenForRef === 'function' ? window.RevisionManifest.tokenForRef('File:' + file) : '';
        var header;
            }
        var meter;
        var existing;
        var decoLayer;
        var close;
        var previewMode;
        options = options || {};
        previewMode = !!options.preview;
        if (bootNode && bootNode.parentNode) return bootNode;
        if (!document.body) return null;


        if (BOOT_EXCLUDED_PAGE && !previewMode) return null;
            function hydrateCachedFlagUrl(file) {
        if (!previewMode) activateBootSurface();
                var key = fileKey(file);
 
                var cacheKey = cacheKeyForFile(file);
        existing = document.getElementById('boot-gate-screen') || (!previewMode && window.__BootGatePrelude && window.__BootGatePrelude.ensure ? window.__BootGatePrelude.ensure() : null);
                if (!key || flagUrlCache[key] !== undefined || !cacheKey || !window.EntryCache || typeof window.EntryCache.getText !== 'function') {
        if (existing) return adoptBootScreen(existing);
                    return Promise.resolve(false);
                }
                return window.EntryCache.getText(cacheKey).then(function (cachedUrl) {
                    if (cachedUrl !== null && cachedUrl !== undefined) {
                        flagUrlCache[key] = String(cachedUrl || '');
                        return true;
                    }
                    return false;
                }).catch(function () { return false; });
            }


        bootNode = document.createElement('div');
            return Promise.all(clean.map(hydrateCachedFlagUrl)).then(function () {
        bootNode.id = 'boot-gate-screen';
                var pending = clean.filter(function (file) {
        bootNode.className = 'boot-gate-screen is-active';
                    return getFlagUrl(file) === '' && flagUrlCache[fileKey(file)] === undefined;
        bootNode.setAttribute('role', 'status');
                });
        bootNode.setAttribute('aria-live', 'polite');
                var chunks = [];


        panel = document.createElement('div');
                while (pending.length) chunks.push(pending.splice(0, 20));
        panel.className = 'boot-gate-panel';
                if (!chunks.length) return flagUrlCache;


        header = document.createElement('div');
                return Promise.all(chunks.map(function (chunk) {
        header.className = 'boot-gate-title';
                    var titleToKey = {};
        header.textContent = 'ARCHIVE INITIALIZATION';
                    var keyToFile = {};
 
                    var titles = [];
        bootStatusNode = document.createElement('div');
                    chunk.forEach(function (file) {
        bootStatusNode.className = 'boot-gate-status';
                        var key = fileKey(file);
        bootStatusNode.textContent = 'Preparing entry systems';
                        if (!key) return;
 
                        titleToKey[fileKey('File:' + file)] = key;
        meter = document.createElement('div');
                        titleToKey[fileKey('파일:' + file)] = key;
        meter.className = 'boot-gate-meter';
                        keyToFile[key] = file;
        bootFillNode = document.createElement('div');
                        titles.push('File:' + file);
        bootFillNode.className = 'boot-gate-meter-fill';
                        titles.push('파일:' + file);
        meter.appendChild(bootFillNode);
                    });
 
                    return fetchApi({
        bootProgressNode = document.createElement('div');
                        action: 'query',
        bootProgressNode.className = 'boot-gate-progress';
                        format: 'json',
        bootProgressNode.textContent = '0%';
                        formatversion: '2',
 
                        redirects: '1',
        bootDetailNode = document.createElement('div');
                        prop: 'imageinfo',
        bootDetailNode.className = 'boot-gate-detail';
                        iiprop: 'url|sha1|timestamp|size',
        bootDetailNode.textContent = 'loading manifest';
                        iiurlwidth: '16',
 
                        titles: titles.join('|')
        close = document.createElement('button');
                    }).then(function (json) {
        close.type = 'button';
                        var pages = (json && json.query && json.query.pages) || [];
        close.className = 'boot-gate-close';
                        var seen = {};
        close.setAttribute('aria-label', 'Close boot preview');
                        pages.forEach(function (page) {
        close.textContent = '×';
                            var key = titleToKey[fileKey(page && page.title)] || fileKey(page && page.title);
        close.addEventListener('click', function () { hideBootScreen(); });
                            var file = keyToFile[key] || (page && page.title || '').replace(/^(?:File|파일):/i, '');
                            var imageinfo = page && page.imageinfo && page.imageinfo[0];
                            var url;
                            var rev;
                            var sep;
                            var cacheKey;
                            if (!key) return;
                            seen[key] = true;
                            url = imageinfo && (imageinfo.thumburl || imageinfo.url) ? (imageinfo.thumburl || imageinfo.url) : '';
                            if (url) {
                                rev = imageinfo && (imageinfo.sha1 || imageinfo.timestamp || imageinfo.size) ? (imageinfo.sha1 || imageinfo.timestamp || imageinfo.size) : '';
                                if (rev && !/[?&]_entryFileRev=/.test(url)) {
                                    sep = url.indexOf('?') === -1 ? '?' : '&';
                                    url += sep + '_entryFileRev=' + encodeURIComponent(String(rev));
                                }
                            }
                            flagUrlCache[key] = url;
                            cacheKey = cacheKeyForFile(file);
                            if (cacheKey && window.EntryCache && typeof window.EntryCache.putText === 'function') {
                                window.EntryCache.putText(cacheKey, url || '', {
                                    resourceKey: resourceKeyForFile(file),
                                    token: tokenForFile(file),
                                    kind: 'flagurl',
                                    contentType: 'text/plain; charset=UTF-8'
                                });
                            }
                        });
                        chunk.forEach(function (file) {
                            var key = fileKey(file);
                            if (key && !seen[key] && flagUrlCache[key] === undefined) flagUrlCache[key] = '';
                        });
                    }).catch(function () {
                        chunk.forEach(function (file) {
                            var key = fileKey(file);
                            if (key && flagUrlCache[key] === undefined) flagUrlCache[key] = '';
                        });
                    });
                })).then(function () { return flagUrlCache; });
            });
        }


         decoLayer = document.createElement('div');
         function normalizeGenericFileTitle(value) {
        decoLayer.className = 'boot-gate-decoration-layer';
            var text = String(value || '').trim();
        decoLayer.setAttribute('data-decoration-target', 'boot-gate');
            var match;
        decoLayer.setAttribute('aria-hidden', 'true');
            var i;


        panel.appendChild(header);
            if (!text) return '';
        panel.appendChild(bootStatusNode);
            for (i = 0; i < 4; i += 1) {
        panel.appendChild(meter);
                try {
        panel.appendChild(bootProgressNode);
                    if (/%[0-9a-f]{2}/i.test(text)) text = decodeURIComponent(text);
        panel.appendChild(bootDetailNode);
                } catch (err) {
        bootNode.appendChild(decoLayer);
                    break;
        bootNode.appendChild(panel);
                }
        bootNode.appendChild(close);
            }
        document.body.appendChild(bootNode);
            match = text.match(/[?&]title=([^&#]+)/i);
        return bootNode;
            if (match) text = match[1];
    }
            text = text.replace(/^https?:\/\/[^/]+/i, '').replace(/^\/+/, '').replace(/^index\.php\/?/i, '').replace(/^wiki\/?/i, '').trim();
            match = text.match(/(?:^|\/)(?:(?:Special|특수)\s*[:/]\s*)?(?:Redirect|넘겨주기)\s*\/\s*file\s*\/(.+)$/i);
            if (match) text = match[1];
            text = text.replace(/^(?:File|파일|Image|이미지)\s*:/i, '').replace(/^:+/, '').trim();
            return text;
        }


    function hideBootScreen() {
        function isFileRef(value) {
        var node = bootNode || document.getElementById('boot-gate-screen');
            var text = String(value || '').trim();
        if (!node) {
            return /^(?:file|파일)\s*:/i.test(text) || /(?:^|\/)(?:(?:Special|특수)\s*[:/]\s*)?(?:Redirect|넘겨주기)\s*\/\s*file\s*\//i.test(text);
            document.documentElement.classList.remove('boot-gate-active');
            if (document.body) document.body.classList.remove('boot-gate-active');
            return;
         }
         }
        node.classList.add('is-complete');
        node.classList.remove('is-active');
        window.setTimeout(function () {
            if (node.parentNode) node.parentNode.removeChild(node);
            if (bootNode === node) bootNode = null;
            document.documentElement.classList.remove('boot-gate-active');
            if (document.body) document.body.classList.remove('boot-gate-active');
        }, 240);
    }


    function collectFlagsFromNationPayload(payload) {
         function fileUrlKey(value) {
        var files = [];
             return normalizeGenericFileTitle(value).replace(/_/g, ' ').replace(/\s+/g, ' ').toLowerCase();
         function add(value) {
             if (!value) return;
            if (typeof value === 'string') {
                files.push(value);
                return;
            }
            if (typeof value === 'object') files.push(value.file || value.flag_file || value.flag || value.flag_title || '');
         }
         }
         function scanItem(item) {
 
             if (!item || typeof item !== 'object') return;
         function stableDirectImageUrl(url) {
             if (Array.isArray(item.flags)) item.flags.forEach(add);
             var text = String(url || '').trim();
             add(item.flag_file || item.flag || item.flag_title || '');
            var separator;
            var bust;
            if (!text) return '';
             if (/[?&]_entryAsset=/.test(text) || /[?&]_=/.test(text)) return text;
             bust = String(BUILD_ID || 'entry');
            separator = text.indexOf('?') === -1 ? '?' : '&';
            return text + separator + '_entryAsset=' + encodeURIComponent(bust);
         }
         }
        (payload && payload.continents || []).forEach(function (continent) {
            (continent.regions || []).forEach(function (region) {
                (region.items || []).forEach(scanItem);
            });
        });
        return unique(files);
    }


    function collectFlagsFromLinkMap(payload) {
        function resolveFileUrl(ref) {
        var files = [];
            var original = String(ref || '').trim();
        var source = payload && payload.items ? payload.items : {};
            var file;
        Object.keys(source || {}).forEach(function (key) {
            var key;
             var item = source[key];
            var cacheKey;
             if (!item || typeof item !== 'object') return;
            var resourceKey;
             files.push(item.flag_file || item.flag || item.flag_title || '');
            var token;
        });
            if (!original) return Promise.resolve('');
        return unique(files);
            if (!isFileRef(original)) return Promise.resolve(stableDirectImageUrl(original));
    }
             file = normalizeGenericFileTitle(original);
 
            key = fileUrlKey(file);
    function prewarmImages(urls, limit) {
             if (!file || !key) return Promise.resolve(stableDirectImageUrl(original));
        return window.EntryStore.preloadImages(urls, {
            if (fileUrlCache[key]) return Promise.resolve(fileUrlCache[key]);
            limit: Number(limit) > 0 ? Number(limit) : 0,
            cacheKey = window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForRef === 'function' ? window.RevisionManifest.cacheKeyForRef('File:' + file, 'fileurl') : '';
            concurrency: 16,
             resourceKey = window.RevisionManifest && typeof window.RevisionManifest.resourceKeyForRef === 'function' ? window.RevisionManifest.resourceKeyForRef('File:' + file) : ('file:' + key);
            persistent: false
            token = window.RevisionManifest && typeof window.RevisionManifest.tokenForRef === 'function' ? window.RevisionManifest.tokenForRef('File:' + file) : '';
        });
            if (cacheKey && window.EntryCache && typeof window.EntryCache.getText === 'function') {
    }
                return window.EntryCache.getText(cacheKey).then(function (cachedUrl) {
 
                    if (cachedUrl !== null && cachedUrl !== undefined) {
    function getDecorationRuntime() {
                        fileUrlCache[key] = String(cachedUrl || '');
        return window.Decorations || window.CLBI_DECORATIONS || null;
                        return fileUrlCache[key];
    }
                    }
 
                    return fetchApi({
    function waitForDecorationRuntime() {
                        action: 'query',
        return new Promise(function (resolve) {
                        format: 'json',
            var tries = 0;
                        formatversion: '2',
             function tick() {
                        redirects: '1',
                 var runtime = getDecorationRuntime();
                        prop: 'imageinfo',
                 if (runtime) return resolve(runtime);
                        iiprop: 'url|sha1|timestamp|size|mime',
                 tries += 1;
                        titles: 'File:' + file
                 if (tries > 40) return resolve(null);
                    }).then(function (json) {
                 window.setTimeout(tick, 25);
                        var pages = (json && json.query && json.query.pages) || [];
             }
                        var info = pages[0] && pages[0].imageinfo && pages[0].imageinfo[0] ? pages[0].imageinfo[0] : null;
            tick();
                        var url = info && info.url ? info.url : original;
        });
                        var rev = info && (info.sha1 || info.timestamp || info.size) ? (info.sha1 || info.timestamp || info.size) : String(BUILD_ID || 'entry-file');
    }
                        var separator = url.indexOf('?') === -1 ? '?' : '&';
                        var resolved = url + separator + '_entryFileRev=' + encodeURIComponent(String(rev));
                        fileUrlCache[key] = resolved;
                        window.EntryCache.putText(cacheKey, resolved, { resourceKey: resourceKey, token: token, kind: 'fileurl', contentType: 'text/plain; charset=UTF-8' });
                        return resolved;
                    });
                }).catch(function () {
                    return stableDirectImageUrl(original);
                });
            }
            return fetchApi({
                action: 'query',
                format: 'json',
                formatversion: '2',
                redirects: '1',
                prop: 'imageinfo',
                iiprop: 'url|sha1|timestamp|size|mime',
                titles: 'File:' + file
             }).then(function (json) {
                 var pages = (json && json.query && json.query.pages) || [];
                var info = pages[0] && pages[0].imageinfo && pages[0].imageinfo[0] ? pages[0].imageinfo[0] : null;
                var url = info && info.url ? info.url : original;
                 var rev = info && (info.sha1 || info.timestamp || info.size) ? (info.sha1 || info.timestamp || info.size) : String(BUILD_ID || 'entry-file');
                 var separator = url.indexOf('?') === -1 ? '?' : '&';
                 var resolved = url + separator + '_entryFileRev=' + encodeURIComponent(String(rev));
                 fileUrlCache[key] = resolved;
                return resolved;
             }).catch(function () {
                return stableDirectImageUrl(original);
            });
        }


    function matchesDecorationEntry(entry, filter) {
        function preloadImageUrl(url, options) {
        var era = String(filter && filter.era || '').trim();
            var key = String(url || '').trim();
        var page = String(filter && filter.page || '').trim();
            var cacheKey;
        var entryPage = String(entry && entry.page || '').replace(/_/g, ' ').trim();
            var sourcePromise;
        if (!entry || typeof entry !== 'object') return false;
            var persistent = !(options && options.persistent === false);
        if (page && entryPage && entryPage !== page) return false;
            if (!key) return Promise.resolve(false);
        if (era && String(entry.era || '').trim() && String(entry.era || '').trim() !== era) return false;
            if (imageReadyCache[key]) return Promise.resolve(true);
        return true;
            if (imagePromiseCache[key]) return imagePromiseCache[key];
    }


    function prepareDecorationSet(task, level) {
            cacheKey = persistent && window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForUrl === 'function' ? window.RevisionManifest.cacheKeyForUrl(key, 'image') : '';
        var ref = task.ref || 'MediaWiki:Decorations.json';
            sourcePromise = Promise.resolve('');
        return window.EntryStore.fetchJsonRef(ref, { noStore: !!task.noStore }).then(function (registry) {
            if (cacheKey && window.EntryCache && typeof window.EntryCache.fetchBlobUrl === 'function') {
            var list = registry && Array.isArray(registry.decorations) ? registry.decorations : [];
                sourcePromise = window.EntryCache.fetchBlobUrl(key, cacheKey, {
            var pixelRefs = [];
                    resourceKey: '',
            list.forEach(function (entry) {
                    token: '',
                var type = String(entry && entry.assetType || '').toLowerCase();
                    kind: 'image'
                var asset = String(entry && (entry.asset || entry.src) || '').trim();
                }).catch(function () { return ''; });
                if (!asset) return;
            }
                if (type !== 'pixel-json' && !/\.json(?:[?#].*)?$/i.test(asset)) return;
 
                if (!matchesDecorationEntry(entry, task)) return;
            imagePromiseCache[key] = sourcePromise.then(function (cachedObjectUrl) {
                 pixelRefs.push(asset);
                return new Promise(function (resolve) {
                    var img = new Image();
                    var settled = false;
                    var src = cachedObjectUrl || key;
                    function finish(ok) {
                        if (settled) return;
                        settled = true;
                        if (ok) {
                            imageReadyCache[key] = true;
                            imageReadyCache[src] = true;
                            imageObjectCache[key] = img;
                            imageObjectCache[src] = img;
                            imageDisplayUrlCache[key] = src;
                            imageDisplayUrlCache[src] = src;
                        }
                        resolve(!!ok);
                    }
                    img.onload = function () {
                        if (img.decode) {
                            img.decode().then(function () { finish(true); }).catch(function () { finish(true); });
                        } else {
                            finish(true);
                        }
                    };
                    img.onerror = function () {
                        if (src !== key) {
                            src = key;
                            img.src = key;
                            return;
                        }
                        finish(false);
                    };
                    img.decoding = 'async';
                    img.loading = 'eager';
                    img.src = src;
                    if (img.complete && img.naturalWidth) {
                        if (img.decode) img.decode().then(function () { finish(true); }).catch(function () { finish(true); });
                        else finish(true);
                    }
                 });
             });
             });
             if (level !== 'full' || task.preparePixels === false || !pixelRefs.length) return registry;
             return imagePromiseCache[key];
            return waitForDecorationRuntime().then(function (runtime) {
         }
                if (!runtime || typeof runtime.preparePixelCanvas !== 'function') {
                    return Promise.all(pixelRefs.map(function (pixelRef) {
                        return window.EntryStore.fetchJsonRef(pixelRef).catch(function () { return null; });
                    })).then(function () { return registry; });
                }
                return Promise.all(pixelRefs.map(function (pixelRef) {
                    return runtime.preparePixelCanvas(pixelRef).catch(function () { return null; });
                })).then(function () { return registry; });
            });
         });
    }


    function prepareNationsEra(task, level) {
        function preloadImages(urls, options) {
        var era = String(task.era || '1950');
            var list = unique((urls || []).filter(Boolean));
        var listRef = task.listRef || ('MediaWiki:' + era + '_Nation_List.json');
            var limit = options && Number(options.limit);
        var linkRef = task.linkMapRef || ('MediaWiki:' + era + '_Nation_Link_Map.json');
            var concurrency = Math.max(1, Math.min(48, Number(options && options.concurrency) || 24));
        var jsonPhaseId = BootPerf.start('nations-era json fetch', { era: era, level: level, listRef: listRef, linkRef: linkRef });
            var index = 0;
        var listPromise = window.EntryStore.fetchJsonRef(listRef).catch(function () { return null; });
            var ok = 0;
        var linkPromise = window.EntryStore.fetchJsonRef(linkRef).catch(function () { return null; });
            var fail = 0;
 
            if (Number.isFinite(limit) && limit > 0) list = list.slice(0, limit);
        return Promise.all([listPromise, linkPromise]).then(function (results) {
            if (!list.length) return Promise.resolve({ total: 0, ok: 0, fail: 0 });
            BootPerf.end(jsonPhaseId, { ok: true });
            return new Promise(function (resolve) {
            var files;
                function pump() {
            var flagUrls;
                    while (index < list.length && concurrency > 0) {
            if (level !== 'full' && level !== 'warm') return results;
                        (function (url) {
            files = unique(collectFlagsFromNationPayload(results[0]).concat(collectFlagsFromLinkMap(results[1])));
                            concurrency -= 1;
            return BootPerf.measure('nations-era flag url resolve', { era: era, count: files.length }, function () {
                            preloadImageUrl(url, options || {}).then(function (result) {
                return window.EntryStore.resolveFlagUrls(files);
                                if (result) ok += 1;
            }).then(function () {
                                else fail += 1;
                if (level === 'warm') {
                            }).catch(function () {
                    /*
                                fail += 1;
                    * Warm tab contract — 20260708.
                            }).then(function () {
                    *
                                concurrency += 1;
                    * A previous tab already stored the same-revision flag URL and image
                                if (index >= list.length && ok + fail >= list.length) resolve({ total: list.length, ok: ok, fail: fail });
                    * blobs.  Re-decoding every flag here makes the second tab feel as slow
                                else pump();
                    * as the first one.  In warm mode we only hydrate the flag URL table from
                            });
                    * EntryCache so NationsPanel can render stable URLs immediately; image
                        })(list[index++]);
                    * decode remains demand-driven by the live panel instead of blocking the
                     }
                    * boot screen.
                    */
                     return results;
                 }
                 }
                 flagUrls = files.map(function (file) { return window.EntryStore.getFlagUrl(file); }).filter(Boolean);
                 pump();
                /* Full means visible flag images are already downloaded and decoded, not just URL-resolved. */
                return BootPerf.measure('nations-era flag image prewarm', { era: era, count: flagUrls.length, limit: task.flagLimit == null ? 0 : Number(task.flagLimit) }, function () {
                    return prewarmImages(flagUrls, task.flagLimit == null ? 0 : Number(task.flagLimit));
                }).then(function () { return results; });
             });
             });
         });
         }
    }
 
        function isImageReady(url) {
            var key = String(url || '').trim();
            return !!(key && imageReadyCache[key]);
        }


    function prepareGlobeSharedAssets(task, level) {
        function getImageElement(url) {
        var refs = Array.isArray(task && task.assets) ? task.assets : [];
            var key = String(url || '').trim();
        if (!refs.length) return Promise.resolve(null);
             return key ? (imageObjectCache[key] || null) : null;
        return BootPerf.measure('globe-shared url resolve', { count: refs.length, level: level }, function () {
         }
            return Promise.all(refs.map(function (ref) {
                return window.EntryStore.resolveFileUrl(ref).catch(function () { return ''; });
            }));
        }).then(function (urls) {
            urls = urls.filter(Boolean);
             /*
            * Globe shared assets are heavy 6K texture sources.  The live
            * NationsGlobe ready contract already waits for the actual Three.js
            * texture path, so decoding the same images here only duplicates work
            * and holds the boot screen.  Keep revision-aware URL resolution in the
            * entry ledger, but make the image warm-up non-blocking.
            */
            BootPerf.mark('globe-shared image prewarm skipped', {
                count: urls.length,
                level: level,
                reason: 'deferred-to-nations-globe-ready-contract'
            });
            window.setTimeout(function () {
                if (!window.EntryStore || typeof window.EntryStore.preloadImages !== 'function') return;
                window.EntryStore.preloadImages(urls, {
                    limit: task.imageLimit == null ? 0 : Number(task.imageLimit),
                    concurrency: Math.max(1, Math.min(16, Number(task.concurrency) || 4)),
                    persistent: false
                }).catch(function () {});
            }, 0);
            return urls;
         });
    }


    function prepareImageAssets(task, level) {
        function getImageDisplayUrl(url) {
        var refs = Array.isArray(task && task.assets) ? task.assets : [];
            var key = String(url || '').trim();
        var full = level === 'full';
             return key ? (imageDisplayUrlCache[key] || key) : '';
        var exposeAs = String(task && task.exposeAs || '').trim();
         }
        if (!refs.length) return Promise.resolve(null);
        return BootPerf.measure('image-assets url resolve', { count: refs.length, exposeAs: exposeAs, level: level }, function () {
             return Promise.all(refs.map(function (ref) {
                return window.EntryStore.resolveFileUrl(ref).catch(function () { return ''; });
            }));
        }).then(function (urls) {
            urls = urls.filter(Boolean);
            if (exposeAs === 'nationsGlobeLoadingGif') {
                window.NationsGlobeLoadingGifRef = refs[0] || '';
                window.NationsGlobeLoadingGifUrl = urls[0] || '';
                window.NationsGlobeLoadingGifFile = 'Gfx-vhs-glitch-001.gif';
            }
            if (!full) return urls;
            return BootPerf.measure('image-assets image prewarm', { count: urls.length, exposeAs: exposeAs, limit: task.imageLimit == null ? 0 : Number(task.imageLimit), concurrency: Math.max(1, Math.min(16, Number(task.concurrency) || 2)) }, function () {
                return window.EntryStore.preloadImages(urls, {
                    limit: task.imageLimit == null ? 0 : Number(task.imageLimit),
                    concurrency: Math.max(1, Math.min(16, Number(task.concurrency) || 2))
                });
            }).then(function () { return urls; });
         });
    }


    function prepareHtmlEntry(task) {
        function normalizeUrlKey(url) {
        var url = String(task && (task.url || task.ref) || '').trim();
            var text = String(url || '').trim();
        if (!url) return Promise.resolve(null);
            var a;
        return window.EntryStore.fetchTextUrl(url, { noStore: !!task.noStore, resourceRef: task.resourceRef || task.ref || task.title || '' });
            if (!text) return '';
    }
            try {
 
                a = document.createElement('a');
    function prepareTask(task, defaultLevel) {
                a.href = text;
        var level = String(task && (task.level || defaultLevel) || 'half').toLowerCase();
                text = a.pathname + (a.search || '');
        var type = String(task && task.type || '').toLowerCase();
            } catch (err) {}
        if (!task || typeof task !== 'object') return Promise.resolve(null);
            try {
        if (type === 'html') return prepareHtmlEntry(task);
                text = decodeURI(text);
        if (type === 'json') return window.EntryStore.fetchJsonRef(task.ref, { noStore: !!task.noStore });
            } catch (err2) {}
        if (type === 'pixel-json') {
            text = text.replace(/([?&])_=[^&]*/g, '$1').replace(/[?&]$/, '');
            return waitForDecorationRuntime().then(function (runtime) {
            text = text.replace(/_/g, '_');
                if (level === 'full' && runtime && typeof runtime.preparePixelCanvas === 'function') {
             return text;
                    return runtime.preparePixelCanvas(task.ref || task.asset);
                }
                return window.EntryStore.fetchJsonRef(task.ref || task.asset);
             });
         }
         }
        if (type === 'decorations') return prepareDecorationSet(task, level);
        if (type === 'nations-era') return prepareNationsEra(task, level);
        if (type === 'globe-shared-assets') return prepareGlobeSharedAssets(task, level);
        if (type === 'image-assets') return prepareImageAssets(task, level);
        return Promise.resolve(null);
    }


    function loadManifest() {
        function fetchTextUrl(url, options) {
        return BootPerf.measure('revision manifest load', {}, function () {
            var key = normalizeUrlKey(url);
             return (window.RevisionManifest && typeof window.RevisionManifest.load === 'function' ? window.RevisionManifest.load() : Promise.resolve(null));
            var cacheKey;
        }).then(function () {
            var resourceRef;
             return BootPerf.measure('entry manifest json fetch', { ref: MANIFEST_TITLE }, function () {
            var resourceKey;
                 return window.EntryStore.fetchJsonRef(MANIFEST_TITLE, { noStore: false });
            var token;
            });
            if (!key) return Promise.reject(new Error('empty text url'));
        }).then(function (manifest) {
            if (textCache[key]) return Promise.resolve(textCache[key].text);
            if (!manifest || typeof manifest !== 'object' || !manifest.version) {
             if (textPromiseCache[key]) return textPromiseCache[key];
                BootPerf.mark('entry manifest fallback', { reason: 'invalid manifest' });
            resourceRef = options && options.resourceRef ? options.resourceRef : (options && options.ref ? options.ref : '');
                 return defaultManifest;
            cacheKey = resourceRef && window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForRef === 'function' ? window.RevisionManifest.cacheKeyForRef(resourceRef, 'text') : '';
             }
            if (!cacheKey && window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForUrl === 'function') cacheKey = window.RevisionManifest.cacheKeyForUrl(url, 'text');
             BootPerf.mark('entry manifest ready', { version: manifest.version });
            resourceKey = resourceRef && window.RevisionManifest && typeof window.RevisionManifest.resourceKeyForRef === 'function' ? window.RevisionManifest.resourceKeyForRef(resourceRef) : ('url:' + key);
            return manifest;
             token = resourceRef && window.RevisionManifest && typeof window.RevisionManifest.tokenForRef === 'function' ? window.RevisionManifest.tokenForRef(resourceRef) : '';
        }).catch(function (err) {
            if (cacheKey && !(options && options.noStore) && window.EntryCache && typeof window.EntryCache.getText === 'function') {
            BootPerf.mark('entry manifest fallback', { reason: err && (err.message || String(err)) || 'load failed' });
                 textPromiseCache[key] = window.EntryCache.getText(cacheKey).then(function (cachedText) {
            return defaultManifest;
                    if (cachedText !== null && cachedText !== undefined) {
        });
                        textCache[key] = { key: key, url: url, text: cachedText, loadedAt: now(), persistent: true };
    }
                        return cachedText;
                    }
                    return fetch(url, {
                        credentials: 'same-origin',
                        cache: 'force-cache'
                    }).then(function (res) {
                        if (!res.ok) throw new Error('HTTP ' + res.status);
                        return res.text();
                    }).then(function (text) {
                        textCache[key] = { key: key, url: url, text: text, loadedAt: now() };
                        window.EntryCache.putText(cacheKey, text, { resourceKey: resourceKey, token: token, kind: 'text', contentType: 'text/html; charset=UTF-8' });
                        return text;
                    });
                });
                 return textPromiseCache[key];
             }
             textPromiseCache[key] = fetch(url, {
                credentials: 'same-origin',
                cache: options && options.noStore ? 'no-store' : 'force-cache'
            }).then(function (res) {
                if (!res.ok) throw new Error('HTTP ' + res.status);
                return res.text();
            }).then(function (text) {
                textCache[key] = { key: key, url: url, text: text, loadedAt: now() };
                return text;
            });
            return textPromiseCache[key];
        }


    function flattenInitialTasks(manifest) {
        function getTextSync(url) {
        var initial = manifest && manifest.initial ? manifest.initial : {};
            var key = normalizeUrlKey(url);
        var full = Array.isArray(initial.full) ? initial.full : [];
            return key && textCache[key] ? textCache[key].text : '';
        var half = Array.isArray(initial.half) ? initial.half : [];
         }
        var tasks = [];
        full.forEach(function (task) {
            task = Object.assign({}, task);
            task.level = task.level || 'full';
            task.blocking = true;
            tasks.push(task);
        });
        half.forEach(function (task) {
            task = Object.assign({}, task);
            task.level = task.level || 'half';
            task.blocking = false;
            tasks.push(task);
         });
        return tasks;
    }


        function setTextUrl(url, text) {
            var key = normalizeUrlKey(url);
            if (!key) return;
            textCache[key] = { key: key, url: url, text: String(text || ''), loadedAt: now() };
        }


    function flattenWarmInitialTasks(tasks) {
        function cacheInfo() {
        var warmed = [];
            return {
        (tasks || []).forEach(function (task) {
                json: Object.keys(jsonCache).length,
            var copy;
                jsonKeys: Object.keys(jsonCache),
            var type = String(task && task.type || '').toLowerCase();
                flags: Object.keys(flagUrlCache).length,
            if (!task || task.blocking === false) return;
                files: Object.keys(fileUrlCache).length,
 
                images: Object.keys(imageReadyCache).length,
            /*
                retainedImages: Object.keys(imageObjectCache).length,
            * Warm boot fast path — 20260708.
                displayImages: Object.keys(imageDisplayUrlCache).length,
            *
                text: Object.keys(textCache).length,
            * Cold boot intentionally performs the expensive work: resolving every flag,
                textKeys: Object.keys(textCache)
            * downloading/decoding images, preparing decoration canvases, and warming shared
            };
            * globe textures.  Once a tab has certified the pack against the current revision
        }
            * manifest, later tabs must not replay that full workload.  They only hydrate the
 
            * small tables needed by the live page and let already-cached image/blob data be
        return {
            * consumed on demand.  This is the missing layer that made second tabs feel almost
            fetchJsonRef: fetchJsonRef,
            * as slow as first tabs even though the string checks were true.
            getJsonSync: getJsonSync,
            */
            setJsonRef: setJsonRef,
             if (type === 'globe-shared-assets') return;
            normalizeRefKey: normalizeRefKey,
             if (type === 'image-assets') return;
             rawUrlForRef: rawUrlForRef,
            copy = Object.assign({}, task);
             revisionUrlForRef: function (ref, ctype) {
            if (type === 'nations-era') copy.level = 'warm';
                var url = rawUrlForRef(ref, ctype);
            else if (type === 'decorations') {
                if (window.RevisionManifest && typeof window.RevisionManifest.addRevisionParam === 'function') {
                 copy.level = 'half';
                    url = window.RevisionManifest.addRevisionParam(url, ref);
                 copy.preparePixels = false;
                 }
             } else if (type === 'pixel-json') copy.level = 'half';
                 return url;
             warmed.push(copy);
             },
         });
            resolveFlagUrls: resolveFlagUrls,
        return warmed;
            setFlagUrl: setFlagUrl,
            getFlagUrl: getFlagUrl,
            resolveFileUrl: resolveFileUrl,
            preloadImageUrl: preloadImageUrl,
            preloadImages: preloadImages,
            isImageReady: isImageReady,
            getImageElement: getImageElement,
            getImageDisplayUrl: getImageDisplayUrl,
            fetchTextUrl: fetchTextUrl,
            getTextSync: getTextSync,
            setTextUrl: setTextUrl,
            stableDirectImageUrl: stableDirectImageUrl,
             cacheInfo: cacheInfo
         };
     }
     }


     function currentInitialPackKey(manifest) {
     window.EntryStore = window.EntryStore || createEntryStore();
        var version = manifest && manifest.version ? String(manifest.version) : BUILD_ID;
        return 'initial-entry-full:' + version;
    }


     function currentInitialPackToken(manifest) {
     function updateBootProgress(done, total, label) {
         var version = manifest && manifest.version ? String(manifest.version) : BUILD_ID;
         var pct = total ? Math.max(0, Math.min(100, Math.round((done / total) * 100))) : 0;
         var revToken = window.RevisionManifest && typeof window.RevisionManifest.manifestToken === 'function' ? window.RevisionManifest.manifestToken(version) : version;
         if (bootProgressNode) bootProgressNode.textContent = pct + '%';
         return revToken;
        if (bootFillNode) bootFillNode.style.width = pct + '%';
         if (bootDetailNode && label) bootDetailNode.textContent = label;
     }
     }


     function isInitialPackWarm(manifest) {
     function adoptBootScreen(node) {
         var key = currentInitialPackKey(manifest);
         if (!node) return null;
         var token = currentInitialPackToken(manifest);
        bootNode = node;
         return !!(window.EntryCache && typeof window.EntryCache.packReady === 'function' && window.EntryCache.packReady(key, token));
         bootStatusNode = bootNode.querySelector('.boot-gate-status');
         bootProgressNode = bootNode.querySelector('.boot-gate-progress');
        bootDetailNode = bootNode.querySelector('.boot-gate-detail');
        bootFillNode = bootNode.querySelector('.boot-gate-meter-fill');
        bootNode.classList.add('is-active');
        bootNode.classList.remove('is-complete');
        return bootNode;
     }
     }


     function markInitialPackWarm(manifest, meta) {
     function ensureBootScreen(options) {
         var key = currentInitialPackKey(manifest);
         var panel;
         var token = currentInitialPackToken(manifest);
        var header;
         if (window.EntryCache && typeof window.EntryCache.setPackReady === 'function') {
        var meter;
            window.EntryCache.setPackReady(key, token, Object.assign({ manifestVersion: manifest && manifest.version || BUILD_ID }, meta || {}));
        var existing;
        }
        var decoLayer;
    }
        var close;
        var previewMode;
        options = options || {};
         previewMode = !!options.preview;
         if (bootNode && bootNode.parentNode) return bootNode;
        if (!document.body) return null;


        if (BOOT_EXCLUDED_PAGE && !previewMode) return null;
        if (!previewMode) activateBootSurface();


    function waitMs(ms) {
        existing = document.getElementById('boot-gate-screen') || (!previewMode && window.__BootGatePrelude && window.__BootGatePrelude.ensure ? window.__BootGatePrelude.ensure() : null);
        return new Promise(function (resolve) { window.setTimeout(resolve, Math.max(0, ms || 0)); });
        if (existing) return adoptBootScreen(existing);
    }


    function waitForBody() {
         bootNode = document.createElement('div');
         if (document.body) return Promise.resolve(document.body);
         bootNode.id = 'boot-gate-screen';
         return new Promise(function (resolve) {
        bootNode.className = 'boot-gate-screen is-active';
            function tick() {
        bootNode.setAttribute('role', 'status');
                if (document.body) return resolve(document.body);
        bootNode.setAttribute('aria-live', 'polite');
                window.setTimeout(tick, 10);
            }
            tick();
        });
    }


    function waitForDomReady() {
         panel = document.createElement('div');
         if (document.readyState !== 'loading') return Promise.resolve();
         panel.className = 'boot-gate-panel';
         return new Promise(function (resolve) {
            document.addEventListener('DOMContentLoaded', resolve, { once: true });
        });
    }


    function waitForAnimationFrames(count) {
         header = document.createElement('div');
         count = Math.max(1, Math.round(count || 1));
         header.className = 'boot-gate-title';
         return new Promise(function (resolve) {
        header.textContent = 'ARCHIVE INITIALIZATION';
            function next(left) {
 
                if (left <= 0) return resolve();
        bootStatusNode = document.createElement('div');
                window.requestAnimationFrame(function () { next(left - 1); });
         bootStatusNode.className = 'boot-gate-status';
            }
        bootStatusNode.textContent = 'Preparing entry systems';
            next(count);
         });
    }


    function waitUntil(predicate, options) {
         meter = document.createElement('div');
         var started = now();
         meter.className = 'boot-gate-meter';
         var timeout = options && options.timeoutMs ? options.timeoutMs : 8000;
         bootFillNode = document.createElement('div');
         var interval = options && options.intervalMs ? options.intervalMs : 60;
        bootFillNode.className = 'boot-gate-meter-fill';
        return new Promise(function (resolve) {
        meter.appendChild(bootFillNode);
            function tick() {
                var result = false;
                try { result = predicate(); } catch (err) { result = false; }
                if (result) return resolve({ ok: true, value: result });
                if (now() - started >= timeout) return resolve({ ok: false, timeout: true });
                window.setTimeout(tick, interval);
            }
            tick();
        });
    }


    function waitForTrackedScripts() {
         bootProgressNode = document.createElement('div');
         var list = (window.EntryScriptLoads || []).slice();
         bootProgressNode.className = 'boot-gate-progress';
         if (!list.length) return Promise.resolve([]);
         bootProgressNode.textContent = '0%';
         return Promise.all(list.map(function (promise) {
            return Promise.resolve(promise).catch(function (err) { return { ok: false, error: err }; });
        }));
    }


    function waitForDocumentSurface() {
         bootDetailNode = document.createElement('div');
         return waitForDomReady().then(function () {
         bootDetailNode.className = 'boot-gate-detail';
            return waitForBody();
         bootDetailNode.textContent = 'loading manifest';
         }).then(function () {
            return waitUntil(function () {
                return document.querySelector('.content-wrapper') && document.querySelector('.liberty-content-main');
            }, { timeoutMs: 8000, intervalMs: 50 });
         });
    }


    function isNationsPageSurface() {
        close = document.createElement('button');
         var page = String(mw && mw.config ? (mw.config.get('wgPageName') || mw.config.get('wgTitle') || '') : '');
         close.type = 'button';
         return !!document.querySelector('.clbi-nations-panel-stack') || /국가[_ ]및[_ ]조합/.test(page);
        close.className = 'boot-gate-close';
    }
        close.setAttribute('aria-label', 'Close boot preview');
        close.textContent = '×';
         close.addEventListener('click', function () { hideBootScreen({ force: true }); });


     function getInitialNationsEra(manifest) {
        decoLayer = document.createElement('div');
         var tasks = flattenInitialTasks(manifest);
        decoLayer.className = 'boot-gate-decoration-layer';
         var i;
        decoLayer.setAttribute('data-decoration-target', 'boot-gate');
         for (i = 0; i < tasks.length; i += 1) {
        decoLayer.setAttribute('aria-hidden', 'true');
             if (tasks[i] && tasks[i].type === 'nations-era' && String(tasks[i].level || '').toLowerCase() === 'full') {
 
                 return String(tasks[i].era || '1950');
        panel.appendChild(header);
        panel.appendChild(bootStatusNode);
        panel.appendChild(meter);
        panel.appendChild(bootProgressNode);
        panel.appendChild(bootDetailNode);
        bootNode.appendChild(decoLayer);
        bootNode.appendChild(panel);
        bootNode.appendChild(close);
        document.body.appendChild(bootNode);
        return bootNode;
    }
 
     function buildLoginUrl() {
         var pageName = String(readConfig('wgPageName', '') || '').trim();
         var params = {};
 
         if (pageName && !isAuthenticationPage() && !isCreateAccountPage()) params.returnto = pageName;
        try {
             if (mw && mw.util && typeof mw.util.getUrl === 'function') {
                 return mw.util.getUrl('Special:UserLogin', params);
             }
             }
         }
         } catch (err) {}
         return '1950';
 
         return '/index.php?title=Special%3AUserLogin' + (params.returnto ? '&returnto=' + encodeURIComponent(params.returnto) : '');
     }
     }


     function waitForNationsPanelReady(era) {
     function ensureLoginGateAction(panel) {
         return BootPerf.measure('wait nations panel api', { era: era }, function () {
         var copy;
            return waitUntil(function () { return window.NationsPanel && typeof window.NationsPanel.whenEraReady === 'function'; }, {
        var action;
                timeoutMs: 8000,
 
                intervalMs: 50
        if (loginGateActionNode && loginGateActionNode.parentNode) return loginGateActionNode;
            });
         loginGateActionNode = document.createElement('div');
         }).then(function (result) {
        loginGateActionNode.className = 'boot-gate-login';
            if (!result.ok || !window.NationsPanel || typeof window.NationsPanel.whenEraReady !== 'function') return null;
 
            return BootPerf.measure('wait nations panel era ready', { era: era }, function () {
        copy = document.createElement('div');
                return window.NationsPanel.whenEraReady(era, { timeoutMs: 15000 }).catch(function () { return null; });
        copy.className = 'boot-gate-login-copy';
            });
         copy.textContent = 'SIGN IN TO ENTER THE WIKI.';
         }).then(function () {
 
            return BootPerf.measure('wait nations panel dom ready', { era: era }, function () {
        action = document.createElement('a');
                return waitUntil(function () {
        action.className = 'boot-gate-login-action';
                    var panel = document.querySelector('.clbi-nations-era-content[data-era-content="' + era + '"] .clbi-nations-tabpanel[data-nation-list-source="1"]') ||
        action.href = buildLoginUrl();
                        document.querySelector('.clbi-nations-tabpanel[data-nation-list-source="1"]');
        action.textContent = 'LOGIN';
                    return panel && panel.classList.contains('clbi-nations-list-json-ready') && panel.getAttribute('data-nation-list-year-loaded') === String(era);
        action.setAttribute('role', 'button');
                }, { timeoutMs: 15000, intervalMs: 80 });
 
            });
        loginGateActionNode.appendChild(copy);
         });
        loginGateActionNode.appendChild(action);
        panel.appendChild(loginGateActionNode);
         return loginGateActionNode;
     }
     }


     function waitForNationsGlobeReady(options) {
     function showLoginGate() {
         var globe = document.querySelector('.clbi-nations-globe-window[data-nations-globe], [data-nations-globe="real-world"]');
         var node = ensureBootScreen();
         var soft;
        var panel;
         var timeout;
        var title;
        var action;
 
        if (!node || !requiresLoginGate()) return false;
        activateBootSurface();
        loginGateLocked = true;
        node.classList.remove('is-complete');
        node.classList.add('is-active', 'is-login-required');
        node.setAttribute('role', 'dialog');
         node.setAttribute('aria-modal', 'true');
         node.setAttribute('aria-live', 'off');


         options = options || {};
         panel = node.querySelector('.boot-gate-panel');
         soft = !!options.soft;
         title = node.querySelector('.boot-gate-title');
         timeout = Number(options.timeoutMs || (soft ? 450 : 30000));
         if (title) title.textContent = 'ACCOUNT AUTHENTICATION';
        if (bootStatusNode) bootStatusNode.textContent = 'LOGIN REQUIRED';
        if (bootDetailNode) bootDetailNode.textContent = '';
        if (bootProgressNode) bootProgressNode.textContent = '';
        if (bootFillNode) bootFillNode.style.width = '100%';


         if (!globe) {
        action = panel ? ensureLoginGateAction(panel).querySelector('.boot-gate-login-action') : null;
             BootPerf.mark('wait nations globe skipped', { reason: 'no globe node', soft: soft });
         if (action) {
            return Promise.resolve(null);
             action.href = buildLoginUrl();
            window.requestAnimationFrame(function () {
                try { action.focus({ preventScroll: true }); }
                catch (err) { try { action.focus(); } catch (ignore) {} }
            });
         }
         }
        return true;
    }


         return BootPerf.measure(soft ? 'wait nations globe warm attach' : 'wait nations globe ready contract', { soft: soft, timeoutMs: timeout }, function () {
    function hideBootScreen(options) {
            if (soft) {
         var node = bootNode || document.getElementById('boot-gate-screen');
                /*
        options = options || {};
                Warm-tab policy:
        if (loginGateLocked && requiresLoginGate() && !options.force) return false;
                Raw globe images are already revision-checked and blob-cached by EntryCache,
        if (!node) {
                but WebGL scene creation, GPU upload, topojson parsing, and per-tab Three.js
            document.documentElement.classList.remove('boot-gate-active');
                objects cannot be shared across browser tabs. Waiting for the full is-ready
            if (document.body) document.body.classList.remove('boot-gate-active');
                contract here makes a warm tab slower than the first tab.  In warm mode the
            return true;
                initial gate only waits until the globe consumer has been attached, then the
        }
                globe finishes its own per-tab hydrate without holding the whole page hostage.
        node.classList.add('is-complete');
                */
        node.classList.remove('is-active');
                return waitUntil(function () {
        window.setTimeout(function () {
                    var node = document.querySelector('.clbi-nations-globe-window[data-nations-globe], [data-nations-globe="real-world"]');
            if (node.parentNode) node.parentNode.removeChild(node);
                    if (!node) return false;
            if (bootNode === node) bootNode = null;
                    return node.getAttribute('data-nations-globe-ready') === '1' ||
            loginGateActionNode = null;
                        !!node.CLBI_NationsGlobeInstance ||
            document.documentElement.classList.remove('boot-gate-active');
                        !!node.querySelector('.clbi-nations-globe-stage') ||
            if (document.body) document.body.classList.remove('boot-gate-active');
                        node.classList.contains('is-ready') ||
        }, 240);
                        node.classList.contains('has-error');
        return true;
                }, { timeoutMs: timeout, intervalMs: 40 });
    }
 
    function collectFlagsFromNationPayload(payload) {
        var files = [];
        function add(value) {
            if (!value) return;
            if (typeof value === 'string') {
                files.push(value);
                return;
             }
             }
            if (typeof value === 'object') files.push(value.file || value.flag_file || value.flag || value.flag_title || '');
        }
        function scanItem(item) {
            if (!item || typeof item !== 'object') return;
            if (Array.isArray(item.flags)) item.flags.forEach(add);
            add(item.flag_file || item.flag || item.flag_title || '');
        }
        (payload && payload.continents || []).forEach(function (continent) {
            (continent.regions || []).forEach(function (region) {
                (region.items || []).forEach(scanItem);
            });
        });
        return unique(files);
    }


            return waitUntil(function () {
    function collectFlagsFromLinkMap(payload) {
                var node = document.querySelector('.clbi-nations-globe-window[data-nations-globe], [data-nations-globe="real-world"]');
        var files = [];
                return node && (node.classList.contains('is-ready') || node.classList.contains('has-error'));
        var source = payload && payload.items ? payload.items : {};
             }, { timeoutMs: timeout, intervalMs: 100 });
        Object.keys(source || {}).forEach(function (key) {
            var item = source[key];
            if (!item || typeof item !== 'object') return;
             files.push(item.flag_file || item.flag || item.flag_title || '');
         });
         });
        return unique(files);
     }
     }


     function waitForDecorationsReady(options) {
     function prewarmImages(urls, limit) {
        options = options || {};
         return window.EntryStore.preloadImages(urls, {
         return waitForDecorationRuntime().then(function (runtime) {
             limit: Number(limit) > 0 ? Number(limit) : 0,
             if (!runtime) return null;
             concurrency: 16,
            if (options.warm) {
             persistent: false
                /*
                * Warm tab contract — 20260708.
                *
                * The decoration registry and pixel canvases were prepared by the cold tab.
                * Calling reload() here re-reads and re-syncs the decoration layer during the
                * boot gate, which is visible as a pointless delay.  A warm tab only needs the
                * current visibility pass so boot can release quickly and editing/preview tools
                * remain responsive.
                */
                try {
                    if (typeof runtime.updateVisibility === 'function') runtime.updateVisibility(document);
                    else if (typeof runtime.sync === 'function') runtime.sync();
                } catch (err) {}
                return waitForAnimationFrames(1);
             }
            if (typeof runtime.reload !== 'function') return null;
            return runtime.reload().catch(function () { return null; }).then(function () {
                return waitForAnimationFrames(2);
             });
         });
         });
     }
     }


     function waitForCurrentEntrySurface(manifest, options) {
     function getDecorationRuntime() {
         var era = getInitialNationsEra(manifest);
         return window.Decorations || window.CLBI_DECORATIONS || null;
        var warmPack;
    }


        options = options || {};
    function waitForDecorationRuntime() {
        warmPack = !!options.warmPack;
        return new Promise(function (resolve) {
 
            var tries = 0;
        if (!isNationsPageSurface()) {
             function tick() {
            return waitForDecorationsReady({ warm: !!warmPack }).then(function () { return waitForAnimationFrames(1); });
                 var runtime = getDecorationRuntime();
        }
                if (runtime) return resolve(runtime);
        if (bootStatusNode) bootStatusNode.textContent = warmPack ? 'Hydrating current information surface from warm cache' : 'Preparing current information surface';
                 tries += 1;
        if (bootDetailNode) bootDetailNode.textContent = 'waiting for nations ' + era + ' ready contract';
                 if (tries > 40) return resolve(null);
        return waitForNationsPanelReady(era)
                 window.setTimeout(tick, 25);
             .then(function () {
             }
                 if (warmPack) {
             tick();
                    if (bootDetailNode) bootDetailNode.textContent = 'attaching globe warm consumer';
        });
                    return waitForNationsGlobeReady({ soft: true, timeoutMs: 450 });
                 }
                 if (bootDetailNode) bootDetailNode.textContent = 'waiting for globe ready contract';
                return waitForNationsGlobeReady();
            })
            .then(function () {
                 if (bootDetailNode) bootDetailNode.textContent = 'waiting for decoration surface';
                return waitForDecorationsReady({ warm: warmPack });
             })
             .then(function () { return waitForAnimationFrames(warmPack ? 1 : 2); });
     }
     }


     function runInitialLoad(options) {
     function matchesDecorationEntry(entry, filter) {
         var done = 0;
         var era = String(filter && filter.era || '').trim();
         var manifestRef;
         var page = String(filter && filter.page || '').trim();
         var tasks;
         var entryPage = String(entry && entry.page || '').replace(/_/g, ' ').trim();
         var bootOptions;
         if (!entry || typeof entry !== 'object') return false;
         var timedOut = false;
         if (page && entryPage && entryPage !== page) return false;
         var warmPack = false;
         if (era && String(entry.era || '').trim() && String(entry.era || '').trim() !== era) return false;
        return true;
    }


         options = options || {};
    function prepareDecorationSet(task, level) {
        bootStartTime = window.__BootGatePrelude && window.__BootGatePrelude.startTime ? window.__BootGatePrelude.startTime : now();
         var ref = task.ref || 'MediaWiki:Decorations.json';
        activateBootSurface();
        return window.EntryStore.fetchJsonRef(ref, { noStore: !!task.noStore }).then(function (registry) {
        ensureBootScreen();
            var list = registry && Array.isArray(registry.decorations) ? registry.decorations : [];
        updateBootProgress(0, 1, 'loading entry manifest');
            var pixelRefs = [];
            list.forEach(function (entry) {
                var type = String(entry && entry.assetType || '').toLowerCase();
                var asset = String(entry && (entry.asset || entry.src) || '').trim();
                if (!asset) return;
                if (type !== 'pixel-json' && !/\.json(?:[?#].*)?$/i.test(asset)) return;
                if (!matchesDecorationEntry(entry, task)) return;
                pixelRefs.push(asset);
            });
            if (level !== 'full' || task.preparePixels === false || !pixelRefs.length) return registry;
            return waitForDecorationRuntime().then(function (runtime) {
                if (!runtime || typeof runtime.preparePixelCanvas !== 'function') {
                    return Promise.all(pixelRefs.map(function (pixelRef) {
                        return window.EntryStore.fetchJsonRef(pixelRef).catch(function () { return null; });
                    })).then(function () { return registry; });
                }
                return Promise.all(pixelRefs.map(function (pixelRef) {
                    return runtime.preparePixelCanvas(pixelRef).catch(function () { return null; });
                })).then(function () { return registry; });
            });
        });
    }


        manifestRef = loadManifest().then(function (manifest) {
    function prepareNationsEra(task, level) {
            var minDisplay;
        var era = String(task.era || '1950');
            var totalSteps;
        var listRef = task.listRef || ('MediaWiki:' + era + '_Nation_List.json');
            var maxBlockingMs;
        var linkRef = task.linkMapRef || ('MediaWiki:' + era + '_Nation_Link_Map.json');
            var timeoutHandle;
        var jsonPhaseId = BootPerf.start('nations-era json fetch', { era: era, level: level, listRef: listRef, linkRef: linkRef });
            bootOptions = manifest.boot || {};
        var listPromise = window.EntryStore.fetchJsonRef(listRef).catch(function () { return null; });
            warmPack = isInitialPackWarm(manifest);
        var linkPromise = window.EntryStore.fetchJsonRef(linkRef).catch(function () { return null; });
            minDisplay = options.minDisplayMs || (warmPack ? (bootOptions.cachedMinDisplayMs || 220) : (bootOptions.minDisplayMs || 950));
            tasks = flattenInitialTasks(manifest);
            if (!tasks.length) tasks = flattenInitialTasks(defaultManifest);
            if (warmPack) tasks = flattenWarmInitialTasks(tasks);


             /*
        return Promise.all([listPromise, linkPromise]).then(function (results) {
            Full/half contract:
            BootPerf.end(jsonPhaseId, { ok: true });
            These manifest tasks only prepare data assets.  The gate is not allowed to open
            var files;
            until the current page surface has consumed that data and reported a real ready
            var flagUrls;
            state belowDo not reintroduce localStorage-only skip logic here; a cached
            if (level !== 'full' && level !== 'warm') return results;
            version number is not the same as current-tab readiness.
            files = unique(collectFlagsFromNationPayload(results[0]).concat(collectFlagsFromLinkMap(results[1])));
            */
             return BootPerf.measure('nations-era flag url resolve', { era: era, count: files.length }, function () {
            totalSteps = tasks.length + 4;
                return window.EntryStore.resolveFlagUrls(files);
            updateBootProgress(0, totalSteps, warmPack ? 'hydrating warm entry cache' : 'starting entry packs');
            }).then(function () {
                if (level === 'warm') {
                    /*
                    * Warm tab contract — 20260708.
                    *
                    * A previous tab already stored the same-revision flag URL and image
                    * blobs.  Re-decoding every flag here makes the second tab feel as slow
                    * as the first one.  In warm mode we only hydrate the flag URL table from
                    * EntryCache so NationsPanel can render stable URLs immediately; image
                    * decode remains demand-driven by the live panel instead of blocking the
                    * boot screen.
                    */
                    return results;
                }
                flagUrls = files.map(function (file) { return window.EntryStore.getFlagUrl(file); }).filter(Boolean);
                /*
                * 20260710: Flag URLs are part of the entry contract, but decoding every
                * flag image is not.  The 1950 list has more than 150 flags, and waiting
                * for all image decodes kept the public boot gate open for several seconds.
                * Keep revision-aware URLs ready for the panel, then let the browser load
                * the actual images from the live DOMA low-priority background warm-up
                * may run after the boot gate has opened, so it never competes with the
                * current entry surface or the globe ready contract.
                */
                BootPerf.mark('nations-era flag image prewarm skipped', {
                    era: era,
                    count: flagUrls.length,
                    limit: task.flagLimit == null ? 0 : Number(task.flagLimit),
                    reason: 'deferred-after-boot-gate'
                });
                if (flagUrls.length && task.deferFlagImages !== false) {
                    deferredEntryWarmups.push(function () {
                        return BootPerf.measure('deferred nations-era flag image prewarm', {
                            era: era,
                            count: flagUrls.length,
                            limit: task.flagLimit == null ? 0 : Number(task.flagLimit)
                        }, function () {
                            return prewarmImages(flagUrls, task.flagLimit == null ? 0 : Number(task.flagLimit));
                        });
                    });
                }
                return results;
            });
        });
    }


            return new Promise(function (resolve) {
    function prepareGlobeSharedAssets(task, level) {
                maxBlockingMs = Number(options.maxBlockingMs || bootOptions.maxBlockingMs || 30000);
        var refs = Array.isArray(task && task.assets) ? task.assets : [];
                timeoutHandle = window.setTimeout(function () {
        if (!refs.length) return Promise.resolve(null);
                    timedOut = true;
        return BootPerf.measure('globe-shared url resolve', { count: refs.length, level: level }, function () {
                    resolve();
            return Promise.all(refs.map(function (ref) {
                }, maxBlockingMs);
                 return window.EntryStore.resolveFileUrl(ref).catch(function () { return ''; });
 
            }));
                Promise.all(tasks.map(function (task) {
        }).then(function (urls) {
                    var label = task.label || task.id || task.type || 'entry task';
            urls = urls.filter(Boolean);
                    return BootPerf.measure('boot task: ' + label, { id: task.id || '', type: task.type || '', level: task.level || task.level === 0 ? task.level : '' }, function () {
            /*
                        return prepareTask(task, task.level);
            * Globe shared assets are heavy 6K texture sources. The live
                    }).catch(function () {
            * NationsGlobe ready contract already waits for the actual Three.js
                        return null;
            * texture path, so decoding the same images here only duplicates work
                    }).then(function () {
            * and holds the boot screen. Keep revision-aware URL resolution in the
                        done += 1;
            * entry ledger, but make the image warm-up non-blocking.
                        updateBootProgress(done, totalSteps, label);
            */
                    });
             BootPerf.mark('globe-shared image prewarm skipped', {
                 })).then(function () {
                 count: urls.length,
                    updateBootProgress(++done, totalSteps, 'loading subsystem scripts');
                 level: level,
                    return BootPerf.measure('wait tracked subsystem scripts', { count: (window.EntryScriptLoads || []).length }, function () { return waitForTrackedScripts(); });
                reason: 'deferred-to-nations-globe-ready-contract'
                }).then(function () {
                    updateBootProgress(++done, totalSteps, 'waiting for document shell');
                    return BootPerf.measure('wait document shell', {}, function () { return waitForDocumentSurface(); });
                }).then(function () {
                    updateBootProgress(++done, totalSteps, 'waiting for current entry surface');
                    return BootPerf.measure('wait current entry surface', { warmPack: warmPack }, function () { return waitForCurrentEntrySurface(manifest, { warmPack: warmPack }); });
                }).then(function () {
                    updateBootProgress(totalSteps, totalSteps, warmPack ? 'warm entry surface complete' : 'entry surface complete');
                    window.clearTimeout(timeoutHandle);
                    resolve();
                }).catch(function () {
                    window.clearTimeout(timeoutHandle);
                    resolve();
                });
            }).then(function () {
                var elapsed = now() - bootStartTime;
                var wait = Math.max(0, minDisplay - elapsed);
                return waitMs(wait);
             }).then(function () {
                localStorage.setItem(READY_KEY, String(manifest.version));
                if (!timedOut) markInitialPackWarm(manifest, { warmSource: warmPack ? 'cache-hit' : 'cold-build' });
                 if (bootStatusNode) bootStatusNode.textContent = timedOut ? 'Entry surface ready with deferred items' : (warmPack ? 'Entry surface ready from warm cache' : 'Entry surface ready');
                updateBootProgress(tasks.length + 4, tasks.length + 4, timedOut ? 'timeout: continuing deferred loading' : (warmPack ? 'warm cache complete' : 'complete'));
                 BootPerf.mark('boot gate complete', { timedOut: timedOut, warmPack: warmPack, manifestVersion: manifest && manifest.version || '' });
                BootPerf.print();
                window.setTimeout(hideBootScreen, 120);
                return manifest;
             });
             });
            window.setTimeout(function () {
                if (!window.EntryStore || typeof window.EntryStore.preloadImages !== 'function') return;
                window.EntryStore.preloadImages(urls, {
                    limit: task.imageLimit == null ? 0 : Number(task.imageLimit),
                    concurrency: Math.max(1, Math.min(16, Number(task.concurrency) || 4)),
                    persistent: false
                }).catch(function () {});
            }, 0);
            return urls;
         });
         });
        return manifestRef;
     }
     }


     function startBoot(options) {
     function prepareImageAssets(task, level) {
         if (BOOT_EXCLUDED_PAGE && !(options && options.force)) {
         var refs = Array.isArray(task && task.assets) ? task.assets : [];
            hideBootScreen();
        var full = level === 'full';
            return Promise.resolve({ skipped: true, reason: 'developer-or-editing-page' });
        var exposeAs = String(task && task.exposeAs || '').trim();
        }
        if (!refs.length) return Promise.resolve(null);
         if (hasBootParam('0') && !(options && options.force)) return Promise.resolve(null);
        return BootPerf.measure('image-assets url resolve', { count: refs.length, exposeAs: exposeAs, level: level }, function () {
        if (bootStarted && bootPromise && !(options && options.force)) return bootPromise;
            return Promise.all(refs.map(function (ref) {
        bootStarted = true;
                return window.EntryStore.resolveFileUrl(ref).catch(function () { return ''; });
        bootPromise = runInitialLoad(options || {});
            }));
        return bootPromise;
         }).then(function (urls) {
    }
            urls = urls.filter(Boolean);
 
            if (exposeAs === 'nationsGlobeLoadingGif') {
    function resetBoot() {
                window.NationsGlobeLoadingGifRef = refs[0] || '';
        localStorage.removeItem(READY_KEY);
                window.NationsGlobeLoadingGifUrl = urls[0] || '';
        bootStarted = false;
                window.NationsGlobeLoadingGifFile = 'Gfx-vhs-glitch-001.gif';
         bootPromise = null;
            }
            if (!full) return urls;
            return BootPerf.measure('image-assets image prewarm', { count: urls.length, exposeAs: exposeAs, limit: task.imageLimit == null ? 0 : Number(task.imageLimit), concurrency: Math.max(1, Math.min(16, Number(task.concurrency) || 2)) }, function () {
                return window.EntryStore.preloadImages(urls, {
                    limit: task.imageLimit == null ? 0 : Number(task.imageLimit),
                    concurrency: Math.max(1, Math.min(16, Number(task.concurrency) || 2))
                });
            }).then(function () { return urls; });
         });
     }
     }


     /*
     function prepareHtmlEntry(task) {
    BootGate intentionally has no SPA hold/release API.
        var url = String(task && (task.url || task.ref) || '').trim();
    Initial boot is the only blocking phase; later SPA routes must consume prepared
        if (!url) return Promise.resolve(null);
    EntryStore artifacts without reopening the loading surface.
        return window.EntryStore.fetchTextUrl(url, { noStore: !!task.noStore, resourceRef: task.resourceRef || task.ref || task.title || '' });
     */
     }


     function buildBootReport() {
     function prepareTask(task, defaultLevel) {
         return {
         var level = String(task && (task.level || defaultLevel) || 'half').toLowerCase();
            build: BUILD_ID,
        var type = String(task && task.type || '').toLowerCase();
            state: {
        if (!task || typeof task !== 'object') return Promise.resolve(null);
                started: bootStarted,
        if (type === 'html') return prepareHtmlEntry(task);
                excludedPage: BOOT_EXCLUDED_PAGE,
        if (type === 'json') return window.EntryStore.fetchJsonRef(task.ref, { noStore: !!task.noStore });
                hasNode: !!((bootNode && bootNode.parentNode) || document.getElementById('boot-gate-screen')),
        if (type === 'pixel-json') {
                htmlActive: !!(document.documentElement && document.documentElement.classList.contains('boot-gate-active')),
             return waitForDecorationRuntime().then(function (runtime) {
                bodyActive: !!(document.body && document.body.classList.contains('boot-gate-active'))
                if (level === 'full' && runtime && typeof runtime.preparePixelCanvas === 'function') {
            },
                    return runtime.preparePixelCanvas(task.ref || task.asset);
            store: window.EntryStore && window.EntryStore.cacheInfo ? window.EntryStore.cacheInfo() : null,
                }
             bootPerf: window.BootPerf && typeof window.BootPerf.summary === 'function' ? window.BootPerf.summary() : null,
                return window.EntryStore.fetchJsonRef(task.ref || task.asset);
            revisionManifest: window.RevisionManifest && typeof window.RevisionManifest.status === 'function' ? window.RevisionManifest.status() : null,
            });
            nations: window.NationsPanel && typeof window.NationsPanel.diagnostics === 'function' ? window.NationsPanel.diagnostics() : null,
        }
            decorations: window.Decorations && typeof window.Decorations.diagnostics === 'function' ? window.Decorations.diagnostics() : null
        if (type === 'decorations') return prepareDecorationSet(task, level);
         };
        if (type === 'nations-era') return prepareNationsEra(task, level);
        if (type === 'globe-shared-assets') return prepareGlobeSharedAssets(task, level);
        if (type === 'image-assets') return prepareImageAssets(task, level);
         return Promise.resolve(null);
     }
     }


     window.EntryLoader = window.EntryLoader || {
     function loadManifest() {
        loadManifest: loadManifest,
        return BootPerf.measure('revision manifest load', {}, function () {
        prepareTask: prepareTask,
            return (window.RevisionManifest && typeof window.RevisionManifest.load === 'function' ? window.RevisionManifest.load() : Promise.resolve(null));
         prepareNationsEra: prepareNationsEra,
        }).then(function () {
         prepareDecorationSet: prepareDecorationSet,
            return BootPerf.measure('entry manifest json fetch', { ref: MANIFEST_TITLE }, function () {
        prepareGlobeSharedAssets: prepareGlobeSharedAssets,
                return window.EntryStore.fetchJsonRef(MANIFEST_TITLE, { noStore: false });
        prepareImageAssets: prepareImageAssets,
            });
        prepareHtmlEntry: prepareHtmlEntry,
         }).then(function (manifest) {
         runInitialLoad: runInitialLoad
            if (!manifest || typeof manifest !== 'object' || !manifest.version) {
     };
                BootPerf.mark('entry manifest fallback', { reason: 'invalid manifest' });
                return defaultManifest;
            }
            BootPerf.mark('entry manifest ready', { version: manifest.version });
            return manifest;
         }).catch(function (err) {
            BootPerf.mark('entry manifest fallback', { reason: err && (err.message || String(err)) || 'load failed' });
            return defaultManifest;
         });
     }


     function showBootPreview(options) {
     function flattenInitialTasks(manifest) {
         var node;
         var initial = manifest && manifest.initial ? manifest.initial : {};
        options = options || {};
         var full = Array.isArray(initial.full) ? initial.full : [];
         /*
        var half = Array.isArray(initial.half) ? initial.half : [];
        * Boot preview is a design/editing surface, not a real boot gate.
         var tasks = [];
        * The earlier preview reused activateBootSurface(), which applied
         full.forEach(function (task) {
        * html.boot-gate-active and hid the entire wiki shell, including
            task = Object.assign({}, task);
        * DevTools. That made it impossible to edit loading-screen
            task.level = task.level || 'full';
        * decorations while previewing them. Keep the real first-entry gate
            task.blocking = true;
        * full-screen, but make preview a small non-blocking surface below the
            tasks.push(task);
        * DevTools z-index so the owner can keep using the editor.
        });
        */
         half.forEach(function (task) {
         node = ensureBootScreen({ preview: true });
            task = Object.assign({}, task);
         if (!node) return null;
            task.level = task.level || 'half';
        node.classList.add('is-preview');
             task.blocking = false;
        if (bootStatusNode) bootStatusNode.textContent = options.status || 'Loading screen preview';
            tasks.push(task);
         updateBootProgress(Number(options.progress || 64), 100, options.detail || 'preview mode: no entry tasks are running');
         });
        try {
         return tasks;
             if (window.Decorations && typeof window.Decorations.sync === 'function') window.Decorations.sync();
         } catch (err) {}
         return node;
     }
     }


    window.BootGate = window.BootGate || {
        version: BUILD_ID,
        start: startBoot,
        show: function (options) {
            options = options || {};
            options.force = true;
            resetBoot();
            return startBoot(options);
        },
        reset: resetBoot,
        hide: hideBootScreen,
        preview: showBootPreview,
        report: buildBootReport,
        state: function () {
            return {
                started: bootStarted,
                hasNode: !!((bootNode && bootNode.parentNode) || document.getElementById('boot-gate-screen')),
                htmlActive: !!(document.documentElement && document.documentElement.classList.contains('boot-gate-active')),
                bodyActive: !!(document.body && document.body.classList.contains('boot-gate-active')),
                prelude: !!window.__BootGatePrelude,
                store: window.EntryStore && window.EntryStore.cacheInfo ? window.EntryStore.cacheInfo() : null,
                revisionManifest: window.RevisionManifest && typeof window.RevisionManifest.status === 'function' ? window.RevisionManifest.status() : null
            };
        }
    };


     function prime() {
     function flattenWarmInitialTasks(tasks) {
         if (BOOT_EXCLUDED_PAGE) {
         var warmed = [];
             hideBootScreen();
        (tasks || []).forEach(function (task) {
             return;
             var copy;
        }
            var type = String(task && task.type || '').toLowerCase();
        activateBootSurface();
             if (!task || task.blocking === false) return;
        waitForBody().then(function () {
 
             ensureBootScreen();
            /*
             return waitForAnimationFrames(1);
            * Warm boot fast path — 20260708.
        }).then(function () {
            *
             startBoot();
            * Cold boot intentionally performs the expensive work: resolving every flag,
            * downloading/decoding images, preparing decoration canvases, and warming shared
            * globe textures.  Once a tab has certified the pack against the current revision
            * manifest, later tabs must not replay that full workload.  They only hydrate the
            * small tables needed by the live page and let already-cached image/blob data be
            * consumed on demand.  This is the missing layer that made second tabs feel almost
            * as slow as first tabs even though the string checks were true.
            */
            if (type === 'globe-shared-assets') return;
            if (type === 'image-assets') return;
            copy = Object.assign({}, task);
             if (type === 'nations-era') copy.level = 'warm';
             else if (type === 'decorations') {
                copy.level = 'half';
                copy.preparePixels = false;
            } else if (type === 'pixel-json') copy.level = 'half';
             warmed.push(copy);
         });
         });
        return warmed;
     }
     }


     waitForBody().then(function () {
     function currentInitialPackKey(manifest) {
         if (!BOOT_EXCLUDED_PAGE) ensureBootScreen();
         var version = manifest && manifest.version ? String(manifest.version) : BUILD_ID;
         else hideBootScreen();
         return 'initial-entry-full:' + version;
    });
     }
     window.setTimeout(prime, 0);
})(window, document, window.mediaWiki || window.mw);


    function currentInitialPackToken(manifest) {
        var version = manifest && manifest.version ? String(manifest.version) : BUILD_ID;
        var revToken = window.RevisionManifest && typeof window.RevisionManifest.manifestToken === 'function' ? window.RevisionManifest.manifestToken(version) : version;
        return revToken;
    }


loadClbiRawScript('MediaWiki:DevTools.js');
    function isInitialPackWarm(manifest) {
loadClbiRawScript('MediaWiki:CategoryNav.js');
        var key = currentInitialPackKey(manifest);
loadClbiRawScript('MediaWiki:NationsPanel.js');
        var token = currentInitialPackToken(manifest);
loadClbiRawScript('MediaWiki:NationsGlobe.js');
        return !!(window.EntryCache && typeof window.EntryCache.packReady === 'function' && window.EntryCache.packReady(key, token));
 
/* CLBI safety guard: adaptive reset functions must exist before shell metric callbacks run. */
function resetLeftRecentAdaptiveState() {
    var list = document.getElementById('clbi-left-recent-list');
    var newsBox = list ? list.closest('.clbi-left-news-box') : null;
    var items = list ? Array.prototype.slice.call(list.querySelectorAll('.news-recent-item')) : [];
 
    if (newsBox) {
        newsBox.classList.remove('is-adaptive-constrained');
        newsBox.style.removeProperty('--adaptive-news-h');
     }
     }


     if (list) {
     function markInitialPackWarm(manifest, meta) {
         list.classList.remove('is-adaptive-faded');
         var key = currentInitialPackKey(manifest);
         list.removeAttribute('data-adaptive-limit');
         var token = currentInitialPackToken(manifest);
         list.style.removeProperty('--adaptive-recent-h');
         if (window.EntryCache && typeof window.EntryCache.setPackReady === 'function') {
            window.EntryCache.setPackReady(key, token, Object.assign({ manifestVersion: manifest && manifest.version || BUILD_ID }, meta || {}));
        }
     }
     }


    items.forEach(function (item) {
        item.classList.remove('is-adaptive-hidden');
    });
}


function resetLeftBillboardAdaptiveState() {
    function waitMs(ms) {
    var box = document.querySelector('#clbi-left-sidebar .left-billboard-box');
        return new Promise(function (resolve) { window.setTimeout(resolve, Math.max(0, ms || 0)); });
    }


     if (!box) return;
     function waitForBody() {
        if (document.body) return Promise.resolve(document.body);
        return new Promise(function (resolve) {
            function tick() {
                if (document.body) return resolve(document.body);
                window.setTimeout(tick, 10);
            }
            tick();
        });
    }


     box.classList.remove('is-left-ad-title-only', 'is-left-ad-extended');
     function waitForDomReady() {
    box.style.removeProperty('--left-billboard-h');
        if (document.readyState !== 'loading') return Promise.resolve();
    box.style.removeProperty('--left-billboard-finish-h');
        return new Promise(function (resolve) {
}
            document.addEventListener('DOMContentLoaded', resolve, { once: true });
        });
    }


window.resetLeftRecentAdaptiveState = resetLeftRecentAdaptiveState;
    function waitForAnimationFrames(count) {
window.resetLeftBillboardAdaptiveState = resetLeftBillboardAdaptiveState;
        count = Math.max(1, Math.round(count || 1));
        return new Promise(function (resolve) {
            function next(left) {
                if (left <= 0) return resolve();
                window.requestAnimationFrame(function () { next(left - 1); });
            }
            next(count);
        });
    }


loadClbiRawScript('MediaWiki:AnecdoteViewer.js');
    function waitUntil(predicate, options) {
        var started = now();
        var timeout = options && options.timeoutMs ? options.timeoutMs : 8000;
        var interval = options && options.intervalMs ? options.intervalMs : 60;
        return new Promise(function (resolve) {
            function tick() {
                var result = false;
                try { result = predicate(); } catch (err) { result = false; }
                if (result) return resolve({ ok: true, value: result });
                if (now() - started >= timeout) return resolve({ ok: false, timeout: true });
                window.setTimeout(tick, interval);
            }
            tick();
        });
    }


    function waitForTrackedScripts() {
        var list = (window.EntryScriptLoads || []).slice();
        if (!list.length) return Promise.resolve([]);
        return Promise.all(list.map(function (promise) {
            return Promise.resolve(promise).catch(function (err) { return { ok: false, error: err }; });
        }));
    }


(function () {
    function waitForDocumentSurface() {
    'use strict';
        return waitForDomReady().then(function () {
            return waitForBody();
        }).then(function () {
            return waitUntil(function () {
                return document.querySelector('.content-wrapper') && document.querySelector('.liberty-content-main');
            }, { timeoutMs: 8000, intervalMs: 50 });
        });
    }


     var SYSTEM_TITLE_NAMESPACES = {
     function isNationsPageSurface() {
         '-1': true,
         var page = String(mw && mw.config ? (mw.config.get('wgPageName') || mw.config.get('wgTitle') || '') : '');
        '4': true,
         return !!document.querySelector('.clbi-nations-panel-stack') || /(?:^|[_ ])시대(?:$|[_ ])/.test(page) || /(?:^|[_ ])Era(?:$|[_ ])/i.test(page);
        '5': true,
        '6': true,
        '7': true,
        '8': true,
        '9': true,
        '10': true,
        '11': true,
        '12': true,
        '13': true,
        '14': true,
        '15': true,
        '828': true,
        '829': true
    };
 
    function normalizePageNameForShell(value) {
         return String(value || '')
            .split('?')[0]
            .replace(/^\/index\.php\//, '')
            .replace(/_/g, ' ')
            .trim();
     }
     }


     function readCurrentPageNameForShell() {
     function getInitialNationsEra(manifest) {
         var pageName = mw.config.get('wgPageName') || '';
         var tasks = flattenInitialTasks(manifest);
 
        var i;
        if (pageName) {
        for (i = 0; i < tasks.length; i += 1) {
            return normalizePageNameForShell(pageName);
            if (tasks[i] && tasks[i].type === 'nations-era' && String(tasks[i].level || '').toLowerCase() === 'full') {
                return String(tasks[i].era || '1950');
            }
         }
         }
 
         return '1950';
         return normalizePageNameForShell(window.location.pathname || '');
     }
     }


     function isAnecdoteNamespaceForShell() {
     function waitForNationsPanelReady(era) {
         var namespaceNumber = Number(mw.config.get('wgNamespaceNumber'));
         return BootPerf.measure('wait nations panel api', { era: era }, function () {
         var canonicalNamespace = String(mw.config.get('wgCanonicalNamespace') || '').toLowerCase();
            return waitUntil(function () { return window.NationsPanel && typeof window.NationsPanel.whenEraReady === 'function'; }, {
         var pageName = readCurrentPageNameForShell();
                timeoutMs: 8000,
 
                intervalMs: 50
        return namespaceNumber === 3000 ||
            });
            canonicalNamespace === 'anecdote' ||
         }).then(function (result) {
            /^(anecdote|에넥도트):/i.test(pageName);
            if (!result.ok || !window.NationsPanel || typeof window.NationsPanel.whenEraReady !== 'function') return null;
            return BootPerf.measure('wait nations panel era ready', { era: era }, function () {
                return window.NationsPanel.whenEraReady(era, { timeoutMs: 15000 }).catch(function () { return null; });
            });
         }).then(function () {
            return BootPerf.measure('wait nations panel dom ready', { era: era }, function () {
                return waitUntil(function () {
                    var panel = document.querySelector('.clbi-nations-era-content[data-era-content="' + era + '"] .clbi-nations-tabpanel[data-nation-list-source="1"]') ||
                        document.querySelector('.clbi-nations-tabpanel[data-nation-list-source="1"]');
                    return panel && panel.classList.contains('clbi-nations-list-json-ready') && panel.getAttribute('data-nation-list-year-loaded') === String(era);
                }, { timeoutMs: 15000, intervalMs: 80 });
            });
        });
     }
     }


     function isBackendOrSystemPageForShell() {
     function waitForNationsGlobeReady(options) {
         var namespaceNumber = Number(mw.config.get('wgNamespaceNumber'));
         var globe = document.querySelector('.clbi-nations-globe-window[data-nations-globe], [data-nations-globe="real-world"]');
        var action = String(mw.config.get('wgAction') || 'view').toLowerCase();
         var soft;
        var contentModel = String(mw.config.get('wgPageContentModel') || '').toLowerCase();
         var timeout;
         var pageName = readCurrentPageNameForShell();
         var lowerPageName = pageName.toLowerCase();


         if (action && action !== 'view') {
         options = options || {};
            return true;
        soft = !!options.soft;
         }
         timeout = Number(options.timeoutMs || (soft ? 450 : 30000));


         if (pageName === '대문') {
         if (!globe) {
             return false;
            BootPerf.mark('wait nations globe skipped', { reason: 'no globe node', soft: soft });
             return Promise.resolve(null);
         }
         }


         if (SYSTEM_TITLE_NAMESPACES[String(namespaceNumber)]) {
         return BootPerf.measure(soft ? 'wait nations globe warm attach' : 'wait nations globe ready contract', { soft: soft, timeoutMs: timeout }, function () {
            return true;
            if (soft) {
        }
                /*
                Warm-tab policy:
                Raw globe images are already revision-checked and blob-cached by EntryCache,
                but WebGL scene creation, GPU upload, topojson parsing, and per-tab Three.js
                objects cannot be shared across browser tabs.  Waiting for the full is-ready
                contract here makes a warm tab slower than the first tab.  In warm mode the
                initial gate only waits until the globe consumer has been attached, then the
                globe finishes its own per-tab hydrate without holding the whole page hostage.
                */
                return waitUntil(function () {
                    var node = document.querySelector('.clbi-nations-globe-window[data-nations-globe], [data-nations-globe="real-world"]');
                    if (!node) return false;
                    return node.getAttribute('data-nations-globe-ready') === '1' ||
                        !!node.CLBI_NationsGlobeInstance ||
                        !!node.querySelector('.clbi-nations-globe-stage') ||
                        node.classList.contains('is-ready') ||
                        node.classList.contains('has-error');
                }, { timeoutMs: timeout, intervalMs: 40 });
            }


        if (contentModel === 'css' || contentModel === 'javascript' || contentModel === 'json' || contentModel === 'sanitized-css') {
            return waitUntil(function () {
            return true;
                var node = document.querySelector('.clbi-nations-globe-window[data-nations-globe], [data-nations-globe="real-world"]');
        }
                return node && (node.classList.contains('is-ready') || node.classList.contains('has-error'));
 
             }, { timeoutMs: timeout, intervalMs: 100 });
        if (/\.(css|js|json)$/i.test(pageName)) {
         });
             return true;
        }
 
        if (/^(mediawiki|미디어위키|special|특수):/i.test(pageName)) {
            return true;
         }
 
        return false;
     }
     }


     function isMediaWikiSystemAssetPageForShell() {
     function waitForDecorationsReady(options) {
         var namespaceNumber = Number(mw.config.get('wgNamespaceNumber'));
         options = options || {};
        var pageName = readCurrentPageNameForShell();
        return waitForDecorationRuntime().then(function (runtime) {
        var contentModel = String(mw.config.get('wgPageContentModel') || '').toLowerCase();
            if (!runtime) return null;
 
            if (options.warm) {
        return namespaceNumber === 8 &&
                /*
             (/\.(css|js)$/i.test(pageName) || contentModel === 'css' || contentModel === 'javascript' || contentModel === 'sanitized-css');
                * Warm tab contract — 20260708.
                *
                * The decoration registry and pixel canvases were prepared by the cold tab.
                * Calling reload() here re-reads and re-syncs the decoration layer during the
                * boot gate, which is visible as a pointless delay. A warm tab only needs the
                * current visibility pass so boot can release quickly and editing/preview tools
                * remain responsive.
                */
                try {
                    if (typeof runtime.updateVisibility === 'function') runtime.updateVisibility(document);
                    else if (typeof runtime.sync === 'function') runtime.sync();
                } catch (err) {}
                return waitForAnimationFrames(1);
            }
            if (typeof runtime.reload !== 'function') return null;
             return runtime.reload().catch(function () { return null; }).then(function () {
                return waitForAnimationFrames(2);
            });
        });
     }
     }


    function waitForCurrentEntrySurface(manifest, options) {
        var era = getInitialNationsEra(manifest);
        var warmPack;


    var systemDocRawFetchToken = 0;
        options = options || {};
        warmPack = !!options.warmPack;


    function cleanupLegacySystemDocCodeMutationsForShell() {
        if (!isNationsPageSurface()) {
        document.querySelectorAll('.clbi-system-doc-codepane').forEach(function (pane) {
            return waitForDecorationsReady({ warm: !!warmPack }).then(function () { return waitForAnimationFrames(1); });
            var parent;
        }
 
        if (bootStatusNode) bootStatusNode.textContent = warmPack ? 'Hydrating current information surface from warm cache' : 'Preparing current information surface';
            if (!pane || !pane.parentNode) return;
        if (bootDetailNode) bootDetailNode.textContent = 'waiting for era ' + era + ' ready contract';
 
        return waitForNationsPanelReady(era)
             parent = pane.parentNode;
             .then(function () {
            while (pane.firstChild) {
                if (warmPack) {
                parent.insertBefore(pane.firstChild, pane);
                    if (bootDetailNode) bootDetailNode.textContent = 'attaching globe warm consumer';
            }
                    return waitForNationsGlobeReady({ soft: true, timeoutMs: 450 });
            parent.removeChild(pane);
                }
        });
                if (bootDetailNode) bootDetailNode.textContent = 'waiting for globe ready contract';
 
                return waitForNationsGlobeReady();
        document.querySelectorAll('.clbi-system-doc-codebox').forEach(function (node) {
            })
            node.classList.remove('clbi-system-doc-codebox');
            .then(function () {
             node.removeAttribute('data-clbi-system-doc-codebox');
                if (bootDetailNode) bootDetailNode.textContent = 'waiting for decoration surface';
             node.removeAttribute('style');
                return waitForDecorationsReady({ warm: warmPack });
        });
             })
             .then(function () { return waitForAnimationFrames(warmPack ? 1 : 2); });
     }
     }


     function getSystemDocOutputForShell() {
     function runDeferredEntryWarmups() {
         return document.querySelector('.liberty-content-main .mw-parser-output');
         var queue = deferredEntryWarmups.splice(0);
        if (!queue.length) return;
        window.setTimeout(function () {
            var chain = Promise.resolve();
            queue.forEach(function (job) {
                chain = chain.then(function () {
                    try { return job(); }
                    catch (err) { return null; }
                }).catch(function () { return null; });
            });
        }, 1200);
     }
     }


     function findSystemDocSourceNodeForShell() {
     function runInitialLoad(options) {
         var output = getSystemDocOutputForShell();
         var done = 0;
         var children;
        var manifestRef;
         var preferred;
        var tasks;
        var bootOptions;
         var timedOut = false;
         var warmPack = false;


         if (!output) return null;
         options = options || {};
        bootStartTime = window.__BootGatePrelude && window.__BootGatePrelude.startTime ? window.__BootGatePrelude.startTime : now();
        activateBootSurface();
        ensureBootScreen();
        updateBootProgress(0, 1, 'loading entry manifest');


         children = Array.prototype.slice.call(output.children || [])
         manifestRef = loadManifest().then(function (manifest) {
            .filter(function (el) {
            var minDisplay;
                return el && el.nodeType === 1 &&
            var totalSteps;
                    el.id !== 'clbi-system-doc-indicator-row' &&
            var maxBlockingMs;
                    el.id !== 'clbi-system-source-viewer' &&
            var timeoutHandle;
                    !el.classList.contains('catlinks') &&
            bootOptions = manifest.boot || {};
                    (el.textContent || '').trim().length > 200;
            warmPack = isInitialPackWarm(manifest);
             });
            minDisplay = options.minDisplayMs || (warmPack ? (bootOptions.cachedMinDisplayMs || 220) : (bootOptions.minDisplayMs || 950));
            tasks = flattenInitialTasks(manifest);
            if (!tasks.length) tasks = flattenInitialTasks(defaultManifest);
             if (warmPack) tasks = flattenWarmInitialTasks(tasks);


        preferred = children.filter(function (el) {
            /*
             return el.matches && el.matches('.mw-highlight, .mw-code, pre');
            Full/half contract:
        })[0];
            These manifest tasks only prepare data assets.  The gate is not allowed to open
            until the current page surface has consumed that data and reported a real ready
            state below. Do not reintroduce localStorage-only skip logic here; a cached
             version number is not the same as current-tab readiness.
            */
            totalSteps = tasks.length + 4;
            updateBootProgress(0, totalSteps, warmPack ? 'hydrating warm entry cache' : 'starting entry packs');


        return preferred || children.sort(function (a, b) {
            return new Promise(function (resolve) {
            return (b.textContent || '').trim().length - (a.textContent || '').trim().length;
                maxBlockingMs = Number(options.maxBlockingMs || bootOptions.maxBlockingMs || 30000);
        })[0] || null;
                timeoutHandle = window.setTimeout(function () {
    }
                    timedOut = true;
                    resolve();
                }, maxBlockingMs);


    function getSystemDocRawUrlForShell() {
                Promise.all(tasks.map(function (task) {
        var title = mw.config.get('wgPageName') || readCurrentPageNameForShell();
                    var label = task.label || task.id || task.type || 'entry task';
        var url;
                    return BootPerf.measure('boot task: ' + label, { id: task.id || '', type: task.type || '', level: task.level || task.level === 0 ? task.level : '' }, function () {
 
                        return prepareTask(task, task.level);
        if (window.mw && mw.util && typeof mw.util.getUrl === 'function') {
                    }).catch(function () {
            url = mw.util.getUrl(title, {
                        return null;
                 action: 'raw',
                    }).then(function () {
                 ctype: 'text/plain'
                        done += 1;
             });
                        updateBootProgress(done, totalSteps, label);
        } else {
                    });
            url = '/index.php?title=' + encodeURIComponent(title) + '&action=raw&ctype=text/plain';
                })).then(function () {
        }
                    updateBootProgress(++done, totalSteps, 'loading subsystem scripts');
 
                    return BootPerf.measure('wait tracked subsystem scripts', { count: (window.EntryScriptLoads || []).length }, function () { return waitForTrackedScripts(); });
        if (window.RevisionManifest && typeof window.RevisionManifest.addRevisionParam === 'function') {
                }).then(function () {
            url = window.RevisionManifest.addRevisionParam(url, title);
                    updateBootProgress(++done, totalSteps, 'waiting for document shell');
         }
                    return BootPerf.measure('wait document shell', {}, function () { return waitForDocumentSurface(); });
         return url;
                 }).then(function () {
                    updateBootProgress(++done, totalSteps, 'waiting for current entry surface');
                    return BootPerf.measure('wait current entry surface', { warmPack: warmPack }, function () { return waitForCurrentEntrySurface(manifest, { warmPack: warmPack }); });
                 }).then(function () {
                    updateBootProgress(totalSteps, totalSteps, warmPack ? 'warm entry surface complete' : 'entry surface complete');
                    window.clearTimeout(timeoutHandle);
                    resolve();
                }).catch(function () {
                    window.clearTimeout(timeoutHandle);
                    resolve();
                });
             }).then(function () {
                var elapsed = now() - bootStartTime;
                var wait = Math.max(0, minDisplay - elapsed);
                return waitMs(wait);
            }).then(function () {
                localStorage.setItem(READY_KEY, String(manifest.version));
                if (!timedOut) markInitialPackWarm(manifest, { warmSource: warmPack ? 'cache-hit' : 'cold-build' });
                if (bootStatusNode) bootStatusNode.textContent = timedOut ? 'Entry surface ready with deferred items' : (warmPack ? 'Entry surface ready from warm cache' : 'Entry surface ready');
                updateBootProgress(tasks.length + 4, tasks.length + 4, timedOut ? 'timeout: continuing deferred loading' : (warmPack ? 'warm cache complete' : 'complete'));
                BootPerf.mark('boot gate complete', { timedOut: timedOut, warmPack: warmPack, manifestVersion: manifest && manifest.version || '' });
                BootPerf.print();
                runDeferredEntryWarmups();
                window.setTimeout(function () {
                    if (requiresLoginGate()) showLoginGate();
                    else hideBootScreen();
                }, 120);
                return manifest;
            });
         });
 
         return manifestRef;
     }
     }


     function removeSystemDocSourceViewerForShell() {
     function startBoot(options) {
         var viewer = document.getElementById('clbi-system-source-viewer');
         if (BOOT_EXCLUDED_PAGE && !(options && options.force)) {
 
             hideBootScreen();
        if (viewer && viewer.parentNode) {
            return Promise.resolve({ skipped: true, reason: 'developer-or-editing-page' });
             viewer.parentNode.removeChild(viewer);
         }
         }
        if (hasBootParam('0') && !requiresLoginGate() && !(options && options.force)) return Promise.resolve(null);
        if (bootStarted && bootPromise && !(options && options.force)) return bootPromise;
        bootStarted = true;
        bootPromise = runInitialLoad(options || {});
        return bootPromise;
    }


        document.querySelectorAll('.clbi-system-original-source-hidden').forEach(function (node) {
    function resetBoot() {
            node.classList.remove('clbi-system-original-source-hidden');
        localStorage.removeItem(READY_KEY);
            node.removeAttribute('data-clbi-system-source-hidden');
        bootStarted = false;
            node.style.removeProperty('display');
         bootPromise = null;
         });
         loginGateLocked = false;
 
         cleanupLegacySystemDocCodeMutationsForShell();
     }
     }


     function ensureSystemDocSourceViewerForShell() {
     /*
        var output = getSystemDocOutputForShell();
    BootGate intentionally has no SPA hold/release API.
        var source;
    Initial boot is the only blocking phase; later SPA routes must consume prepared
        var viewer;
    EntryStore artifacts without reopening the loading surface.
        var fallbackText;
    */


        if (!output || !isMediaWikiSystemAssetPageForShell()) return null;
    function buildBootReport() {
 
        return {
        cleanupLegacySystemDocCodeMutationsForShell();
            build: BUILD_ID,
 
            state: {
        source = findSystemDocSourceNodeForShell();
                started: bootStarted,
        if (!source) return null;
                excludedPage: BOOT_EXCLUDED_PAGE,
 
                loginRequired: requiresLoginGate(),
        viewer = document.getElementById('clbi-system-source-viewer');
                loginLocked: loginGateLocked,
 
                hasNode: !!((bootNode && bootNode.parentNode) || document.getElementById('boot-gate-screen')),
        if (!viewer) {
                htmlActive: !!(document.documentElement && document.documentElement.classList.contains('boot-gate-active')),
            viewer = document.createElement('pre');
                bodyActive: !!(document.body && document.body.classList.contains('boot-gate-active'))
            viewer.id = 'clbi-system-source-viewer';
             },
             viewer.className = 'clbi-system-source-viewer';
             store: window.EntryStore && window.EntryStore.cacheInfo ? window.EntryStore.cacheInfo() : null,
             output.appendChild(viewer);
            bootPerf: window.BootPerf && typeof window.BootPerf.summary === 'function' ? window.BootPerf.summary() : null,
        }
            revisionManifest: window.RevisionManifest && typeof window.RevisionManifest.status === 'function' ? window.RevisionManifest.status() : null,
 
             nations: window.NationsPanel && typeof window.NationsPanel.diagnostics === 'function' ? window.NationsPanel.diagnostics() : null,
        fallbackText = source.textContent || '';
            decorations: window.Decorations && typeof window.Decorations.diagnostics === 'function' ? window.Decorations.diagnostics() : null
 
         };
        if (!viewer.textContent && fallbackText) {
             viewer.textContent = fallbackText;
        }
 
        source.classList.add('clbi-system-original-source-hidden');
        source.setAttribute('data-clbi-system-source-hidden', 'true');
        source.style.setProperty('display', 'none', 'important');
 
         return viewer;
     }
     }


     function renderSystemDocSourceViewerForShell() {
     window.EntryLoader = window.EntryLoader || {
         var viewer;
         loadManifest: loadManifest,
         var pageName;
         prepareTask: prepareTask,
         var token;
         prepareNationsEra: prepareNationsEra,
         var currentScrollTop;
         prepareDecorationSet: prepareDecorationSet,
 
        prepareGlobeSharedAssets: prepareGlobeSharedAssets,
         if (!isMediaWikiSystemAssetPageForShell()) return;
         prepareImageAssets: prepareImageAssets,
 
        prepareHtmlEntry: prepareHtmlEntry,
         pageName = String(mw.config.get('wgPageName') || readCurrentPageNameForShell());
         runInitialLoad: runInitialLoad
        viewer = document.getElementById('clbi-system-source-viewer');
    };


    function showBootPreview(options) {
        var node;
        options = options || {};
         /*
         /*
        시스템 문서 뷰어가 이미 만들어져 있고 raw 원문도 로드된 상태라면
        * Boot preview is a design/editing surface, not a real boot gate.
        다시 source 탐색/숨김/스타일 재적용을 하지 않는다.
        * The earlier preview reused activateBootSurface(), which applied
        DevTools Elements 패널에서 body가 계속 파랗게 깜빡이던 원인은
        * html.boot-gate-active and hid the entire wiki shell, including
        MutationObserver가 이 재적용을 반복해서 DOM attribute mutation을 만들었기 때문이다.
        * DevTools.  That made it impossible to edit loading-screen
        */
        * decorations while previewing them.  Keep the real first-entry gate
         if (
        * full-screen, but make preview a small non-blocking surface below the
             viewer &&
        * DevTools z-index so the owner can keep using the editor.
             viewer.getAttribute('data-clbi-raw-title') === pageName &&
        */
            viewer.getAttribute('data-clbi-raw-loaded') === '1'
        node = ensureBootScreen({ preview: true });
         ) {
         if (!node) return null;
        node.classList.add('is-preview');
        if (bootStatusNode) bootStatusNode.textContent = options.status || 'Loading screen preview';
        updateBootProgress(Number(options.progress || 64), 100, options.detail || 'preview mode: no entry tasks are running');
        try {
             if (window.Decorations && typeof window.Decorations.sync === 'function') window.Decorations.sync();
        } catch (err) {}
        return node;
    }
 
    window.BootGate = window.BootGate || {
        version: BUILD_ID,
        start: startBoot,
        show: function (options) {
             options = options || {};
            options.force = true;
            resetBoot();
            return startBoot(options);
        },
        reset: resetBoot,
        hide: hideBootScreen,
        preview: showBootPreview,
        report: buildBootReport,
        state: function () {
            return {
                started: bootStarted,
                loginRequired: requiresLoginGate(),
                loginLocked: loginGateLocked,
                hasNode: !!((bootNode && bootNode.parentNode) || document.getElementById('boot-gate-screen')),
                htmlActive: !!(document.documentElement && document.documentElement.classList.contains('boot-gate-active')),
                bodyActive: !!(document.body && document.body.classList.contains('boot-gate-active')),
                prelude: !!window.__BootGatePrelude,
                store: window.EntryStore && window.EntryStore.cacheInfo ? window.EntryStore.cacheInfo() : null,
                revisionManifest: window.RevisionManifest && typeof window.RevisionManifest.status === 'function' ? window.RevisionManifest.status() : null
            };
         }
    };
 
    function prime() {
        if (BOOT_EXCLUDED_PAGE) {
            hideBootScreen();
             return;
             return;
         }
         }
        activateBootSurface();
        waitForBody().then(function () {
            ensureBootScreen();
            return waitForAnimationFrames(1);
        }).then(function () {
            startBoot();
        });
    }
    waitForBody().then(function () {
        if (!BOOT_EXCLUDED_PAGE) ensureBootScreen();
        else hideBootScreen();
    });
    window.setTimeout(prime, 0);
})(window, document, window.mediaWiki || window.mw);


        viewer = ensureSystemDocSourceViewerForShell();
        if (!viewer) return;


        currentScrollTop = viewer.scrollTop || 0;
loadClbiRawScript('MediaWiki:DevTools.js');
         viewer.setAttribute('data-clbi-raw-title', pageName);
loadClbiRawScript('MediaWiki:NationsPanel.js');
         token = ++systemDocRawFetchToken;
loadClbiRawScript('MediaWiki:NationsGlobe.js');
 
/* CLBI safety guard: adaptive reset functions must exist before shell metric callbacks run. */
function resetLeftRecentAdaptiveState() {
    var list = document.getElementById('clbi-left-recent-list');
    var newsBox = list ? list.closest('.clbi-left-news-box') : null;
    var items = list ? Array.prototype.slice.call(list.querySelectorAll('.news-recent-item')) : [];
 
    if (newsBox) {
         newsBox.classList.remove('is-adaptive-constrained');
         newsBox.style.removeProperty('--adaptive-news-h');
    }


        fetch(getSystemDocRawUrlForShell(), { credentials: 'same-origin' })
    if (list) {
            .then(function (res) {
        list.classList.remove('is-adaptive-faded');
                if (!res.ok) throw new Error('raw fetch failed ' + res.status);
        list.removeAttribute('data-adaptive-limit');
                return res.text();
        list.style.removeProperty('--adaptive-recent-h');
            })
    }
            .then(function (text) {
                if (token !== systemDocRawFetchToken) return;


                currentScrollTop = viewer.scrollTop || currentScrollTop || 0;
    items.forEach(function (item) {
        item.classList.remove('is-adaptive-hidden');
    });
}


                if (text && viewer.textContent !== text) {
function resetLeftBillboardAdaptiveState() {
                    viewer.textContent = text;
    var box = document.querySelector('#clbi-left-sidebar .left-billboard-box');
                }


                viewer.setAttribute('data-clbi-raw-loaded', '1');
    if (!box) return;
                viewer.scrollTop = currentScrollTop;
            })
            .catch(function () {
                viewer.setAttribute('data-clbi-raw-loaded', '0');
            });
    }


     function removeSystemDocIndicatorForShell() {
     box.classList.remove('is-left-ad-title-only', 'is-left-ad-extended');
        var existing = document.getElementById('clbi-system-doc-indicator-row');
    box.style.removeProperty('--left-billboard-h');
    box.style.removeProperty('--left-billboard-finish-h');
}


        if (document.body) {
window.resetLeftRecentAdaptiveState = resetLeftRecentAdaptiveState;
            document.body.classList.remove('clbi-system-doc-page');
window.resetLeftBillboardAdaptiveState = resetLeftBillboardAdaptiveState;
        }


        if (existing && existing.parentNode) {
loadClbiRawScript('MediaWiki:AnecdoteViewer.js');
            existing.parentNode.removeChild(existing);
        }


        removeSystemDocSourceViewerForShell();
    }


    function renderSystemDocIndicatorForShell() {
(function () {
        var pageName;
    'use strict';
        var extMatch;
        var ext;
        var row;
        var box;
        var meta;
        var label;
        var type;
        var title;
        var anchor;
        var main;


         if (!document.body || !isMediaWikiSystemAssetPageForShell()) return;
    var SYSTEM_TITLE_NAMESPACES = {
         '-1': true,
        '4': true,
        '5': true,
        '6': true,
        '7': true,
        '8': true,
        '9': true,
        '10': true,
        '11': true,
        '12': true,
        '13': true,
        '14': true,
        '15': true,
        '828': true,
        '829': true
    };


         pageName = readCurrentPageNameForShell();
    function normalizePageNameForShell(value) {
        extMatch = pageName.match(/\.(css|js)$/i);
         return String(value || '')
        ext = extMatch ? extMatch[1].toUpperCase() : 'DOC';
            .split('?')[0]
            .replace(/^\/index\.php\//, '')
            .replace(/_/g, ' ')
            .trim();
    }


         document.body.classList.add('clbi-system-doc-page');
    function readCurrentPageNameForShell() {
         var pageName = mw.config.get('wgPageName') || '';


         row = document.getElementById('clbi-system-doc-indicator-row');
         if (pageName) {
            return normalizePageNameForShell(pageName);
        }


         if (!row) {
         return normalizePageNameForShell(window.location.pathname || '');
            row = document.createElement('div');
    }
            row.id = 'clbi-system-doc-indicator-row';
            row.className = 'clbi-system-doc-indicator-row';


            box = document.createElement('div');
    function isAnecdoteNamespaceForShell() {
            box.className = 'clbi-system-doc-indicator';
        var namespaceNumber = Number(mw.config.get('wgNamespaceNumber'));
        var canonicalNamespace = String(mw.config.get('wgCanonicalNamespace') || '').toLowerCase();
        var pageName = readCurrentPageNameForShell();


             meta = document.createElement('div');
        return namespaceNumber === 3000 ||
             meta.className = 'clbi-system-doc-meta';
             canonicalNamespace === 'anecdote' ||
             /^(anecdote|에넥도트):/i.test(pageName);
    }


            label = document.createElement('span');
    function isBackendOrSystemPageForShell() {
            label.className = 'clbi-system-doc-label';
        var namespaceNumber = Number(mw.config.get('wgNamespaceNumber'));
            label.textContent = 'SYSTEM DOCUMENT';
        var action = String(mw.config.get('wgAction') || 'view').toLowerCase();
        var contentModel = String(mw.config.get('wgPageContentModel') || '').toLowerCase();
        var pageName = readCurrentPageNameForShell();
        var lowerPageName = pageName.toLowerCase();


            type = document.createElement('span');
        if (action && action !== 'view') {
            type.className = 'clbi-system-doc-type';
            return true;
        }
 
        if (pageName === '대문') {
            return false;
        }


            title = document.createElement('div');
        if (SYSTEM_TITLE_NAMESPACES[String(namespaceNumber)]) {
             title.className = 'clbi-system-doc-title';
             return true;
        }


            meta.appendChild(label);
        if (contentModel === 'css' || contentModel === 'javascript' || contentModel === 'json' || contentModel === 'sanitized-css') {
            meta.appendChild(type);
             return true;
            box.appendChild(meta);
        }
             box.appendChild(title);
            row.appendChild(box);


            anchor = getSystemDocOutputForShell();
        if (/\.(css|js|json)$/i.test(pageName)) {
            main = document.querySelector('.liberty-content-main');
            return true;
        }


            if (anchor && anchor.parentNode) {
        if (/^(mediawiki|미디어위키|special|특수):/i.test(pageName)) {
                anchor.parentNode.insertBefore(row, anchor);
            return true;
            } else if (main) {
                main.insertBefore(row, main.firstChild);
            }
         }
         }


         type = row.querySelector('.clbi-system-doc-type');
         return false;
        title = row.querySelector('.clbi-system-doc-title');
    }


         if (type) type.textContent = ext;
    function isMediaWikiSystemAssetPageForShell() {
         if (title) title.textContent = pageName;
         var namespaceNumber = Number(mw.config.get('wgNamespaceNumber'));
        var pageName = readCurrentPageNameForShell();
         var contentModel = String(mw.config.get('wgPageContentModel') || '').toLowerCase();


         renderSystemDocSourceViewerForShell();
         return namespaceNumber === 8 &&
            (/\.(css|js)$/i.test(pageName) || contentModel === 'css' || contentModel === 'javascript' || contentModel === 'sanitized-css');
     }
     }


    var PAGE_TITLE_TARGET_SELECTORS = [
        '.liberty-content-header',
        '.liberty-content-header .title',
        '.liberty-content-header .title h1',
        '.liberty-content-header h1',
        '#firstHeading',
        '.firstHeading',
        '.mw-first-heading',
        '.page-heading',
        '.page-header',
        '.mw-page-title-main',
        '.mw-page-title-namespace',
        '.mw-page-title-separator'
    ];


     var pageShellObserverStarted = false;
     var systemDocRawFetchToken = 0;
    var pageShellObserverTimer = null;


     function setPageTitleDomHidden(hidden) {
     function cleanupLegacySystemDocCodeMutationsForShell() {
         var nodes = document.querySelectorAll(PAGE_TITLE_TARGET_SELECTORS.join(','));
         document.querySelectorAll('.clbi-system-doc-codepane').forEach(function (pane) {
            var parent;


        nodes.forEach(function (node) {
             if (!pane || !pane.parentNode) return;
             if (!node || !node.style) return;


             if (hidden) {
             parent = pane.parentNode;
                node.setAttribute('data-clbi-title-hidden', 'true');
             while (pane.firstChild) {
                node.style.setProperty('display', 'none', 'important');
                 parent.insertBefore(pane.firstChild, pane);
             } else if (node.getAttribute('data-clbi-title-hidden') === 'true') {
                 node.removeAttribute('data-clbi-title-hidden');
                node.style.removeProperty('display');
             }
             }
            parent.removeChild(pane);
        });
        document.querySelectorAll('.clbi-system-doc-codebox').forEach(function (node) {
            node.classList.remove('clbi-system-doc-codebox');
            node.removeAttribute('data-clbi-system-doc-codebox');
            node.removeAttribute('style');
         });
         });
     }
     }


     function applyPageShellClasses() {
     function getSystemDocOutputForShell() {
         var body = document.body;
        return document.querySelector('.liberty-content-main .mw-parser-output');
         var isSystemPage;
    }
 
    function findSystemDocSourceNodeForShell() {
         var output = getSystemDocOutputForShell();
        var children;
         var preferred;


         if (!body) return;
         if (!output) return null;


         isSystemPage = isBackendOrSystemPageForShell();
         children = Array.prototype.slice.call(output.children || [])
            .filter(function (el) {
                return el && el.nodeType === 1 &&
                    el.id !== 'clbi-system-doc-indicator-row' &&
                    el.id !== 'clbi-system-source-viewer' &&
                    !el.classList.contains('catlinks') &&
                    (el.textContent || '').trim().length > 200;
            });


         body.classList.remove('page-title-hidden', 'page-title-visible', 'backend-system-page', 'anecdote-namespace-page');
         preferred = children.filter(function (el) {
            return el.matches && el.matches('.mw-highlight, .mw-code, pre');
        })[0];


         if (!isMediaWikiSystemAssetPageForShell()) {
         return preferred || children.sort(function (a, b) {
             body.classList.remove('clbi-system-doc-page');
             return (b.textContent || '').trim().length - (a.textContent || '').trim().length;
            removeSystemDocIndicatorForShell();
        })[0] || null;
        }
    }


        if (isAnecdoteNamespaceForShell()) {
    function getSystemDocRawUrlForShell() {
            body.classList.add('anecdote-namespace-page');
        var title = mw.config.get('wgPageName') || readCurrentPageNameForShell();
         }
         var url;


         if (isMediaWikiSystemAssetPageForShell()) {
         if (window.mw && mw.util && typeof mw.util.getUrl === 'function') {
             body.classList.add('page-title-hidden', 'backend-system-page', 'clbi-system-doc-page');
             url = mw.util.getUrl(title, {
            setPageTitleDomHidden(true);
                action: 'raw',
            renderSystemDocIndicatorForShell();
                ctype: 'text/plain'
        } else if (isSystemPage) {
             });
            body.classList.add('page-title-visible', 'backend-system-page');
             setPageTitleDomHidden(false);
         } else {
         } else {
             body.classList.add('page-title-hidden');
             url = '/index.php?title=' + encodeURIComponent(title) + '&action=raw&ctype=text/plain';
             setPageTitleDomHidden(true);
        }
 
        if (window.RevisionManifest && typeof window.RevisionManifest.addRevisionParam === 'function') {
             url = window.RevisionManifest.addRevisionParam(url, title);
         }
         }
        return url;
     }
     }


     function applyPageShellClassesDeferred() {
     function removeSystemDocSourceViewerForShell() {
         applyPageShellClasses();
         var viewer = document.getElementById('clbi-system-source-viewer');
         window.setTimeout(applyPageShellClasses, 0);
 
         window.setTimeout(applyPageShellClasses, 80);
         if (viewer && viewer.parentNode) {
         window.setTimeout(applyPageShellClasses, 250);
            viewer.parentNode.removeChild(viewer);
         }
 
        document.querySelectorAll('.clbi-system-original-source-hidden').forEach(function (node) {
            node.classList.remove('clbi-system-original-source-hidden');
            node.removeAttribute('data-clbi-system-source-hidden');
            node.style.removeProperty('display');
         });
 
        cleanupLegacySystemDocCodeMutationsForShell();
     }
     }


     function startPageShellObserver() {
     function ensureSystemDocSourceViewerForShell() {
         var observer;
         var output = getSystemDocOutputForShell();
        var source;
        var viewer;
        var fallbackText;
 
        if (!output || !isMediaWikiSystemAssetPageForShell()) return null;


         if (pageShellObserverStarted || !window.MutationObserver || !document.body) return;
         cleanupLegacySystemDocCodeMutationsForShell();


         pageShellObserverStarted = true;
         source = findSystemDocSourceNodeForShell();
         observer = new MutationObserver(function (mutations) {
         if (!source) return null;
            var i;
            var target;


            /*
        viewer = document.getElementById('clbi-system-source-viewer');
            시스템 CSS/JS 문서는 applyPageShellClasses()가 초기에 한 번
            인디케이터와 source viewer를 만든 뒤에는 MutationObserver가 다시
            같은 렌더링을 반복할 필요가 없다. 이 반복이 DevTools에서 body/요소가
            계속 플래시되는 직접 원인이다.
            SPA 전환 뒤의 처리는 loadPage()와 wikipage.content hook에서 따로 호출된다.
            */
            if (isMediaWikiSystemAssetPageForShell()) {
                for (i = 0; i < mutations.length; i += 1) {
                    target = mutations[i] && mutations[i].target;


                    if (
        if (!viewer) {
                        target &&
            viewer = document.createElement('pre');
                        target.nodeType === 1 &&
            viewer.id = 'clbi-system-source-viewer';
                        (
            viewer.className = 'clbi-system-source-viewer';
                            target.id === 'clbi-system-source-viewer' ||
            output.appendChild(viewer);
                            target.id === 'clbi-system-doc-indicator-row' ||
        }
                            (target.closest && target.closest('#clbi-system-source-viewer, #clbi-system-doc-indicator-row'))
                        )
                    ) {
                        return;
                    }
                }


                if (
        fallbackText = source.textContent || '';
                    document.getElementById('clbi-system-doc-indicator-row') &&
                    document.getElementById('clbi-system-source-viewer')
                ) {
                    return;
                }
            }


            if (pageShellObserverTimer) return;
        if (!viewer.textContent && fallbackText) {
            viewer.textContent = fallbackText;
        }


            pageShellObserverTimer = window.setTimeout(function () {
        source.classList.add('clbi-system-original-source-hidden');
                pageShellObserverTimer = null;
        source.setAttribute('data-clbi-system-source-hidden', 'true');
                applyPageShellClasses();
         source.style.setProperty('display', 'none', 'important');
            }, 50);
         });


         observer.observe(document.body, {
         return viewer;
            childList: true,
            subtree: true
        });
     }
     }


     if (document.readyState === 'loading') {
     function renderSystemDocSourceViewerForShell() {
         document.addEventListener('DOMContentLoaded', function () {
         var viewer;
            applyPageShellClassesDeferred();
         var pageName;
            startPageShellObserver();
         var token;
         });
         var currentScrollTop;
    } else {
         applyPageShellClassesDeferred();
         startPageShellObserver();
    }


    if (mw.hook) {
        if (!isMediaWikiSystemAssetPageForShell()) return;
        mw.hook('wikipage.content').add(applyPageShellClassesDeferred);
    }


    window.CLBI_PAGE_SHELL = {
        pageName = String(mw.config.get('wgPageName') || readCurrentPageNameForShell());
         refresh: applyPageShellClasses,
         viewer = document.getElementById('clbi-system-source-viewer');
        isBackendOrSystemPage: isBackendOrSystemPageForShell,
        isSystemAssetPage: isMediaWikiSystemAssetPageForShell,
        renderSystemDocIndicator: renderSystemDocIndicatorForShell,
        removeSystemDocIndicator: removeSystemDocIndicatorForShell,
        refreshSystemDocSourceViewer: renderSystemDocSourceViewerForShell
    };
}());


function loadLangScript(done) {
        /*
    $.getScript('/index.php?title=미디어위키:Lang.js&action=raw&ctype=text/javascript')
        시스템 문서 뷰어가 이미 만들어져 있고 raw 원문도 로드된 상태라면
        .done(function() {
        다시 source 탐색/숨김/스타일 재적용을 하지 않는다.
            if (typeof done === 'function') done();
        DevTools Elements 패널에서 body가 계속 파랗게 깜빡이던 원인은
         })
        MutationObserver가 이 재적용을 반복해서 DOM attribute mutation을 만들었기 때문이다.
        .fail(function(a, b, c) {
        */
             console.error('Lang.js load failed:', b, c);
        if (
            if (typeof done === 'function') done();
            viewer &&
         });
            viewer.getAttribute('data-clbi-raw-title') === pageName &&
}
            viewer.getAttribute('data-clbi-raw-loaded') === '1'
         ) {
             return;
        }
 
        viewer = ensureSystemDocSourceViewerForShell();
         if (!viewer) return;


        currentScrollTop = viewer.scrollTop || 0;
        viewer.setAttribute('data-clbi-raw-title', pageName);
        token = ++systemDocRawFetchToken;


function initHalftoneBackground() {
        fetch(getSystemDocRawUrlForShell(), { credentials: 'same-origin' })
    try {
            .then(function (res) {
        initWebGLHalftoneBackground();
                if (!res.ok) throw new Error('raw fetch failed ' + res.status);
    } catch (err) {
                return res.text();
        console.error('WebGL halftone background failed:', err);
            })
    }
            .then(function (text) {
}
                if (token !== systemDocRawFetchToken) return;


function initWebGLHalftoneBackground() {
                currentScrollTop = viewer.scrollTop || currentScrollTop || 0;
    var canvasId = 'site-halftone-bg';
    var existing = document.getElementById(canvasId);
    var canvas = existing || document.createElement('canvas');
    var halftoneState = window.SiteHalftoneBackgroundState || (window.SiteHalftoneBackgroundState = { runId: 0 });
    var runId = halftoneState.runId + 1;


    halftoneState.runId = runId;
                if (text && viewer.textContent !== text) {
                    viewer.textContent = text;
                }


    if (!existing) {
                viewer.setAttribute('data-clbi-raw-loaded', '1');
        canvas.id = canvasId;
                viewer.scrollTop = currentScrollTop;
        canvas.setAttribute('aria-hidden', 'true');
            })
        document.body.insertBefore(canvas, document.body.firstChild || null);
            .catch(function () {
                viewer.setAttribute('data-clbi-raw-loaded', '0');
            });
     }
     }


     canvas.style.position = 'fixed';
     function removeSystemDocIndicatorForShell() {
    canvas.style.inset = '0';
        var existing = document.getElementById('clbi-system-doc-indicator-row');
    canvas.style.width = '100vw';
 
    canvas.style.height = '100vh';
        if (document.body) {
    canvas.style.pointerEvents = 'none';
            document.body.classList.remove('clbi-system-doc-page');
    canvas.style.background = '#000000';
        }
    canvas.style.display = 'block';
 
        if (existing && existing.parentNode) {
            existing.parentNode.removeChild(existing);
        }


    if (!canvas.getAttribute('data-halftone-context-watch')) {
         removeSystemDocSourceViewerForShell();
        canvas.setAttribute('data-halftone-context-watch', '1');
        canvas.addEventListener('webglcontextlost', function (event) {
            event.preventDefault();
            canvas.style.display = 'none';
            if (window.SiteHalftoneBackgroundState) {
                window.SiteHalftoneBackgroundState.contextLost = true;
                window.SiteHalftoneBackgroundState.runId += 1;
            }
        }, false);
         canvas.addEventListener('webglcontextrestored', function () {
            if (window.SiteHalftoneBackgroundState) {
                window.SiteHalftoneBackgroundState.contextLost = false;
            }
            window.setTimeout(initWebGLHalftoneBackground, 0);
        }, false);
     }
     }


     var gl = canvas.getContext('webgl', {
     function renderSystemDocIndicatorForShell() {
         alpha: false,
         var pageName;
         antialias: false,
        var extMatch;
         depth: false,
        var ext;
         stencil: false,
         var row;
         preserveDrawingBuffer: false,
         var box;
         powerPreference: 'low-power'
         var meta;
    }) || canvas.getContext('experimental-webgl');
         var label;
         var type;
        var title;
        var anchor;
        var main;
 
        if (!document.body || !isMediaWikiSystemAssetPageForShell()) return;


    if (!gl) {
        pageName = readCurrentPageNameForShell();
         canvas.style.display = 'none';
         extMatch = pageName.match(/\.(css|js)$/i);
         console.warn('WebGL background unavailable.');
         ext = extMatch ? extMatch[1].toUpperCase() : 'DOC';
        return;
    }


    var vertexSrc = [
         document.body.classList.add('clbi-system-doc-page');
         'attribute vec2 a_position;',
        'void main() {',
        '  gl_Position = vec4(a_position, 0.0, 1.0);',
        '}'
    ].join('\n');


    var fragmentSrc = [
         row = document.getElementById('clbi-system-doc-indicator-row');
        'precision mediump float;',
 
         'uniform vec2 u_resolution;',
         if (!row) {
        'uniform float u_time;',
            row = document.createElement('div');
        'const float TAU = 6.28318530718;',
            row.id = 'clbi-system-doc-indicator-row';
        'float gaussian(float v, float r) {',
            row.className = 'clbi-system-doc-indicator-row';
        ' return exp(-((v * v) / max(0.0001, r * r)));',
 
        '}',
            box = document.createElement('div');
         'float hash(vec2 p) {',
            box.className = 'clbi-system-doc-indicator';
        '  return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453123);',
 
        '}',
            meta = document.createElement('div');
        'float bucketAlpha(float a) {',
            meta.className = 'clbi-system-doc-meta';
        ' float i = floor(a * 9.0);',
 
        '  if (i < 1.0) return 0.040;',
            label = document.createElement('span');
        ' if (i < 2.0) return 0.080;',
            label.className = 'clbi-system-doc-label';
        '  if (i < 3.0) return 0.135;',
            label.textContent = 'SYSTEM DOCUMENT';
        ' if (i < 4.0) return 0.210;',
 
        '  if (i < 5.0) return 0.310;',
            type = document.createElement('span');
        '  if (i < 6.0) return 0.430;',
            type.className = 'clbi-system-doc-type';
        ' if (i < 7.0) return 0.580;',
 
        '  if (i < 8.0) return 0.760;',
            title = document.createElement('div');
        ' return 0.920;',
            title.className = 'clbi-system-doc-title';
        '}',
 
        'void main() {',
            meta.appendChild(label);
        ' vec2 frag = gl_FragCoord.xy;',
            meta.appendChild(type);
        '  float spacing = 5.0;',
            box.appendChild(meta);
        ' float dotSize = 1.08;',
            box.appendChild(title);
        '  vec2 grid = floor(frag / spacing);',
            row.appendChild(box);
        ' vec2 inCell = mod(frag, spacing);',
 
        '  vec2 dotOrigin = vec2(1.0, 1.0);',
            anchor = getSystemDocOutputForShell();
        '  vec2 dotCenter = dotOrigin + vec2(dotSize * 0.5);',
            main = document.querySelector('.liberty-content-main');
        '  vec2 local = abs(inCell - dotCenter);',
 
        ' float noise = hash(grid);',
            if (anchor && anchor.parentNode) {
        '  float size = dotSize + noise * 0.18;',
                anchor.parentNode.insertBefore(row, anchor);
        ' float dotMask = 1.0 - smoothstep(size * 0.5, size * 0.5 + 0.22, max(local.x, local.y));',
            } else if (main) {
        '  vec2 uv = frag / u_resolution;',
                main.insertBefore(row, main.firstChild);
        '  float centerLine = 0.50 +',
            }
        '    sin((uv.y * 1.32 + 0.08) * TAU) * 0.070 +',
         }
        '   sin((uv.y * 3.18 + 0.34) * TAU) * 0.030;',
        '  float u = uv.x - centerLine;',
        '  float absU = abs(u);',
        ' float sideLift = smoothstep(0.065, 0.44, absU);',
        '  float valley = gaussian(u, 0.150);',
        '  float t = u_time;',
        '  float leftRibbonCenter = -0.28 + sin((uv.y * 3.20 + 0.12) * TAU) * 0.050;',
        ' float rightRibbonCenter = 0.27 + sin((uv.y * 2.85 + 0.56) * TAU) * 0.055;',
        ' float leftRibbon = gaussian(u - leftRibbonCenter, 0.105);',
        ' float rightRibbon = gaussian(u - rightRibbonCenter, 0.110);',
        '  float foldedU = u +',
        '    sin((uv.y * 4.40 + 0.22) * TAU) * 0.050 * (0.3 + sideLift) +',
        '    sin((uv.y * 7.20 + uv.x * 1.10) * TAU) * 0.022;',
        '  float verticalFold = pow(0.5 + 0.5 * cos(((foldedU * 3.05) + (sin(uv.y * TAU * 2.35) * 0.18)) * TAU), 2.5);',
        '  float diagonalFold = pow(0.5 + 0.5 * cos(((foldedU * 1.80) - (uv.y * 1.12) + 0.18) * TAU), 2.1);',
        '  float waist = gaussian(uv.y - 0.50, 0.25) * gaussian(absU - 0.20, 0.19);',
        '  float grain = (noise - 0.5) * 0.050;',
        '  float staticField =',
        '    0.055 +',
        '    sideLift * 0.210 +',
        '    (leftRibbon + rightRibbon) * 0.145 +',
        '    verticalFold * (0.055 + sideLift * 0.115) +',
        '    diagonalFold * 0.045 +',
        '    waist * 0.060 -',
        '    valley * 0.150 +',
        '    grain;',
        '  float alpha = staticField;',
        '  alpha += 0.115 * (leftRibbon + rightRibbon) * sin(t * 0.00030 + ((uv.y * 1.9) + sideLift * 0.4) * TAU);',
        '  alpha += 0.095 * verticalFold * (0.4 + sideLift) * sin(t * 0.00041 + ((uv.y * 2.7) + foldedU * 0.65) * TAU);',
        '  alpha += 0.070 * waist * sin(t * 0.00053 + ((uv.y * 3.1) - absU * 0.8) * TAU);',
        '  alpha += 0.060 * (1.0 - valley) * diagonalFold * sin(t * 0.00067 + ((uv.y * 1.4) + uv.x * 0.6) * TAU);',
        '  alpha += 0.038 * (0.35 + sideLift) * (0.35 + noise) * sin(t * 0.00079 + ((uv.y * 4.6) + noise * 0.8) * TAU);',
        '  alpha = bucketAlpha(clamp(alpha, 0.025, 0.96));',
        '  float value = alpha * dotMask;',
        '  gl_FragColor = vec4(vec3(0.8862745 * value), 1.0);',
         '}'
    ].join('\n');


    function compileShader(type, source) {
        type = row.querySelector('.clbi-system-doc-type');
        var shader = gl.createShader(type);
         title = row.querySelector('.clbi-system-doc-title');
         gl.shaderSource(shader, source);
        gl.compileShader(shader);


         if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
         if (type) type.textContent = ext;
            console.error('WebGL shader compile error:', gl.getShaderInfoLog(shader));
        if (title) title.textContent = pageName;
            gl.deleteShader(shader);
            return null;
        }


         return shader;
         renderSystemDocSourceViewerForShell();
     }
     }


     var vertexShader = compileShader(gl.VERTEX_SHADER, vertexSrc);
     var PAGE_TITLE_TARGET_SELECTORS = [
     var fragmentShader = compileShader(gl.FRAGMENT_SHADER, fragmentSrc);
        '.liberty-content-header',
 
        '.liberty-content-header .title',
     if (!vertexShader || !fragmentShader) return;
        '.liberty-content-header .title h1',
 
        '.liberty-content-header h1',
    var program = gl.createProgram();
        '#firstHeading',
    gl.attachShader(program, vertexShader);
        '.firstHeading',
    gl.attachShader(program, fragmentShader);
        '.mw-first-heading',
    gl.linkProgram(program);
        '.page-heading',
        '.page-header',
        '.mw-page-title-main',
        '.mw-page-title-namespace',
        '.mw-page-title-separator'
    ];
 
    var pageShellObserverStarted = false;
     var pageShellObserverTimer = null;
 
     function setPageTitleDomHidden(hidden) {
        var nodes = document.querySelectorAll(PAGE_TITLE_TARGET_SELECTORS.join(','));
 
        nodes.forEach(function (node) {
            if (!node || !node.style) return;


    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
            if (hidden) {
        console.error('WebGL program link error:', gl.getProgramInfoLog(program));
                node.setAttribute('data-clbi-title-hidden', 'true');
         return;
                node.style.setProperty('display', 'none', 'important');
            } else if (node.getAttribute('data-clbi-title-hidden') === 'true') {
                node.removeAttribute('data-clbi-title-hidden');
                node.style.removeProperty('display');
            }
         });
     }
     }


     var positionLoc = gl.getAttribLocation(program, 'a_position');
     function applyPageShellClasses() {
    var resolutionLoc = gl.getUniformLocation(program, 'u_resolution');
        var body = document.body;
    var timeLoc = gl.getUniformLocation(program, 'u_time');
        var isSystemPage;


    var buffer = gl.createBuffer();
        if (!body) return;
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
        -1, -1,
        1, -1,
        -1,  1,
        -1,  1,
        1, -1,
        1,  1
    ]), gl.STATIC_DRAW);


    gl.useProgram(program);
        isSystemPage = isBackendOrSystemPageForShell();
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
    gl.enableVertexAttribArray(positionLoc);
    gl.vertexAttribPointer(positionLoc, 2, gl.FLOAT, false, 0, 0);


    function resize() {
         body.classList.remove('page-title-hidden', 'page-title-visible', 'backend-system-page', 'anecdote-namespace-page');
         var dpr = Math.min(window.devicePixelRatio || 1, 1.5);
        var cssW = Math.max(1, window.innerWidth || document.documentElement.clientWidth || 1);
        var cssH = Math.max(1, window.innerHeight || document.documentElement.clientHeight || 1);
        var w = Math.max(1, Math.floor(cssW * dpr));
        var h = Math.max(1, Math.floor(cssH * dpr));


         if (canvas.width !== w || canvas.height !== h) {
         if (!isMediaWikiSystemAssetPageForShell()) {
             canvas.width = w;
             body.classList.remove('clbi-system-doc-page');
            canvas.height = h;
             removeSystemDocIndicatorForShell();
            canvas.style.width = cssW + 'px';
             canvas.style.height = cssH + 'px';
            gl.viewport(0, 0, w, h);
         }
         }
    }


    var prefersReducedMotion = false;
         if (isAnecdoteNamespaceForShell()) {
    try {
            body.classList.add('anecdote-namespace-page');
         prefersReducedMotion = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    } catch (err) {}
 
    function getNationsGlobeHalftoneState() {
        var globe = document.querySelector('.clbi-nations-globe-window[data-nations-globe], [data-nations-globe="real-world"]');
 
        if (!globe) {
            return 'none';
         }
         }


         if (globe.classList && globe.classList.contains('is-dragging')) {
         if (isMediaWikiSystemAssetPageForShell()) {
             return 'active';
            body.classList.add('page-title-hidden', 'backend-system-page', 'clbi-system-doc-page');
            setPageTitleDomHidden(true);
            renderSystemDocIndicatorForShell();
        } else if (isSystemPage) {
            body.classList.add('page-title-visible', 'backend-system-page');
            setPageTitleDomHidden(false);
        } else {
             body.classList.add('page-title-hidden');
            setPageTitleDomHidden(true);
         }
         }
    }


         return 'present';
    function applyPageShellClassesDeferred() {
         applyPageShellClasses();
        window.setTimeout(applyPageShellClasses, 0);
        window.setTimeout(applyPageShellClasses, 80);
        window.setTimeout(applyPageShellClasses, 250);
     }
     }


     function getFrameInterval() {
     function startPageShellObserver() {
         var globeState;
         var observer;


         if (prefersReducedMotion) {
         if (pageShellObserverStarted || !window.MutationObserver || !document.body) return;
            return 1000;
        }


         globeState = getNationsGlobeHalftoneState();
         pageShellObserverStarted = true;
        observer = new MutationObserver(function (mutations) {
            var i;
            var target;


        /*
            /*
        * Nations page background guard — 20260709.
            시스템 CSS/JS 문서는 applyPageShellClasses()가 초기에 한 번
        *
            인디케이터와 source viewer를 만든 뒤에는 MutationObserver가 다시
        * The old guard returned without drawing while the nations globe existed.
            같은 렌더링을 반복할 필요가 없다. 이 반복이 DevTools에서 body/요소가
        * That protected the globe, but it also left the fixed WebGL canvas alive
            계속 플래시되는 직접 원인이다.
        * with preserveDrawingBuffer=false. After the browser discarded the last
            SPA 전환 뒤의 처리는 loadPage()와 wikipage.content hook에서 따로 호출된다.
        * buffer, the decorative background became a black fixed canvas. Keep the
            */
        * background alive, but lower its cadence while the globe owns the page.
            if (isMediaWikiSystemAssetPageForShell()) {
        */
                for (i = 0; i < mutations.length; i += 1) {
        if (globeState === 'active') {
                    target = mutations[i] && mutations[i].target;
            return 500;
        }
 
        if (globeState === 'present') {
            return 250;
        }


        return 66;
                    if (
    }
                        target &&
 
                        target.nodeType === 1 &&
    var lastFrame = 0;
                        (
    var startTime = performance.now();
                            target.id === 'clbi-system-source-viewer' ||
 
                            target.id === 'clbi-system-doc-indicator-row' ||
    function draw(now) {
                            (target.closest && target.closest('#clbi-system-source-viewer, #clbi-system-doc-indicator-row'))
        resize();
                        )
 
                    ) {
        gl.clearColor(0, 0, 0, 1);
                        return;
        gl.clear(gl.COLOR_BUFFER_BIT);
                    }
        gl.uniform2f(resolutionLoc, canvas.width, canvas.height);
                }
        gl.uniform1f(timeLoc, now - startTime);
        gl.drawArrays(gl.TRIANGLES, 0, 6);
    }


    function render(now) {
                if (
        if (halftoneState.runId !== runId || halftoneState.contextLost) {
                    document.getElementById('clbi-system-doc-indicator-row') &&
            return;
                    document.getElementById('clbi-system-source-viewer')
        }
                ) {
                    return;
                }
            }


        requestAnimationFrame(render);
            if (pageShellObserverTimer) return;


        if (document.hidden) {
            pageShellObserverTimer = window.setTimeout(function () {
             return;
                pageShellObserverTimer = null;
         }
                applyPageShellClasses();
             }, 50);
         });


         if (now - lastFrame < getFrameInterval()) {
         /*
             return;
        SPA 본문 교체는 wikipage.content 훅이 담당한다.
        }
        body 전체 subtree를 감시하면 대문 SVG·장식·DevTools 내부 변경까지
        페이지 셸 재판정으로 증폭되므로 body 직계 자식 변화만 감시한다.
        */
        observer.observe(document.body, {
             childList: true,
            subtree: false
        });
    }


         lastFrame = now;
    if (document.readyState === 'loading') {
         draw(now);
         document.addEventListener('DOMContentLoaded', function () {
            applyPageShellClassesDeferred();
            startPageShellObserver();
        });
    } else {
        applyPageShellClassesDeferred();
         startPageShellObserver();
     }
     }


     draw(performance.now());
     if (mw.hook) {
     requestAnimationFrame(render);
        mw.hook('wikipage.content').add(applyPageShellClassesDeferred);
}
     }


var CLBI_SVG_BELL = '<svg class="profile-svg profile-svg-bell" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10.268 21a2 2 0 0 0 3.464 0"/><path d="M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"/></svg>';
    window.CLBI_PAGE_SHELL = {
var CLBI_SVG_BELL_DOT = '<svg class="profile-svg profile-svg-bell-dot" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10.268 21a2 2 0 0 0 3.464 0"/><path d="M11.68 2.009A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673c-.824-.85-1.678-1.731-2.21-3.348"/><circle cx="18" cy="5" r="3"/></svg>';
        refresh: applyPageShellClasses,
var CLBI_SVG_LIST = '<svg class="profile-svg profile-svg-list" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 5h.01"/><path d="M3 12h.01"/><path d="M3 19h.01"/><path d="M8 5h13"/><path d="M8 12h13"/><path d="M8 19h13"/></svg>';
        isBackendOrSystemPage: isBackendOrSystemPageForShell,
var CLBI_SVG_LANGUAGES = '<svg class="profile-svg profile-svg-languages" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 8 6 6"/><path d="m4 14 6-6 2-3"/><path d="M2 5h12"/><path d="M7 2h1"/><path d="m22 22-5-10-5 10"/><path d="M14 18h6"/></svg>';
        isSystemAssetPage: isMediaWikiSystemAssetPageForShell,
var CLBI_SVG_POWER = '<svg class="profile-svg profile-svg-power" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 2v10"/><path d="M18.4 6.6a9 9 0 1 1-12.77.04"/></svg>';
        renderSystemDocIndicator: renderSystemDocIndicatorForShell,
var CLBI_SVG_SETTINGS = '<svg class="profile-svg profile-svg-settings" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"/><circle cx="12" cy="12" r="3"/></svg>';
        removeSystemDocIndicator: removeSystemDocIndicatorForShell,
var CLBI_SVG_SCAN_TEXT = '<svg class="profile-svg profile-svg-scan-text" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 7V5a2 2 0 0 1 2-2h2"/><path d="M17 3h2a2 2 0 0 1 2 2v2"/><path d="M21 17v2a2 2 0 0 1-2 2h-2"/><path d="M7 21H5a2 2 0 0 1-2-2v-2"/><path d="M7 8h8"/><path d="M7 12h10"/><path d="M7 16h6"/></svg>';
        refreshSystemDocSourceViewer: renderSystemDocSourceViewerForShell
var CLBI_SVG_SCAN_EYE = '<svg class="profile-svg profile-svg-scan-eye" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 7V5a2 2 0 0 1 2-2h2"/><path d="M17 3h2a2 2 0 0 1 2 2v2"/><path d="M21 17v2a2 2 0 0 1-2 2h-2"/><path d="M7 21H5a2 2 0 0 1-2-2v-2"/><circle cx="12" cy="12" r="1"/><path d="M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0"/></svg>';
    };
var CLBI_SVG_NEWSPAPER = '<svg class="profile-svg profile-svg-newspaper" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 18h-5"/><path d="M18 14h-8"/><path d="M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-4 0v-9a2 2 0 0 1 2-2h2"/><rect width="8" height="4" x="10" y="6" rx="1"/></svg>';
}());
var CLBI_SVG_GREAT_WALL = '<svg class="profile-svg profile-svg-great-wall lucide lucide-paint-roller" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect width="16" height="6" x="2" y="2" rx="2"/><path d="M10 16v-2a2 2 0 0 1 2-2h8a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2"/><rect width="4" height="6" x="8" y="16" rx="1"/></svg>';
var CLBI_SVG_TROPHY = '<svg class="profile-svg profile-svg-trophy" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 14.66v1.626a2 2 0 0 1-.976 1.696A5 5 0 0 0 7 21.978"/><path d="M14 14.66v1.626a2 2 0 0 0 .976 1.696A5 5 0 0 1 17 21.978"/><path d="M18 9h1.5a1 1 0 0 0 0-5H18"/><path d="M4 22h16"/><path d="M6 9a6 6 0 0 0 12 0V3a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1z"/><path d="M6 9H4.5a1 1 0 0 1 0-5H6"/></svg>';
var CLBI_SVG_PACKAGE = '<svg class="profile-svg profile-svg-package" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3v6"/><path d="M16.76 3a2 2 0 0 1 1.8 1.1l2.23 4.479a2 2 0 0 1 .21.891V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V9.472a2 2 0 0 1 .211-.894L5.45 4.1A2 2 0 0 1 7.24 3z"/><path d="M3.054 9.013h17.893"/></svg>';


var PROFILE_RENDER_TOKEN = 0;
function loadLangScript(done) {
 
    $.getScript('/index.php?title=미디어위키:Lang.js&action=raw&ctype=text/javascript')
function invalidateProfileRender() {
        .done(function() {
    PROFILE_RENDER_TOKEN++;
            if (typeof done === 'function') done();
        })
        .fail(function(a, b, c) {
            console.error('Lang.js load failed:', b, c);
            if (typeof done === 'function') done();
        });
}
}


$(function() {
    initHalftoneBackground();


// ── 하단 Plank 단축키 가이드 ──
/*
function escapeClbiBottomGuideHtml(value) {
DevTools 같은 내부 스크롤은 셸 레이아웃을 바꾸지 않는다. 이 짧은 상호작용 동안
    return String(value == null ? '' : value)
전체 화면 WebGL/CRT가 새 GPU 프레임을 계속 제출하면, transform 셸과 고정 네비의
        .replace(/&/g, '&amp;')
합성 타일 갱신이 서로 경합한다. 마지막 정상 프레임은 그대로 유지하고 시각 시계도
        .replace(/</g, '&lt;')
정지시켜, 스크롤 종료 후 끊김 없이 이어지게 한다.
        .replace(/>/g, '&gt;')
*/
        .replace(/"/g, '&quot;')
var CLBI_COMPOSITOR_BUSY_UNTIL = 0;
        .replace(/'/g, '&#039;');
}


function readClbiBottomGuidePageName() {
function markClbiCompositorBusy(duration) {
     var pageName = window.mw && mw.config ? (mw.config.get('wgPageName') || '') : '';
     var now = window.performance && performance.now ? performance.now() : Date.now();
 
     CLBI_COMPOSITOR_BUSY_UNTIL = Math.max(CLBI_COMPOSITOR_BUSY_UNTIL, now + Math.max(80, Number(duration) || 140));
    if (!pageName) {
        pageName = window.location.pathname || '';
     }
 
    return String(pageName)
        .split('?')[0]
        .replace(/^\/index\.php\//, '')
        .replace(/_/g, ' ')
        .trim();
}
}


function isClbiNationsShortcutContext() {
function isClbiCompositorBusy() {
     var pageName = readClbiBottomGuidePageName();
     var now = window.performance && performance.now ? performance.now() : Date.now();
 
     return now < CLBI_COMPOSITOR_BUSY_UNTIL;
     return pageName === '국가 및 조합' ||
        pageName === 'Nations & Factions' ||
        !!document.querySelector('.clbi-nations-panel-stack, .clbi-nations-globe-window, .clbi-nations-tabpanel');
}
}


function isClbiWikiEditShortcutContext() {
window.markClbiCompositorBusy = markClbiCompositorBusy;
    var action = window.mw && mw.config ? String(mw.config.get('wgAction') || '') : '';
window.isClbiCompositorBusy = isClbiCompositorBusy;
    var search = String(window.location.search || '');


    return action === 'edit' ||
if (!window.CLBI_COMPOSITOR_ACTIVITY_BOUND) {
        action === 'submit' ||
    window.CLBI_COMPOSITOR_ACTIVITY_BOUND = true;
        /(?:^|[?&])action=(?:edit|submit)(?:&|$)/.test(search) ||
        !!document.querySelector('#editform, #wpSave, input[name="wpSave"], button[name="wpSave"]');
}


    document.addEventListener('scroll', function (event) {
        var target = event.target && event.target.nodeType === 1 ? event.target : null;
        if (target && target.closest && target.closest('#dev-tools-panel')) {
            markClbiCompositorBusy(160);
        }
    }, true);


function isClbiNationListManagerShortcutContext() {
    document.addEventListener('wheel', function (event) {
    return !!document.querySelector('.nation-list-manager');
        var target = event.target && event.target.nodeType === 1 ? event.target : null;
        if (target && target.closest && target.closest('#dev-tools-panel')) {
            markClbiCompositorBusy(160);
        }
    }, { capture:true, passive:true });
}
}


function getClbiBottomShortcutItems() {
function initHalftoneBackground() {
     if (isClbiWikiEditShortcutContext()) {
     try {
        return [
         initWebGLHalftoneBackground();
            { key: 'Ctrl+S', label: '변경사항 저장' }
     } catch (err) {
         ];
         console.error('WebGL halftone background failed:', err);
    }
 
 
    if (isClbiNationListManagerShortcutContext()) {
        return [
            { key: 'Ctrl+S', label: '국가 목록 저장' }
        ];
     }
 
    if (isClbiNationsShortcutContext()) {
         return [
            { key: 'Q', label: '이전 시대' },
            { key: 'E', label: '다음 시대' },
            { key: 'Shift+Q', label: '이전 연도' },
            { key: 'Shift+E', label: '다음 연도' },
            { key: 'Ctrl+Q', label: '이전 대륙' },
            { key: 'Ctrl+E', label: '다음 대륙' }
        ];
     }
     }
    return [];
}
}


function renderClbiBottomShortcutGuide() {
function initWebGLHalftoneBackground() {
     var guide = document.getElementById('clbi-bottom-shortcut-guide');
     var canvasId = 'site-halftone-bg';
     var items;
    var existing = document.getElementById(canvasId);
     var html;
    var canvas = existing || document.createElement('canvas');
     var halftoneState = window.SiteHalftoneBackgroundState || (window.SiteHalftoneBackgroundState = { runId: 0 });
     var runId = halftoneState.runId + 1;


     if (!guide) return;
     halftoneState.runId = runId;


    items = getClbiBottomShortcutItems();
     if (!existing) {
 
         canvas.id = canvasId;
     if (!items.length) {
        canvas.setAttribute('aria-hidden', 'true');
         guide.classList.add('is-empty');
         document.body.insertBefore(canvas, document.body.firstChild || null);
         guide.innerHTML = '';
        return;
     }
     }


     guide.classList.remove('is-empty');
     canvas.style.position = 'fixed';
    canvas.style.inset = '0';
    canvas.style.width = '100vw';
    canvas.style.height = '100vh';
    canvas.style.pointerEvents = 'none';
    canvas.style.background = '#000000';
    canvas.style.display = 'block';


     html = '<div class="clbi-bottom-shortcut-list">';
     if (!canvas.getAttribute('data-halftone-context-watch')) {
        canvas.setAttribute('data-halftone-context-watch', '1');
        canvas.addEventListener('webglcontextlost', function (event) {
            event.preventDefault();
            canvas.style.display = 'none';
            if (window.SiteHalftoneBackgroundState) {
                window.SiteHalftoneBackgroundState.contextLost = true;
                window.SiteHalftoneBackgroundState.runId += 1;
            }
        }, false);
        canvas.addEventListener('webglcontextrestored', function () {
            if (window.SiteHalftoneBackgroundState) {
                window.SiteHalftoneBackgroundState.contextLost = false;
            }
            window.setTimeout(initWebGLHalftoneBackground, 0);
        }, false);
    }


     items.forEach(function (item) {
     var gl = canvas.getContext('webgl', {
         html += '<div class="clbi-bottom-shortcut-item">' +
         alpha: false,
            '<span class="clbi-bottom-shortcut-key">' + escapeClbiBottomGuideHtml(item.key) + '</span>' +
        antialias: false,
            '<span class="clbi-bottom-shortcut-label">' + escapeClbiBottomGuideHtml(item.label) + '</span>' +
        depth: false,
         '</div>';
        stencil: false,
     });
        preserveDrawingBuffer: false,
         powerPreference: 'low-power'
     }) || canvas.getContext('experimental-webgl');


     html += '</div>';
     if (!gl) {
    guide.innerHTML = html;
         canvas.style.display = 'none';
}
        console.warn('WebGL background unavailable.');
 
function buildClbiBottomPlankHtml(wrapId, navId, mainId) {
    return '' +
         '<div id="' + wrapId + '">' +
            '<div id="' + navId + '">' +
                '<div id="' + mainId + '">' +
                    '<div id="clbi-bottom-shortcut-guide" class="is-empty" aria-label="단축키 안내"></div>' +
                '</div>' +
            '</div>' +
        '</div>';
}
 
var CLBI_NATIONS_LAST_POINTER_X = null;
var CLBI_NATIONS_LAST_POINTER_Y = null;
 
function getClbiNationsTabAtPointer(tabpanel) {
    var element;
    var tab;
 
    if (!tabpanel) return null;
    if (CLBI_NATIONS_LAST_POINTER_X === null || CLBI_NATIONS_LAST_POINTER_Y === null) return null;
    if (typeof document.elementFromPoint !== 'function') return null;
 
    element = document.elementFromPoint(CLBI_NATIONS_LAST_POINTER_X, CLBI_NATIONS_LAST_POINTER_Y);
    if (!element) return null;
 
    tab = element.closest ? element.closest('.clbi-nations-tabpanel-tab[data-continent]') : null;
 
    if (!tab || !tabpanel.contains(tab)) return null;
 
    return tab;
}
 
function validateClbiNationsPointerHover(tabpanel, forceSuppress) {
    var tab = getClbiNationsTabAtPointer(tabpanel);
    var suppressContinent;
    var tabContinent;
    var tabIsActive;
 
    if (!tabpanel) return;
 
    if (!tab) {
        clearClbiNationsKeyboardHoverSuppressed(tabpanel);
         return;
         return;
     }
     }


     tabContinent = tab.getAttribute('data-continent') || '';
     var vertexSrc = [
    tabIsActive = tab.classList.contains('is-active') || tab.getAttribute('aria-selected') === 'true';
        'attribute vec2 a_position;',
        'void main() {',
        ' gl_Position = vec4(a_position, 0.0, 1.0);',
        '}'
    ].join('\n');


     if (tabIsActive) {
     var fragmentSrc = [
         clearClbiNationsKeyboardHoverSuppressed(tabpanel);
        'precision mediump float;',
         return;
        'uniform vec2 u_resolution;',
    }
        'uniform float u_time;',
 
        'const float TAU = 6.28318530718;',
    suppressContinent = tabpanel.getAttribute('data-clbi-hover-suppress-continent') || '';
        'float gaussian(float v, float r) {',
 
         '  return exp(-((v * v) / max(0.0001, r * r)));',
    if (forceSuppress || !suppressContinent) {
        '}',
         tabpanel.classList.add('is-keyboard-switching');
        'float hash(vec2 p) {',
         tabpanel.setAttribute('data-clbi-hover-suppress-continent', tabContinent);
         return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453123);',
         return;
        '}',
    }
        'float bucketAlpha(float a) {',
 
        '  float i = floor(a * 9.0);',
    if (suppressContinent === tabContinent) {
        '  if (i < 1.0) return 0.040;',
         tabpanel.classList.add('is-keyboard-switching');
        ' if (i < 2.0) return 0.080;',
         return;
        ' if (i < 3.0) return 0.135;',
    }
        '  if (i < 4.0) return 0.210;',
 
        '  if (i < 5.0) return 0.310;',
    /*
         '  if (i < 6.0) return 0.430;',
    * The pointer actually moved onto another tab after the keyboard switch.
        '  if (i < 7.0) return 0.580;',
    * At that point this is no longer stale browser :hover; let normal hover work.
        ' if (i < 8.0) return 0.760;',
    */
         '  return 0.920;',
    clearClbiNationsKeyboardHoverSuppressed(tabpanel);
        '}',
}
        'void main() {',
 
        '  vec2 frag = gl_FragCoord.xy;',
function validateAllClbiNationsPointerHovers() {
        '  float spacing = 5.0;',
    var panels = document.querySelectorAll('.clbi-nations-tabpanel.is-keyboard-switching');
        '  float dotSize = 1.08;',
 
        '  vec2 grid = floor(frag / spacing);',
    Array.prototype.forEach.call(panels, function (tabpanel) {
         '  vec2 inCell = mod(frag, spacing);',
         if (isClbiNationsPanelOwnedTabpanel(tabpanel)) return;
        '  vec2 dotOrigin = vec2(1.0, 1.0);',
         validateClbiNationsPointerHover(tabpanel, false);
        '  vec2 dotCenter = dotOrigin + vec2(dotSize * 0.5);',
     });
        '  vec2 local = abs(inCell - dotCenter);',
}
        '  float noise = hash(grid);',
        '  float size = dotSize + noise * 0.18;',
        '  float dotMask = 1.0 - smoothstep(size * 0.5, size * 0.5 + 0.22, max(local.x, local.y));',
        '  vec2 uv = frag / u_resolution;',
        '  float centerLine = 0.50 +',
         '    sin((uv.y * 1.32 + 0.08) * TAU) * 0.070 +',
        '    sin((uv.y * 3.18 + 0.34) * TAU) * 0.030;',
        ' float u = uv.x - centerLine;',
        ' float absU = abs(u);',
         '  float sideLift = smoothstep(0.065, 0.44, absU);',
        '  float valley = gaussian(u, 0.150);',
        '  float t = u_time;',
        '  float leftRibbonCenter = -0.28 + sin((uv.y * 3.20 + 0.12) * TAU) * 0.050;',
        '  float rightRibbonCenter = 0.27 + sin((uv.y * 2.85 + 0.56) * TAU) * 0.055;',
        '  float leftRibbon = gaussian(u - leftRibbonCenter, 0.105);',
        '  float rightRibbon = gaussian(u - rightRibbonCenter, 0.110);',
        '  float foldedU = u +',
        '    sin((uv.y * 4.40 + 0.22) * TAU) * 0.050 * (0.3 + sideLift) +',
        '    sin((uv.y * 7.20 + uv.x * 1.10) * TAU) * 0.022;',
        '  float verticalFold = pow(0.5 + 0.5 * cos(((foldedU * 3.05) + (sin(uv.y * TAU * 2.35) * 0.18)) * TAU), 2.5);',
        '  float diagonalFold = pow(0.5 + 0.5 * cos(((foldedU * 1.80) - (uv.y * 1.12) + 0.18) * TAU), 2.1);',
        ' float waist = gaussian(uv.y - 0.50, 0.25) * gaussian(absU - 0.20, 0.19);',
        '  float grain = (noise - 0.5) * 0.050;',
        '  float staticField =',
        '    0.055 +',
        '    sideLift * 0.210 +',
        '    (leftRibbon + rightRibbon) * 0.145 +',
        '    verticalFold * (0.055 + sideLift * 0.115) +',
        '    diagonalFold * 0.045 +',
        '    waist * 0.060 -',
        '    valley * 0.150 +',
        '    grain;',
        '  float alpha = staticField;',
        '  alpha += 0.115 * (leftRibbon + rightRibbon) * sin(t * 0.00030 + ((uv.y * 1.9) + sideLift * 0.4) * TAU);',
        '  alpha += 0.095 * verticalFold * (0.4 + sideLift) * sin(t * 0.00041 + ((uv.y * 2.7) + foldedU * 0.65) * TAU);',
        '  alpha += 0.070 * waist * sin(t * 0.00053 + ((uv.y * 3.1) - absU * 0.8) * TAU);',
        '  alpha += 0.060 * (1.0 - valley) * diagonalFold * sin(t * 0.00067 + ((uv.y * 1.4) + uv.x * 0.6) * TAU);',
        '  alpha += 0.038 * (0.35 + sideLift) * (0.35 + noise) * sin(t * 0.00079 + ((uv.y * 4.6) + noise * 0.8) * TAU);',
         '  alpha = bucketAlpha(clamp(alpha, 0.025, 0.96));',
        '  float value = alpha * dotMask;',
         '  gl_FragColor = vec4(vec3(0.8862745 * value), 1.0);',
        '}'
     ].join('\n');
 
    function compileShader(type, source) {
        var shader = gl.createShader(type);
        gl.shaderSource(shader, source);
        gl.compileShader(shader);


function isClbiNationsPanelOwnedTabpanel(tabpanel) {
        if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
    /*
            console.error('WebGL shader compile error:', gl.getShaderInfoLog(shader));
    * Mouse continent tab regression guard.
            gl.deleteShader(shader);
    * -------------------------------------
            return null;
    * Detached SPA preparation serializes attributes/classes but it cannot
        }
    * serialize DOM event listeners or JS properties.  The NationsPanel fix
    * therefore uses the DOM property CLBI_NationsPanelOwned /
    * CLBI_NationsTabPanelBound as the real ownership marker.
    *
    * Do NOT treat data-nations-tabpanel-ready or clbi-nations-continent-cache
    * as ownership here.  Those can survive innerHTML insertion while the real
    * click listeners were lost, causing Common.js to delegate to a panel that
    * NationsPanel has not rebound yet. The fallback below must remain able to
    * handle mouse clicks until NationsPanel reclaims the live DOM node.
    */
    return !!(tabpanel && tabpanel.CLBI_NationsPanelOwned);
}


function isClbiNationsLiveContinentActive(tabpanel, continent) {
        return shader;
    var tab;
     }
     var panel;


     if (!tabpanel || !continent) return false;
     var vertexShader = compileShader(gl.VERTEX_SHADER, vertexSrc);
    var fragmentShader = compileShader(gl.FRAGMENT_SHADER, fragmentSrc);


     tab = Array.prototype.slice.call(tabpanel.querySelectorAll('.clbi-nations-tabpanel-tab[data-continent]')).find(function (candidate) {
     if (!vertexShader || !fragmentShader) return;
        return candidate.getAttribute('data-continent') === continent;
    });


     panel = Array.prototype.slice.call(tabpanel.querySelectorAll('.clbi-nations-tabpanel-continent[data-continent-panel]')).find(function (candidate) {
     var program = gl.createProgram();
        return candidate.getAttribute('data-continent-panel') === continent;
    gl.attachShader(program, vertexShader);
     });
    gl.attachShader(program, fragmentShader);
     gl.linkProgram(program);


     return !!(
     if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
        tab &&
         console.error('WebGL program link error:', gl.getProgramInfoLog(program));
        panel &&
         return;
        (tab.classList.contains('is-active') || tab.getAttribute('aria-selected') === 'true') &&
     }
         panel.classList.contains('is-active') &&
        panel.getAttribute('aria-hidden') !== 'true' &&
         !panel.hasAttribute('hidden')
     );
}


function activateClbiNationsContinent(tabpanel, targetContinent, options) {
    var positionLoc = gl.getAttribLocation(program, 'a_position');
    var tabs;
     var resolutionLoc = gl.getUniformLocation(program, 'u_resolution');
     var panels;
     var timeLoc = gl.getUniformLocation(program, 'u_time');
     var skipOwner = !!(options && options.skipOwner);


     if (!tabpanel || !targetContinent) return false;
     var buffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
        -1, -1,
        1, -1,
        -1,  1,
        -1,  1,
        1, -1,
        1,  1
    ]), gl.STATIC_DRAW);


     if (!skipOwner && isClbiNationsPanelOwnedTabpanel(tabpanel)) {
     gl.useProgram(program);
        var owner = window.NationsPanel || window.CLBI_NATIONS_PANEL || null;
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
    gl.enableVertexAttribArray(positionLoc);
    gl.vertexAttribPointer(positionLoc, 2, gl.FLOAT, false, 0, 0);


         if (owner && typeof owner.activateContinent === 'function') {
    function resize() {
            try {
         var dpr = Math.min(window.devicePixelRatio || 1, 1.5);
                if (owner.activateContinent(targetContinent, {
        var cssW = Math.max(1, window.innerWidth || document.documentElement.clientWidth || 1);
                    source: 'common-legacy-click',
        var cssH = Math.max(1, window.innerHeight || document.documentElement.clientHeight || 1);
                    panel: tabpanel
        var w = Math.max(1, Math.floor(cssW * dpr));
                })) {
        var h = Math.max(1, Math.floor(cssH * dpr));
                    return true;
 
                }
        if (canvas.width !== w || canvas.height !== h) {
             } catch (err) {}
            canvas.width = w;
            canvas.height = h;
            canvas.style.width = cssW + 'px';
            canvas.style.height = cssH + 'px';
             gl.viewport(0, 0, w, h);
         }
         }
    }


         /*
    var prefersReducedMotion = false;
        * Ownership markers can be stale during SPA/hydration edge cases.  If
    try {
        * the owner API is missing or refuses the live panel, do not drop the
         prefersReducedMotion = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
        * mouse click. Fall through to the local fallback so pointer users are
    } catch (err) {}
        * never left with keyboard-only continent tabs.
 
        */
    function getNationsGlobeHalftoneNode() {
        return document.querySelector('.clbi-nations-globe-window[data-nations-globe], [data-nations-globe="real-world"]');
     }
     }


     tabs = Array.prototype.slice.call(tabpanel.querySelectorAll('.clbi-nations-tabpanel-tab[data-continent]'));
     function getNationsGlobeHalftoneState() {
    panels = Array.prototype.slice.call(tabpanel.querySelectorAll('.clbi-nations-tabpanel-continent[data-continent-panel]'));
        var globe = getNationsGlobeHalftoneNode();
        var instance;


    if (!tabs.length || !panels.length) return false;
        if (!globe) {
            return 'none';
        }


    tabs.forEach(function (tab) {
        if (globe.classList && globe.classList.contains('is-dragging')) {
        var active = tab.getAttribute('data-continent') === targetContinent;
            return 'active';
        tab.classList.toggle('is-active', active);
         }
        tab.setAttribute('aria-selected', active ? 'true' : 'false');
         tab.setAttribute('tabindex', active ? '0' : '-1');
    });


    panels.forEach(function (panel) {
        instance = globe.CLBI_NationsGlobeInstance || null;
        var active = panel.getAttribute('data-continent-panel') === targetContinent;
        if (instance && typeof instance.isHalftoneBackgroundBusy === 'function' && instance.isHalftoneBackgroundBusy()) {
         panel.classList.toggle('is-active', active);
            return 'busy';
         }


         if (active) {
         if (globe.getAttribute && globe.getAttribute('data-clbi-globe-bg-busy') === '1') {
            panel.removeAttribute('hidden');
             return 'busy';
        } else {
             panel.setAttribute('hidden', 'hidden');
         }
         }
    });


     try {
        return 'present';
        if (window.Decorations && typeof window.Decorations.sync === 'function') window.Decorations.sync();
     }
         else if (window.CLBI_DECORATIONS && typeof window.CLBI_DECORATIONS.sync === 'function') window.CLBI_DECORATIONS.sync();
 
    } catch (err) {}
    function shouldSkipHalftoneDrawForGlobe() {
         var globe = getNationsGlobeHalftoneNode();
        var instance;


    return true;
        if (!globe) return false;
}


function setClbiNationsKeyboardHoverSuppressed(tabpanel) {
        instance = globe.CLBI_NationsGlobeInstance || null;
    validateClbiNationsPointerHover(tabpanel, true);
}


function clearClbiNationsKeyboardHoverSuppressed(tabpanel) {
        /*
    if (!tabpanel) return;
        * Background pause/resume — 20260710.
    tabpanel.classList.remove('is-keyboard-switching');
        *
    tabpanel.removeAttribute('data-clbi-hover-suppress-continent');
        * While the nations globe is being held, keep the last rendered halftone
}
        * frame on screen and pause the halftone clock.  The important detail is
        * that this is not a wall-clock catch-up: skipped seconds are not replayed
        * or fast-forwarded when the pointer is released.
        */
        if (globe.classList && globe.classList.contains('is-dragging')) return true;
        if (instance && instance.dragging) return true;
 
        if (instance && typeof instance.isHalftoneBackgroundHardBusy === 'function') {
            return instance.isHalftoneBackgroundHardBusy();
        }
 
        if (globe.getAttribute && globe.getAttribute('data-clbi-globe-bg-busy') === '1') return true;


function moveClbiNationsContinent(direction) {
        return false;
    var tabpanel = document.querySelector('.clbi-nations-tabpanel');
     }
    var tabs;
    var activeIndex;
    var nextIndex;
     var target;


     if (!tabpanel) return false;
     function getFrameInterval() {
        if (prefersReducedMotion) {
            return 1000;
        }


    if (isClbiNationsPanelOwnedTabpanel(tabpanel) &&
        /*
        window.CLBI_NATIONS_PANEL &&
        * Nations background parity — 20260710.
        typeof window.CLBI_NATIONS_PANEL.moveContinent === 'function') {
        *
        return !!window.CLBI_NATIONS_PANEL.moveContinent(direction, {
        * The nations page used to permanently lower the halftone cadence while
            source: 'common-legacy-keyboard',
        * the globe existed. Profiling showed that the steady halftone draw is
            panel: tabpanel
        * normally cheap; the real contention happens during globe drag, first
         });
        * WebGL texture upload, and long layout/render tasks. Keep the same
        * full-quality cadence as ordinary pages, and skip only the frames that
        * would directly collide with an active/busy globe moment.
        */
         return 66;
     }
     }


     tabs = Array.prototype.slice.call(tabpanel.querySelectorAll('.clbi-nations-tabpanel-tab[data-continent]'));
     var lastFrame = 0;
    if (!tabs.length) return false;
    var startTime = performance.now();
    var visualTime = 0;
    var lastVisualNow = 0;
 
    function draw(now) {
        var state = getNationsGlobeHalftoneState();
        var interval = getFrameInterval();
        var perf = window.InteractionPerf;
        var delta;
 
        if (!lastVisualNow) {
            lastVisualNow = now;
        }
        delta = Math.max(0, Math.min(120, now - lastVisualNow));
        lastVisualNow = now;
        visualTime += delta;
 
        function runDraw() {
            resize();


    activeIndex = tabs.findIndex(function (tab) {
            gl.clearColor(0, 0, 0, 1);
        return tab.classList.contains('is-active') || tab.getAttribute('aria-selected') === 'true';
            gl.clear(gl.COLOR_BUFFER_BIT);
    });
            gl.uniform2f(resolutionLoc, canvas.width, canvas.height);
            gl.uniform1f(timeLoc, visualTime);
            gl.drawArrays(gl.TRIANGLES, 0, 6);
        }


    if (activeIndex < 0) activeIndex = 0;
        if (perf && typeof perf.measureSync === 'function') {
            return perf.measureSync('background halftone draw', { globeState: state, interval: interval }, runDraw);
        }
        return runDraw();
    }


     nextIndex = (activeIndex + direction + tabs.length) % tabs.length;
     var frameTimer = 0;
     target = tabs[nextIndex].getAttribute('data-continent');
     var frameRaf = 0;


     if (activateClbiNationsContinent(tabpanel, target)) {
     function scheduleNextFrame(delay) {
         setClbiNationsKeyboardHoverSuppressed(tabpanel);
         window.clearTimeout(frameTimer);
         window.setTimeout(function () {
         frameTimer = window.setTimeout(function () {
             validateClbiNationsPointerHover(tabpanel, false);
             frameTimer = 0;
        }, 0);
            if (halftoneState.runId !== runId || halftoneState.contextLost) return;
         return true;
            if (window.requestAnimationFrame) {
                frameRaf = window.requestAnimationFrame(render);
            } else {
                render(performance.now());
            }
         }, Math.max(16, Number(delay) || getFrameInterval()));
     }
     }


     return false;
     function render(now) {
}
        var interval = getFrameInterval();


function initClbiNationsTabpanelControls(root) {
        frameRaf = 0;
    var scope = root && root.querySelectorAll ? root : document;
        if (halftoneState.runId !== runId || halftoneState.contextLost) return;
    var panels = scope.querySelectorAll('.clbi-nations-tabpanel');


    Array.prototype.forEach.call(panels, function (tabpanel) {
        if (document.hidden) {
        /*
            lastVisualNow = now;
        * Common.js is only a safety fallback for continent tabs; NationsPanel
            scheduleNextFrame(250);
        * is the primary owner.  This guard must be a DOM property, not a
            return;
        * serialized attribute.  SPA warm prepaint can preserve
         }
        * data-clbi-nations-tabs-ready="1" while losing the actual event
        * listeners, which was the root cause of mouse clicks no longer moving
        * continents while keyboard shortcuts still worked.
        */
        if (tabpanel.CLBI_NationsCommonTabsBound) return;
        tabpanel.CLBI_NationsCommonTabsBound = true;
         tabpanel.setAttribute('data-clbi-nations-tabs-ready', '1');


         tabpanel.addEventListener('pointerdown', function () {
         if (isClbiCompositorBusy()) {
             clearClbiNationsKeyboardHoverSuppressed(tabpanel);
             lastFrame = now;
         });
            lastVisualNow = now;
            scheduleNextFrame(interval);
            return;
         }


         tabpanel.addEventListener('pointerleave', function () {
         if (shouldSkipHalftoneDrawForGlobe()) {
             clearClbiNationsKeyboardHoverSuppressed(tabpanel);
             lastFrame = now;
         });
            halftoneState.lastGlobeBusySkipAt = now;
            lastVisualNow = now;
            scheduleNextFrame(interval);
            return;
         }


         tabpanel.addEventListener('click', function (event) {
         lastFrame = now;
            var tab = event.target.closest ? event.target.closest('.clbi-nations-tabpanel-tab[data-continent]') : null;
        draw(now);
        scheduleNextFrame(interval);
    }


            if (!tab || !tabpanel.contains(tab)) return;
    draw(performance.now());
    scheduleNextFrame(getFrameInterval());


             clearClbiNationsKeyboardHoverSuppressed(tabpanel);
    document.addEventListener('visibilitychange', function () {
        if (!document.hidden && halftoneState.runId === runId && !halftoneState.contextLost) {
            window.clearTimeout(frameTimer);
            if (frameRaf && window.cancelAnimationFrame) window.cancelAnimationFrame(frameRaf);
            frameRaf = 0;
             scheduleNextFrame(16);
        }
    });


            if (activateClbiNationsContinent(tabpanel, tab.getAttribute('data-continent'))) {
}
                event.preventDefault();
            }
        });


        tabpanel.addEventListener('keydown', function (event) {
var CLBI_SVG_BELL = '<svg class="profile-svg profile-svg-bell" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10.268 21a2 2 0 0 0 3.464 0"/><path d="M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"/></svg>';
            var tab = event.target.closest ? event.target.closest('.clbi-nations-tabpanel-tab[data-continent]') : null;
var CLBI_SVG_BELL_DOT = '<svg class="profile-svg profile-svg-bell-dot" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10.268 21a2 2 0 0 0 3.464 0"/><path d="M11.68 2.009A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673c-.824-.85-1.678-1.731-2.21-3.348"/><circle cx="18" cy="5" r="3"/></svg>';
            var handled = false;
var CLBI_SVG_LIST = '<svg class="profile-svg profile-svg-list" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 5h.01"/><path d="M3 12h.01"/><path d="M3 19h.01"/><path d="M8 5h13"/><path d="M8 12h13"/><path d="M8 19h13"/></svg>';
var CLBI_SVG_LANGUAGES = '<svg class="profile-svg profile-svg-languages" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 8 6 6"/><path d="m4 14 6-6 2-3"/><path d="M2 5h12"/><path d="M7 2h1"/><path d="m22 22-5-10-5 10"/><path d="M14 18h6"/></svg>';
var CLBI_SVG_POWER = '<svg class="profile-svg profile-svg-power" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 2v10"/><path d="M18.4 6.6a9 9 0 1 1-12.77.04"/></svg>';
var CLBI_SVG_SETTINGS = '<svg class="profile-svg profile-svg-settings" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"/><circle cx="12" cy="12" r="3"/></svg>';
var CLBI_SVG_SCAN_TEXT = '<svg class="profile-svg profile-svg-scan-text" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 7V5a2 2 0 0 1 2-2h2"/><path d="M17 3h2a2 2 0 0 1 2 2v2"/><path d="M21 17v2a2 2 0 0 1-2 2h-2"/><path d="M7 21H5a2 2 0 0 1-2-2v-2"/><path d="M7 8h8"/><path d="M7 12h10"/><path d="M7 16h6"/></svg>';
var CLBI_SVG_SCAN_EYE = '<svg class="profile-svg profile-svg-scan-eye" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 7V5a2 2 0 0 1 2-2h2"/><path d="M17 3h2a2 2 0 0 1 2 2v2"/><path d="M21 17v2a2 2 0 0 1-2 2h-2"/><path d="M7 21H5a2 2 0 0 1-2-2v-2"/><circle cx="12" cy="12" r="1"/><path d="M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0"/></svg>';
var CLBI_SVG_NEWSPAPER = '<svg class="profile-svg profile-svg-newspaper" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 18h-5"/><path d="M18 14h-8"/><path d="M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-4 0v-9a2 2 0 0 1 2-2h2"/><rect width="8" height="4" x="10" y="6" rx="1"/></svg>';
var CLBI_SVG_GREAT_WALL = '<svg class="profile-svg profile-svg-great-wall lucide lucide-paint-roller" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect width="16" height="6" x="2" y="2" rx="2"/><path d="M10 16v-2a2 2 0 0 1 2-2h8a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2"/><rect width="4" height="6" x="8" y="16" rx="1"/></svg>';
var CLBI_SVG_TROPHY = '<svg class="profile-svg profile-svg-trophy" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 14.66v1.626a2 2 0 0 1-.976 1.696A5 5 0 0 0 7 21.978"/><path d="M14 14.66v1.626a2 2 0 0 0 .976 1.696A5 5 0 0 1 17 21.978"/><path d="M18 9h1.5a1 1 0 0 0 0-5H18"/><path d="M4 22h16"/><path d="M6 9a6 6 0 0 0 12 0V3a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1z"/><path d="M6 9H4.5a1 1 0 0 1 0-5H6"/></svg>';
var CLBI_SVG_PACKAGE = '<svg class="profile-svg profile-svg-package" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3v6"/><path d="M16.76 3a2 2 0 0 1 1.8 1.1l2.23 4.479a2 2 0 0 1 .21.891V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V9.472a2 2 0 0 1 .211-.894L5.45 4.1A2 2 0 0 1 7.24 3z"/><path d="M3.054 9.013h17.893"/></svg>';


            if (!tab || !tabpanel.contains(tab)) return;
var PROFILE_RENDER_TOKEN = 0;


            if (event.key === 'ArrowLeft') handled = moveClbiNationsContinent(-1);
function invalidateProfileRender() {
            else if (event.key === 'ArrowRight') handled = moveClbiNationsContinent(1);
     PROFILE_RENDER_TOKEN++;
 
            if (handled) {
                event.preventDefault();
                event.stopPropagation();
            }
        });
     });
}
}


function handleClbiNationsContinentDocumentClick(event) {
$(function() {
     var target;
     initHalftoneBackground();
    var tab;
    var tabpanel;
    var continent;
    var owner;
    var handled = false;


     if (!event || event.__clbiNationsContinentHandled) return;
// ── 하단 Plank 단축키 가이드 ──
    target = event.target;
function escapeClbiBottomGuideHtml(value) {
    if (!target || !target.closest) return;
     return String(value == null ? '' : value)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}


     tab = target.closest('.clbi-nations-tabpanel-tab[data-continent]');
function readClbiBottomGuidePageName() {
    if (!tab) return;
     var pageName = window.mw && mw.config ? (mw.config.get('wgPageName') || '') : '';


     tabpanel = tab.closest ? tab.closest('.clbi-nations-tabpanel') : null;
     if (!pageName) {
     if (!tabpanel || !tabpanel.contains(tab)) return;
        pageName = window.location.pathname || '';
     }


     continent = tab.getAttribute('data-continent') || '';
     return String(pageName)
    if (!continent) return;
        .split('?')[0]
        .replace(/^\/index\.php\//, '')
        .replace(/_/g, ' ')
        .trim();
}


    /*
function isClbiNationsShortcutContext() {
    * Final live-DOM mouse delegate.
     var pageName = readClbiBottomGuidePageName();
    * --------------------------------
    * The continent tab UI has two initialization phases: detached preparation
    * for seamless SPA entry, then live DOM hydration.  Detached preparation can
    * leave serialized "ready" attributes behind while losing event listeners.
    * Keyboard shortcuts still work because they call the public NationsPanel
    * API directly, but mouse clicks depend on live listeners.  This capturing
    * delegate is intentionally independent of per-panel ready attributes: it
    * always resolves the clicked live tab and hands it to NationsPanel first,
    * then falls back to the local Common.js switcher if needed.
    */
     event.__clbiNationsContinentHandled = true;
    clearClbiNationsKeyboardHoverSuppressed(tabpanel);


     owner = window.NationsPanel || window.CLBI_NATIONS_PANEL || null;
     return pageName === '시대' ||
    if (owner && typeof owner.activateContinent === 'function') {
        pageName === 'Era' ||
         try {
         !!document.querySelector('.clbi-nations-panel-stack, .clbi-nations-globe-window, .clbi-nations-tabpanel');
            handled = !!owner.activateContinent(continent, {
}
                source: 'mouse-click-live-delegate',
                panel: tabpanel
            });
        } catch (err) {
            handled = false;
        }


        /*
function isClbiWikiEditShortcutContext() {
        * Owner API stale-cache guard.
    var action = window.mw && mw.config ? String(mw.config.get('wgAction') || '') : '';
        *
    var search = String(window.location.search || '');
        * A previous regression came from NationsPanel returning true after it
 
        * updated cached/detached tab nodes instead of the clicked live tab. A
    return action === 'edit' ||
        * true return value alone is therefore not enough for mouse input. Verify
        action === 'submit' ||
        * the live DOM that received the click. If it did not become active,
        /(?:^|[?&])action=(?:edit|submit)(?:&|$)/.test(search) ||
        * bypass the owner and run the Common.js live query fallback directly.
        !!document.querySelector('#editform, #wpSave, input[name="wpSave"], button[name="wpSave"]');
        */
}
        if (handled && !isClbiNationsLiveContinentActive(tabpanel, continent)) {
 
             handled = false;
 
         }
function isClbiNationListManagerShortcutContext() {
    return !!document.querySelector('.nation-list-manager');
}
 
function getClbiBottomShortcutItems() {
    if (isClbiWikiEditShortcutContext()) {
        return [
             { key: 'Ctrl+S', label: '변경사항 저장' }
         ];
     }
     }


     if (!handled) {
 
         handled = activateClbiNationsContinent(tabpanel, continent, { skipOwner: true });
     if (isClbiNationListManagerShortcutContext()) {
         return [
            { key: 'Ctrl+S', label: '국가 목록 저장' }
        ];
     }
     }


     if (handled) {
     if (isClbiNationsShortcutContext()) {
         try { playStaticSound(); } catch (err2) {}
         return [
        event.preventDefault();
            { key: 'Q', label: '이전 시대' },
        event.stopPropagation();
            { key: 'E', label: '다음 시대' },
        if (typeof event.stopImmediatePropagation === 'function') event.stopImmediatePropagation();
            { key: 'Shift+Q', label: '이전 연도' },
            { key: 'Shift+E', label: '다음 연도' },
            { key: 'Ctrl+Q', label: '이전 대륙' },
            { key: 'Ctrl+E', label: '다음 대륙' }
        ];
     }
     }
}


function initClbiNationsGlobalClickDelegate() {
     return [];
     if (document.body.getAttribute('data-clbi-nations-global-click-ready') === '1') return;
    document.body.setAttribute('data-clbi-nations-global-click-ready', '1');
    document.addEventListener('click', handleClbiNationsContinentDocumentClick, true);
}
}


function renderClbiBottomShortcutGuide() {
    var guide = document.getElementById('clbi-bottom-shortcut-guide');
    var items;
    var html;


function initClbiNationsPointerHoverValidation() {
     if (!guide) return;
     if (document.body.getAttribute('data-clbi-nations-pointer-hover-ready') === '1') return;


     document.body.setAttribute('data-clbi-nations-pointer-hover-ready', '1');
     items = getClbiBottomShortcutItems();


     document.addEventListener('pointermove', function (event) {
     if (!items.length) {
         CLBI_NATIONS_LAST_POINTER_X = event.clientX;
         guide.classList.add('is-empty');
         CLBI_NATIONS_LAST_POINTER_Y = event.clientY;
         guide.innerHTML = '';
         validateAllClbiNationsPointerHovers();
         return;
     }, true);
     }
 
    guide.classList.remove('is-empty');


     document.addEventListener('pointerleave', function () {
     html = '<div class="clbi-bottom-shortcut-list">';
        CLBI_NATIONS_LAST_POINTER_X = null;
        CLBI_NATIONS_LAST_POINTER_Y = null;
        validateAllClbiNationsPointerHovers();
    }, true);


     window.addEventListener('blur', function () {
     items.forEach(function (item) {
         CLBI_NATIONS_LAST_POINTER_X = null;
         html += '<div class="clbi-bottom-shortcut-item">' +
        CLBI_NATIONS_LAST_POINTER_Y = null;
            '<span class="clbi-bottom-shortcut-key">' + escapeClbiBottomGuideHtml(item.key) + '</span>' +
        validateAllClbiNationsPointerHovers();
            '<span class="clbi-bottom-shortcut-label">' + escapeClbiBottomGuideHtml(item.label) + '</span>' +
        '</div>';
     });
     });
}


 
     html += '</div>';
function initClbiBottomShortcutSystem(root) {
     guide.innerHTML = html;
    renderClbiBottomShortcutGuide();
    initClbiNationsGlobalClickDelegate();
     initClbiNationsTabpanelControls(root || document);
     initClbiNationsPointerHoverValidation();
}
}


// ── 상·하단 네비게이션 바 ──
function buildClbiBottomPlankHtml(wrapId, navId, mainId) {
function buildClbiNavHtml(position) {
    var isBottom = position === 'bottom';
    var base = isBottom ? 'clbi-bottom' : 'clbi-top';
    var shortBase = isBottom ? 'clbi-bnav' : 'clbi-tnav';
    var wrapId = base + '-nav-wrap';
    var navId = base + '-nav';
    var mainId = base + '-nav-main';
    var tabsId = base + '-nav-tabs';
    var searchId = base + '-nav-search';
    var inputId = isBottom ? 'clbi-bottom-search-input' : 'clbi-top-search-input';
    var rightId = base + '-nav-right';
    var worldId = shortBase + '-worldbuilding';
    var infoId = shortBase + '-info';
    var subId = isBottom ? 'clbi-bottom-sub-worldbuilding' : 'clbi-sub-worldbuilding';
    var subInnerId = subId + '-inner';
 
    if (isBottom) {
        return buildClbiBottomPlankHtml(wrapId, navId, mainId);
    }
 
     return '' +
     return '' +
         '<div id="' + wrapId + '">' +
         '<div id="' + wrapId + '">' +
             '<div id="' + navId + '">' +
             '<div id="' + navId + '">' +
                 '<div id="' + mainId + '">' +
                 '<div id="' + mainId + '">' +
                     '<div id="' + tabsId + '">' +
                     '<div id="clbi-bottom-shortcut-guide" class="is-empty" aria-label="단축키 안내"></div>' +
                        '<a class="clbi-top-nav-item" href="/index.php/대문">' +
                '</div>' +
                            '<img class="clbi-tnav-icon" src="/index.php?title=특수:Redirect/file/Ic-main-menu-001.png" alt="">' +
            '</div>' +
                            '<span class="clbi-tnav-label">메인 메뉴</span>' +
        '</div>';
                        '</a>' +
}
                        '<a class="clbi-top-nav-item" href="/index.php/프로젝트:소개">' +
 
                            '<img class="clbi-tnav-icon" src="/index.php?title=특수:Redirect/file/Ic-project-001.png" alt="">' +
var CLBI_NATIONS_LAST_POINTER_X = null;
                            '<span class="clbi-tnav-label">프로젝트</span>' +
var CLBI_NATIONS_LAST_POINTER_Y = null;
                        '</a>' +
 
                        '<div class="clbi-top-nav-item" id="' + worldId + '">' +
function getClbiNationsTabAtPointer(tabpanel) {
                            '<img class="clbi-tnav-icon" src="/index.php?title=특수:Redirect/file/Ic-worldbuilding-001.png" alt="">' +
    var element;
                            '<span class="clbi-tnav-label">세계관</span>' +
    var tab;
                            '<span class="clbi-tnav-arrow">▾</span>' +
                        '</div>' +
                    '</div>' +
                    (isBottom ? '' : (
                        '<div id="' + searchId + '">' +
                            '<input type="text" id="' + inputId + '" placeholder="검색...">' +
                        '</div>'
                    )) +
                    '<div id="' + rightId + '">' +
                        '<div class="clbi-top-nav-item" id="' + infoId + '">' +
                            '<span class="clbi-tnav-label">ℹ</span>' +
                        '</div>' +
                    '</div>' +
                '</div>' +
                '<div id="' + subId + '">' +
                    '<div id="' + subInnerId + '">' +
                        '<div class="clbi-tnav-sub-list">' +
                            '<a class="clbi-tnav-sub-item" href="/index.php/역사적_사건">역사적 사건</a>' +
                            '<a class="clbi-tnav-sub-item" href="/index.php/설정">설정</a>' +
                            '<a class="clbi-tnav-sub-item" href="/index.php/국가_및_조합">국가 및 조합</a>' +
                            '<a class="clbi-tnav-sub-item" href="/index.php/기업_및_공동체">기업 및 공동체</a>' +
                            '<a class="clbi-tnav-sub-item" href="/index.php/군_정치집단">군, 정치집단</a>' +
                            '<a class="clbi-tnav-sub-item" href="/index.php/인물">인물</a>' +
                        '</div>' +
                    '</div>' +
                '</div>' +
            '</div>' +
        '</div>';
}


function normalizeClbiShellDomOrder() {
     if (!tabpanel) return null;
     var contentWrapper = document.querySelector('.content-wrapper');
     if (CLBI_NATIONS_LAST_POINTER_X === null || CLBI_NATIONS_LAST_POINTER_Y === null) return null;
     var topNav = document.getElementById('clbi-top-nav-wrap');
     if (typeof document.elementFromPoint !== 'function') return null;
     var bottomNav = document.getElementById('clbi-bottom-nav-wrap');
    var canvas = document.getElementById('site-halftone-bg');
    var anchor;
    var viewportH;
    var topRect;
    var wrapperRect;
    var needsRecovery;
    var expectedWrapperTop;
    var host;


     if (!contentWrapper || !topNav || !bottomNav || !document.body) return;
    element = document.elementFromPoint(CLBI_NATIONS_LAST_POINTER_X, CLBI_NATIONS_LAST_POINTER_Y);
     if (!element) return null;


     /*
     tab = element.closest ? element.closest('.clbi-nations-tabpanel-tab[data-continent]') : null;
    CLBI shell can live inside a Liberty <section>.  Some skins/layouts give that
    section a flow context that lets the top nav visually overlap the content
    wrapper even when DOM sibling order is correct.  Mark the common parent and
    let Layout.css force a simple vertical flow for the shell.
    */
    host = topNav.parentElement === contentWrapper.parentElement &&
        contentWrapper.parentElement === bottomNav.parentElement
        ? contentWrapper.parentElement
        : null;


     if (host) {
     if (!tab || !tabpanel.contains(tab)) return null;
        host.classList.add('clbi-shell-host');
    }


     viewportH = window.innerHeight || document.documentElement.clientHeight || 0;
     return tab;
     topRect = topNav.getBoundingClientRect();
}
     wrapperRect = contentWrapper.getBoundingClientRect();
 
     expectedWrapperTop = topRect.bottom + 8;
function validateClbiNationsPointerHover(tabpanel, forceSuppress) {
     var tab = getClbiNationsTabAtPointer(tabpanel);
     var suppressContinent;
    var tabContinent;
     var tabIsActive;


     needsRecovery = false;
     if (!tabpanel) return;


     if (viewportH > 0) {
     if (!tab) {
         if (topRect.top >= viewportH * 0.55) needsRecovery = true;
         clearClbiNationsKeyboardHoverSuppressed(tabpanel);
         if (wrapperRect.top >= viewportH * 0.60) needsRecovery = true;
         return;
     }
     }


     if (topRect.top > 240 || wrapperRect.top > 320) {
     tabContinent = tab.getAttribute('data-continent') || '';
         needsRecovery = true;
    tabIsActive = tab.classList.contains('is-active') || tab.getAttribute('aria-selected') === 'true';
 
    if (tabIsActive) {
         clearClbiNationsKeyboardHoverSuppressed(tabpanel);
        return;
     }
     }


     if (wrapperRect.top < expectedWrapperTop - 1) {
    suppressContinent = tabpanel.getAttribute('data-clbi-hover-suppress-continent') || '';
         needsRecovery = true;
 
     if (forceSuppress || !suppressContinent) {
        tabpanel.classList.add('is-keyboard-switching');
        tabpanel.setAttribute('data-clbi-hover-suppress-continent', tabContinent);
         return;
     }
     }


     if (!needsRecovery) {
     if (suppressContinent === tabContinent) {
         document.body.classList.add('clbi-shell-ready');
         tabpanel.classList.add('is-keyboard-switching');
         return;
         return;
     }
     }


     anchor = canvas && canvas.parentNode === document.body
     /*
        ? canvas.nextSibling
    * The pointer actually moved onto another tab after the keyboard switch.
        : document.body.firstChild;
    * At that point this is no longer stale browser :hover; let normal hover work.
    */
    clearClbiNationsKeyboardHoverSuppressed(tabpanel);
}


    document.body.insertBefore(topNav, anchor);
function validateAllClbiNationsPointerHovers() {
     document.body.insertBefore(contentWrapper, topNav.nextSibling);
     var panels = document.querySelectorAll('.clbi-nations-tabpanel.is-keyboard-switching');
    document.body.insertBefore(bottomNav, contentWrapper.nextSibling);


     document.body.classList.add('clbi-shell-ready');
     Array.prototype.forEach.call(panels, function (tabpanel) {
        if (isClbiNationsPanelOwnedTabpanel(tabpanel)) return;
        validateClbiNationsPointerHover(tabpanel, false);
    });
}
}


window.normalizeClbiShellDomOrder = normalizeClbiShellDomOrder;
function isClbiNationsPanelOwnedTabpanel(tabpanel) {
 
     /*
 
    * Mouse continent tab regression guard.
function ensureClbiVerticalScaleHost() {
    * -------------------------------------
     var topNav = document.getElementById('clbi-top-nav-wrap');
    * Detached SPA preparation serializes attributes/classes but it cannot
    var contentWrapper = document.querySelector('.content-wrapper');
    * serialize DOM event listeners or JS properties. The NationsPanel fix
    var bottomNav = document.getElementById('clbi-bottom-nav-wrap');
    * therefore uses the DOM property CLBI_NationsPanelOwned /
    var host;
    * CLBI_NationsTabPanelBound as the real ownership marker.
     var existing;
    *
    var parent;
    * Do NOT treat data-nations-tabpanel-ready or clbi-nations-continent-cache
    * as ownership here.  Those can survive innerHTML insertion while the real
    * click listeners were lost, causing Common.js to delegate to a panel that
    * NationsPanel has not rebound yet.  The fallback below must remain able to
    * handle mouse clicks until NationsPanel reclaims the live DOM node.
    */
     return !!(tabpanel && tabpanel.CLBI_NationsPanelOwned);
}


    if (!topNav || !contentWrapper || !bottomNav || !document.body) return null;
function isClbiNationsLiveContinentActive(tabpanel, continent) {
    var tab;
    var panel;


     existing = document.getElementById('clbi-shell-scale-host');
     if (!tabpanel || !continent) return false;


     if (existing && existing.contains(topNav) && existing.contains(contentWrapper) && existing.contains(bottomNav)) {
     tab = Array.prototype.slice.call(tabpanel.querySelectorAll('.clbi-nations-tabpanel-tab[data-continent]')).find(function (candidate) {
         existing.classList.add('clbi-shell-host');
         return candidate.getAttribute('data-continent') === continent;
        return existing;
     });
     }


     parent = topNav.parentElement === contentWrapper.parentElement && contentWrapper.parentElement === bottomNav.parentElement
     panel = Array.prototype.slice.call(tabpanel.querySelectorAll('.clbi-nations-tabpanel-continent[data-continent-panel]')).find(function (candidate) {
         ? topNav.parentElement
         return candidate.getAttribute('data-continent-panel') === continent;
        : null;
    });


     if (parent && parent !== document.body) {
     return !!(
         parent.classList.add('clbi-shell-host');
        tab &&
         parent.id = parent.id || 'clbi-shell-scale-host';
        panel &&
        return parent;
        (tab.classList.contains('is-active') || tab.getAttribute('aria-selected') === 'true') &&
    }
         panel.classList.contains('is-active') &&
         panel.getAttribute('aria-hidden') !== 'true' &&
        !panel.hasAttribute('hidden')
    );
}


    host = existing || document.createElement('div');
function activateClbiNationsContinent(tabpanel, targetContinent, options) {
     host.id = 'clbi-shell-scale-host';
    var tabs;
     host.className = 'clbi-shell-host';
     var panels;
     var skipOwner = !!(options && options.skipOwner);


     if (!host.parentNode) {
     if (!tabpanel || !targetContinent) return false;
        document.body.insertBefore(host, topNav);
    }


     host.appendChild(topNav);
     if (!skipOwner && isClbiNationsPanelOwnedTabpanel(tabpanel)) {
    host.appendChild(contentWrapper);
        var owner = window.NationsPanel || window.CLBI_NATIONS_PANEL || null;
    host.appendChild(bottomNav);


    return host;
        if (owner && typeof owner.activateContinent === 'function') {
}
            try {
                if (owner.activateContinent(targetContinent, {
                    source: 'common-legacy-click',
                    panel: tabpanel
                })) {
                    return true;
                }
            } catch (err) {}
        }


function readClbiRootPx(name, fallback) {
        /*
    var raw = '';
        * Ownership markers can be stale during SPA/hydration edge cases.  If
     var value;
        * the owner API is missing or refuses the live panel, do not drop the
        * mouse click.  Fall through to the local fallback so pointer users are
        * never left with keyboard-only continent tabs.
        */
     }


     try {
     tabs = Array.prototype.slice.call(tabpanel.querySelectorAll('.clbi-nations-tabpanel-tab[data-continent]'));
        raw = getComputedStyle(document.documentElement).getPropertyValue(name);
     panels = Array.prototype.slice.call(tabpanel.querySelectorAll('.clbi-nations-tabpanel-continent[data-continent-panel]'));
     } catch (err) {}


     value = parseFloat(raw);
     if (!tabs.length || !panels.length) return false;
    return isFinite(value) && value > 0 ? value : fallback;
}


function resetLeftRecentAdaptiveState() {
    tabs.forEach(function (tab) {
    var list = document.getElementById('clbi-left-recent-list');
        var active = tab.getAttribute('data-continent') === targetContinent;
    var newsBox = list ? list.closest('.clbi-left-news-box') : null;
        tab.classList.toggle('is-active', active);
    var items = list ? Array.prototype.slice.call(list.querySelectorAll('.news-recent-item')) : [];
        tab.setAttribute('aria-selected', active ? 'true' : 'false');
        tab.setAttribute('tabindex', active ? '0' : '-1');
    });


     if (newsBox) {
     panels.forEach(function (panel) {
         newsBox.classList.remove('is-adaptive-constrained');
         var active = panel.getAttribute('data-continent-panel') === targetContinent;
         newsBox.style.removeProperty('--adaptive-news-h');
         panel.classList.toggle('is-active', active);
    }


    if (list) {
        if (active) {
        list.classList.remove('is-adaptive-faded');
            panel.removeAttribute('hidden');
        list.removeAttribute('data-adaptive-limit');
         } else {
         list.style.removeProperty('--adaptive-recent-h');
            panel.setAttribute('hidden', 'hidden');
    }
        }
 
    items.forEach(function (item) {
        item.classList.remove('is-adaptive-hidden');
     });
     });
}


function resetLeftBillboardAdaptiveState() {
    try {
    var box = document.querySelector('#clbi-left-sidebar .left-billboard-box');
        if (window.Decorations && typeof window.Decorations.sync === 'function') window.Decorations.sync();
        else if (window.CLBI_DECORATIONS && typeof window.CLBI_DECORATIONS.sync === 'function') window.CLBI_DECORATIONS.sync();
    } catch (err) {}


     if (!box) return;
     return true;
}


    box.classList.remove('is-left-ad-title-only', 'is-left-ad-extended');
function setClbiNationsKeyboardHoverSuppressed(tabpanel) {
     box.style.removeProperty('--left-billboard-h');
     validateClbiNationsPointerHover(tabpanel, true);
    box.style.removeProperty('--left-billboard-finish-h');
}
}


function updateClbiShellVerticalScale() {
function clearClbiNationsKeyboardHoverSuppressed(tabpanel) {
     var root = document.documentElement;
     if (!tabpanel) return;
     var body = document.body;
     tabpanel.classList.remove('is-keyboard-switching');
     var host;
     tabpanel.removeAttribute('data-clbi-hover-suppress-continent');
    var topInner;
}
    var bottomInner;
    var thresholdH;
    var gap;
    var outerGapTotal;
    var baseStageH;
    var stageW;
    var stageH;
    var viewportW;
    var viewportH;
    var availableW;
    var availableH;
    var topH;
    var bottomH;
    var contentH;
    var widthScale;
    var heightScale;
    var scale;
    var shouldScale;


     if (!root || !body) return;
function moveClbiNationsContinent(direction) {
     var tabpanel = document.querySelector('.clbi-nations-tabpanel');
    var tabs;
    var activeIndex;
    var nextIndex;
    var target;


    host = ensureClbiVerticalScaleHost();
     if (!tabpanel) return false;
     if (!host) return;


     thresholdH = readClbiRootPx('--clbi-vertical-scale-threshold-h', 1080);
     if (isClbiNationsPanelOwnedTabpanel(tabpanel) &&
    gap = readClbiRootPx('--layout-gap', 8);
        window.CLBI_NATIONS_PANEL &&
    outerGapTotal = gap * 2;
        typeof window.CLBI_NATIONS_PANEL.moveContinent === 'function') {
    baseStageH = Math.max(420, thresholdH - outerGapTotal);
        return !!window.CLBI_NATIONS_PANEL.moveContinent(direction, {
    stageW = readClbiRootPx('--layout-shell-w', 1880);
            source: 'common-legacy-keyboard',
            panel: tabpanel
        });
    }


     viewportW = Math.max(320, window.innerWidth || document.documentElement.clientWidth || stageW);
     tabs = Array.prototype.slice.call(tabpanel.querySelectorAll('.clbi-nations-tabpanel-tab[data-continent]'));
    viewportH = Math.max(320, window.innerHeight || document.documentElement.clientHeight || thresholdH);
     if (!tabs.length) return false;
     availableW = Math.max(240, viewportW - outerGapTotal);
    availableH = Math.max(240, viewportH - outerGapTotal);


     /*
     activeIndex = tabs.findIndex(function (tab) {
    평상시에는 기존 세로 채움 레이아웃을 기준으로 삼는다.
        return tab.classList.contains('is-active') || tab.getAttribute('aria-selected') === 'true';
    세로가 기준점보다 작아지는 경우에는 기준 높이를 고정점으로 삼고,
     });
    가로만 부족한 경우에는 현재 사용 가능한 세로 높이를 고정점으로 삼는다.
    이렇게 해야 가로 부족으로 scale에 들어갈 때 본문 높이가 갑자기 접히지 않는다.
     */
    stageH = availableH >= baseStageH ? availableH : baseStageH;


     topInner = document.getElementById('clbi-top-nav');
     if (activeIndex < 0) activeIndex = 0;
    bottomInner = document.getElementById('clbi-bottom-nav');


     topH = topInner ? Math.ceil(topInner.offsetHeight || topInner.getBoundingClientRect().height || 38) : 38;
     nextIndex = (activeIndex + direction + tabs.length) % tabs.length;
     bottomH = bottomInner ? Math.ceil(bottomInner.offsetHeight || bottomInner.getBoundingClientRect().height || 38) : 38;
     target = tabs[nextIndex].getAttribute('data-continent');
    contentH = Math.max(360, Math.floor(stageH - topH - bottomH - (gap * 2)));


     widthScale = availableW < stageW ? availableW / stageW : 1;
     if (activateClbiNationsContinent(tabpanel, target)) {
    heightScale = availableH < baseStageH ? availableH / baseStageH : 1;
        setClbiNationsKeyboardHoverSuppressed(tabpanel);
    scale = Math.min(1, widthScale, heightScale);
        window.setTimeout(function () {
    scale = Math.max(0.50, Math.min(1, Math.floor(scale * 1000) / 1000));
            validateClbiNationsPointerHover(tabpanel, false);
     shouldScale = scale < 0.999;
        }, 0);
        return true;
     }


     root.style.setProperty('--clbi-stage-design-w', stageW + 'px');
     return false;
    root.style.setProperty('--clbi-stage-design-h', Math.floor(stageH) + 'px');
}
    root.style.setProperty('--clbi-stage-content-h', contentH + 'px');
    root.style.setProperty('--clbi-shell-scale', String(scale));


     body.classList.toggle('clbi-shell-vertical-scale', shouldScale);
function initClbiNationsTabpanelControls(root) {
     var scope = root && root.querySelectorAll ? root : document;
    var panels = scope.querySelectorAll('.clbi-nations-tabpanel');


     if (shouldScale) {
     Array.prototype.forEach.call(panels, function (tabpanel) {
         resetLeftRecentAdaptiveState();
         /*
         resetLeftBillboardAdaptiveState();
        * Common.js is only a safety fallback for continent tabs; NationsPanel
    }
        * is the primary owner.  This guard must be a DOM property, not a
}
        * serialized attribute.  SPA warm prepaint can preserve
window.updateClbiShellVerticalScale = updateClbiShellVerticalScale;
        * data-clbi-nations-tabs-ready="1" while losing the actual event
        * listeners, which was the root cause of mouse clicks no longer moving
        * continents while keyboard shortcuts still worked.
        */
         if (tabpanel.CLBI_NationsCommonTabsBound) return;
        tabpanel.CLBI_NationsCommonTabsBound = true;
        tabpanel.setAttribute('data-clbi-nations-tabs-ready', '1');


var $contentWrapper = $('.content-wrapper').first();
        tabpanel.addEventListener('pointerdown', function () {
            clearClbiNationsKeyboardHoverSuppressed(tabpanel);
        });


if ($contentWrapper.length) {
        tabpanel.addEventListener('pointerleave', function () {
    $('#clbi-top-nav-wrap, #clbi-bottom-nav-wrap').remove();
            clearClbiNationsKeyboardHoverSuppressed(tabpanel);
    $contentWrapper.before(buildClbiNavHtml('top'));
        });
    $contentWrapper.after(buildClbiNavHtml('bottom'));
    renderClbiBottomShortcutGuide();
    initClbiNationsTabpanelControls(document);
    if (typeof window.normalizeClbiShellDomOrder === 'function') window.normalizeClbiShellDomOrder();
}


var CLBI_SHELL_METRICS_RAF = null;
        tabpanel.addEventListener('click', function (event) {
            var tab = event.target.closest ? event.target.closest('.clbi-nations-tabpanel-tab[data-continent]') : null;


function runClbiShellMetricsBatch() {
            if (!tab || !tabpanel.contains(tab)) return;
    var top = document.getElementById('clbi-top-nav-wrap');
    var bottom = document.getElementById('clbi-bottom-nav-wrap');
    var root = document.documentElement;
    var topH = 0;
    var bottomH = 0;


    CLBI_SHELL_METRICS_RAF = null;
            clearClbiNationsKeyboardHoverSuppressed(tabpanel);


    if (!root) return;
            if (activateClbiNationsContinent(tabpanel, tab.getAttribute('data-continent'))) {
                event.preventDefault();
            }
        });


    if (top) {
        tabpanel.addEventListener('keydown', function (event) {
        topH = Math.ceil(top.getBoundingClientRect().height || top.offsetHeight || 0);
            var tab = event.target.closest ? event.target.closest('.clbi-nations-tabpanel-tab[data-continent]') : null;
    }
            var handled = false;


    if (bottom) {
            if (!tab || !tabpanel.contains(tab)) return;
        bottomH = Math.ceil(bottom.getBoundingClientRect().height || bottom.offsetHeight || 0);
    }


    root.style.setProperty('--clbi-top-nav-outer-h', topH + 'px');
            if (event.key === 'ArrowLeft') handled = moveClbiNationsContinent(-1);
    root.style.setProperty('--clbi-bottom-nav-outer-h', bottomH + 'px');
            else if (event.key === 'ArrowRight') handled = moveClbiNationsContinent(1);


    if (typeof updateClbiShellVerticalScale === 'function') {
            if (handled) {
        updateClbiShellVerticalScale();
                event.preventDefault();
    }
                event.stopPropagation();
 
            }
    if (typeof scheduleAdaptiveLeftRecentItems === 'function') {
         });
        scheduleAdaptiveLeftRecentItems();
     });
    }
 
    if (typeof scheduleClbiContentBottomGap === 'function') {
         scheduleClbiContentBottomGap();
     }
}
}


function requestClbiShellMetricsFrame() {
function handleClbiNationsContinentDocumentClick(event) {
     if (CLBI_SHELL_METRICS_RAF !== null) return;
     var target;
    var tab;
    var tabpanel;
    var continent;
    var owner;
    var handled = false;


     CLBI_SHELL_METRICS_RAF = window.requestAnimationFrame
     if (!event || event.__clbiNationsContinentHandled) return;
        ? window.requestAnimationFrame(runClbiShellMetricsBatch)
    target = event.target;
        : window.setTimeout(runClbiShellMetricsBatch, 16);
    if (!target || !target.closest) return;
}


function scheduleClbiShellMetrics() {
    tab = target.closest('.clbi-nations-tabpanel-tab[data-continent]');
     requestClbiShellMetricsFrame();
     if (!tab) return;


     window.setTimeout(requestClbiShellMetricsFrame, 0);
     tabpanel = tab.closest ? tab.closest('.clbi-nations-tabpanel') : null;
    window.setTimeout(requestClbiShellMetricsFrame, 80);
     if (!tabpanel || !tabpanel.contains(tab)) return;
    window.setTimeout(requestClbiShellMetricsFrame, 240);
}
function watchClbiShellMetrics() {
    var top = document.getElementById('clbi-top-nav-wrap');
     var bottom = document.getElementById('clbi-bottom-nav-wrap');
    var observer;


     scheduleClbiShellMetrics();
     continent = tab.getAttribute('data-continent') || '';
    if (!continent) return;


     $(window).on('resize orientationchange', scheduleClbiShellMetrics);
     /*
    $(window).on('pageshow.clbiShellScale focus.clbiShellScale', scheduleClbiShellMetrics);
    * Final live-DOM mouse delegate.
    document.addEventListener('visibilitychange', function () {
    * --------------------------------
        if (!document.hidden) scheduleClbiShellMetrics();
    * The continent tab UI has two initialization phases: detached preparation
     });
    * for seamless SPA entry, then live DOM hydration.  Detached preparation can
     $(window).on('resize.clbiLeftBillboard orientationchange.clbiLeftBillboard', scheduleLeftSidebarVerticalFit);
    * leave serialized "ready" attributes behind while losing event listeners.
     $(window).on('resize.clbiRecentViewport orientationchange.clbiRecentViewport', function () { scheduleAdaptiveLeftRecentItems(); scheduleClbiContentBottomGap(); });
    * Keyboard shortcuts still work because they call the public NationsPanel
    $(window).on('resize.clbiContentBottomGap orientationchange.clbiContentBottomGap', scheduleClbiContentBottomGap);
    * API directly, but mouse clicks depend on live listeners. This capturing
    * delegate is intentionally independent of per-panel ready attributes: it
    * always resolves the clicked live tab and hands it to NationsPanel first,
    * then falls back to the local Common.js switcher if needed.
    */
    event.__clbiNationsContinentHandled = true;
     clearClbiNationsKeyboardHoverSuppressed(tabpanel);
 
     owner = window.NationsPanel || window.CLBI_NATIONS_PANEL || null;
     if (owner && typeof owner.activateContinent === 'function') {
        try {
            handled = !!owner.activateContinent(continent, {
                source: 'mouse-click-live-delegate',
                panel: tabpanel
            });
        } catch (err) {
            handled = false;
        }


    if (window.ResizeObserver) {
        /*
        observer = new ResizeObserver(scheduleClbiShellMetrics);
        * Owner API stale-cache guard.
        if (top) observer.observe(top);
        *
         if (bottom) observer.observe(bottom);
        * A previous regression came from NationsPanel returning true after it
         window.CLBI_SHELL_RESIZE_OBSERVER = observer;
        * updated cached/detached tab nodes instead of the clicked live tab. A
        * true return value alone is therefore not enough for mouse input. Verify
        * the live DOM that received the click. If it did not become active,
        * bypass the owner and run the Common.js live query fallback directly.
        */
         if (handled && !isClbiNationsLiveContinentActive(tabpanel, continent)) {
            handled = false;
         }
     }
     }
}


function bindClbiWorldbuildingToggle(buttonSelector, menuSelector) {
     if (!handled) {
     $(buttonSelector).on('click', function() {
         handled = activateClbiNationsContinent(tabpanel, continent, { skipOwner: true });
         var $menu = $(menuSelector);
    }
        var $btn = $(this);


         $menu.toggleClass('worldbuilding-open');
    if (handled) {
         $btn.toggleClass('clbi-tnav-active', $menu.hasClass('worldbuilding-open'));
         try { playStaticSound(); } catch (err2) {}
         scheduleClbiShellMetrics();
         event.preventDefault();
     });
        event.stopPropagation();
         if (typeof event.stopImmediatePropagation === 'function') event.stopImmediatePropagation();
     }
}
}


bindClbiWorldbuildingToggle('#clbi-tnav-worldbuilding', '#clbi-sub-worldbuilding');
function initClbiNationsGlobalClickDelegate() {
bindClbiWorldbuildingToggle('#clbi-bnav-worldbuilding', '#clbi-bottom-sub-worldbuilding');
    if (document.body.getAttribute('data-clbi-nations-global-click-ready') === '1') return;
 
    document.body.setAttribute('data-clbi-nations-global-click-ready', '1');
$('#clbi-top-search-input, #clbi-bottom-search-input').on('keydown', function(e) {
     document.addEventListener('click', handleClbiNationsContinentDocumentClick, true);
    if (e.key === 'Enter') {
        var q = $(this).val().trim();
        if (q) window.location.href = '/index.php?search=' + encodeURIComponent(q);
     }
});
 
if (window.mw && mw.hook) {
    mw.hook('wikipage.content').add(function ($content) {
        initClbiBottomShortcutSystem($content && $content[0] ? $content[0] : document);
    });
}
}


watchClbiShellMetrics();


});
function initClbiNationsPointerHoverValidation() {
    if (document.body.getAttribute('data-clbi-nations-pointer-hover-ready') === '1') return;


// 페이지 전환 사운드
    document.body.setAttribute('data-clbi-nations-pointer-hover-ready', '1');
var transitionSound = new Audio('/index.php?title=특수:Redirect/file/Sfx-ui-001.mp3');


(function() {
    document.addEventListener('pointermove', function (event) {
    var master = parseFloat(localStorage.getItem('clbi-audio-master') || 80) / 100;
        CLBI_NATIONS_LAST_POINTER_X = event.clientX;
    var sfx = parseFloat(localStorage.getItem('clbi-audio-sfx') || 60) / 100;
        CLBI_NATIONS_LAST_POINTER_Y = event.clientY;
    var sfxOn = localStorage.getItem('clbi-audio-sfxOn') !== 'false';
        validateAllClbiNationsPointerHovers();
     transitionSound.volume = sfxOn ? master * sfx : 0;
     }, true);
})();


function playStaticSound() {
    document.addEventListener('pointerleave', function () {
    var master = parseFloat(localStorage.getItem('clbi-audio-master') || 80) / 100;
        CLBI_NATIONS_LAST_POINTER_X = null;
    var sfx = parseFloat(localStorage.getItem('clbi-audio-sfx') || 60) / 100;
        CLBI_NATIONS_LAST_POINTER_Y = null;
     var sfxOn = localStorage.getItem('clbi-audio-sfxOn') !== 'false';
        validateAllClbiNationsPointerHovers();
     }, true);


     if (!sfxOn) return;
     window.addEventListener('blur', function () {
 
        CLBI_NATIONS_LAST_POINTER_X = null;
    transitionSound.volume = master * sfx;
        CLBI_NATIONS_LAST_POINTER_Y = null;
    transitionSound.currentTime = 0;
        validateAllClbiNationsPointerHovers();
     transitionSound.play();
     });
}
}


// 현재 언어 감지
function getCurrentLang() {
    var langData = document.getElementById('clbi-lang-data');
    return langData ? (langData.getAttribute('data-lang') || 'ko') : 'ko';
}


function normalizePageName(value) {
function initClbiBottomShortcutSystem(root) {
     return String(value || '')
     renderClbiBottomShortcutGuide();
        .split('?')[0]
    initClbiNationsGlobalClickDelegate();
        .replace(/^\/index\.php\//, '')
    initClbiNationsTabpanelControls(root || document);
        .replace(/_/g, ' ')
    initClbiNationsPointerHoverValidation();
        .trim();
}
}


function buildWikiPath(title) {
// ── 상·하단 네비게이션 바 ──
     return '/index.php/' + encodeURI(String(title || '').replace(/ /g, '_'));
function buildClbiNavHtml(position) {
}
     var isBottom = position === 'bottom';
    var base = isBottom ? 'clbi-bottom' : 'clbi-top';
    var shortBase = isBottom ? 'clbi-bnav' : 'clbi-tnav';
    var wrapId = base + '-nav-wrap';
    var navId = base + '-nav';
    var mainId = base + '-nav-main';
    var tabsId = base + '-nav-tabs';
    var searchId = base + '-nav-search';
    var inputId = isBottom ? 'clbi-bottom-search-input' : 'clbi-top-search-input';
    var worldId = shortBase + '-worldbuilding';
    var subId = isBottom ? 'clbi-bottom-sub-worldbuilding' : 'clbi-sub-worldbuilding';
    var subInnerId = subId + '-inner';


function getLangShortCode(lang) {
    if (isBottom) {
    var map = { ko: 'KR', en: 'EN', zh: 'ZH', ja: 'JA', ru: 'RU', es: 'ES' };
        return buildClbiBottomPlankHtml(wrapId, navId, mainId);
    return map[lang] || String(lang || '').toUpperCase();
}
 
function getLanguageTargetTitle(lang) {
    var data = document.getElementById('clbi-lang-data');
    if (!data || !lang) return '';
 
    var keys = [
        'data-' + lang,
        'data-page-' + lang,
        'data-title-' + lang,
        'data-target-' + lang,
        'data-lang-' + lang
    ];
 
    for (var i = 0; i < keys.length; i++) {
        var value = data.getAttribute(keys[i]);
        if (value) return value;
     }
     }


     return '';
     return '' +
}
        '<div id="' + wrapId + '">' +
 
            '<div id="' + navId + '">' +
function escapeClbiHtml(value) {
                '<div id="' + mainId + '">' +
    return String(value == null ? '' : value)
                    '<div id="' + tabsId + '">' +
        .replace(/&/g, '&amp;')
                        '<a class="clbi-top-nav-item" href="/index.php/대문">' +
        .replace(/</g, '&lt;')
                            '<img class="clbi-tnav-icon" src="/index.php?title=특수:Redirect/file/Ic-main-menu-001.png" alt="">' +
        .replace(/>/g, '&gt;')
                            '<span class="clbi-tnav-label">메인 메뉴</span>' +
        .replace(/"/g, '&quot;')
                        '</a>' +
        .replace(/'/g, '&#039;');
                        '<a class="clbi-top-nav-item" href="/index.php/프로젝트:소개">' +
                            '<img class="clbi-tnav-icon" src="/index.php?title=특수:Redirect/file/Ic-project-001.png" alt="">' +
                            '<span class="clbi-tnav-label">프로젝트</span>' +
                        '</a>' +
                        '<div class="clbi-top-nav-item" id="' + worldId + '">' +
                            '<img class="clbi-tnav-icon" src="/index.php?title=특수:Redirect/file/Ic-worldbuilding-001.png" alt="">' +
                            '<span class="clbi-tnav-label">세계관</span>' +
                            '<span class="clbi-tnav-arrow">▾</span>' +
                        '</div>' +
                    '</div>' +
                    (isBottom ? '' : (
                        '<div id="' + searchId + '">' +
                            '<input type="text" id="' + inputId + '" placeholder="검색...">' +
                        '</div>'
                    )) +
                '</div>' +
                '<div id="' + subId + '">' +
                    '<div id="' + subInnerId + '">' +
                        '<div class="clbi-tnav-sub-list">' +
                            '<a class="clbi-tnav-sub-item" href="/index.php/시대">시대</a>' +
                            '<a class="clbi-tnav-sub-item" href="/index.php/설정">설정</a>' +
                            '<a class="clbi-tnav-sub-item" href="/index.php/기업_및_공동체">기업 및 공동체</a>' +
                            '<a class="clbi-tnav-sub-item" href="/index.php/군_정치집단">군, 정치집단</a>' +
                            '<a class="clbi-tnav-sub-item" href="/index.php/인물">인물</a>' +
                        '</div>' +
                    '</div>' +
                '</div>' +
            '</div>' +
        '</div>';
}
}


function normalizeClbiShellDomOrder() {
    var contentWrapper = document.querySelector('.content-wrapper');
    var topNav = document.getElementById('clbi-top-nav-wrap');
    var bottomNav = document.getElementById('clbi-bottom-nav-wrap');
    var canvas = document.getElementById('site-halftone-bg');
    var anchor;
    var viewportH;
    var topRect;
    var wrapperRect;
    var needsRecovery;
    var expectedWrapperTop;
    var host;


var SIDEBAR_LANG_SVG_NS = 'http://www.w3.org/2000/svg';
    if (!contentWrapper || !topNav || !bottomNav || !document.body) return;
var SIDEBAR_LANGUAGE_STATUS_TITLE = 'MediaWiki:LanguageStatus.json';
var SIDEBAR_LANGUAGE_LABELS = {
    ko: '한국어',
    en: 'English',
    zh: '中文',
    ja: '日本語',
    ru: 'Русский',
    es: 'Español'
};
var SIDEBAR_LANGUAGE_DIAL_LABELS = {
    ko: '한국어',
    en: 'ENG',
    zh: '中文',
    ja: '日本語',
    ru: 'РУС',
    es: 'ESP'
};
var SIDEBAR_LANGUAGE_STATUS_VALUES = {
    available: true,
    wip: true,
    unavailable: true
};


var sidebarLanguageStatusRegistry = {};
    /*
var sidebarLanguageStatusLoaded = false;
    CLBI shell can live inside a Liberty <section>.  Some skins/layouts give that
var sidebarLanguageStatusLoading = false;
    section a flow context that lets the top nav visually overlap the content
var sidebarLanguageStatusCallbacks = [];
    wrapper even when DOM sibling order is correct.  Mark the common parent and
    let Layout.css force a simple vertical flow for the shell.
    */
    host = topNav.parentElement === contentWrapper.parentElement &&
        contentWrapper.parentElement === bottomNav.parentElement
        ? contentWrapper.parentElement
        : null;


var sidebarLanguageState = {
    if (host) {
    order: ['ko', 'en', 'zh', 'ja', 'ru', 'es'],
        host.classList.add('clbi-shell-host');
     currentLang: 'ko',
     }
    baseIndex: 0,
    selectedIndex: 0,
    rotation: 0,
    dragging: false,
    dragMoved: false,
    dragStartX: 0,
    dragStartY: 0,
    dragStartRotation: 0,
    dragAxis: null,
    pointerCaptured: false,
    lastX: 0,
    lastTime: 0,
    releaseVelocity: 0,
    suppressClickUntil: 0,
    raf: null,
    pendingRotation: 0,
    snapTimer: null,
    inertiaRaf: null,
    navigateTimer: null,
    bound: false,
    boundElement: null,
    rotor: null,
    cx: 101,
    cy: 119,
    outerR: 109,
    innerR: 28,
    sectorAngle: 30,
    halfSector: 15,
    repeats: 8,
    dragSensitivity: 0.58,
    maxSpinVelocity: 1.75,
    minSpinVelocity: 0.055,
    spinDecel: 0.00185
};


function createSidebarLanguageSvgEl(tag) {
    viewportH = window.innerHeight || document.documentElement.clientHeight || 0;
     return document.createElementNS(SIDEBAR_LANG_SVG_NS, tag);
    topRect = topNav.getBoundingClientRect();
}
     wrapperRect = contentWrapper.getBoundingClientRect();
    expectedWrapperTop = topRect.bottom + 8;


function normalizeSidebarLanguageIndex(index) {
     needsRecovery = false;
     var length = sidebarLanguageState.order.length;
    var normalized = index % length;
    return normalized < 0 ? normalized + length : normalized;
}


function getSidebarLanguageName(lang) {
    if (viewportH > 0) {
    return SIDEBAR_LANGUAGE_LABELS[lang] || String(lang || '').toUpperCase();
        if (topRect.top >= viewportH * 0.55) needsRecovery = true;
}
        if (wrapperRect.top >= viewportH * 0.60) needsRecovery = true;
    }


function getSidebarLanguageDialName(lang) {
    if (topRect.top > 240 || wrapperRect.top > 320) {
    return SIDEBAR_LANGUAGE_DIAL_LABELS[lang] || getSidebarLanguageName(lang);
        needsRecovery = true;
}
    }


function normalizeSidebarLanguageStatusValue(value) {
    if (wrapperRect.top < expectedWrapperTop - 1) {
    value = String(value == null ? '' : value).toLowerCase().trim();
        needsRecovery = true;
     return SIDEBAR_LANGUAGE_STATUS_VALUES[value] ? value : '';
     }
}


function getSidebarLanguageStatusPageKey() {
    if (!needsRecovery) {
    var raw = String(mw.config.get('wgPageName') || '').trim();
        document.body.classList.add('clbi-shell-ready');
     var normalized = normalizePageName(raw);
        return;
     }


     return normalized || raw || '대문';
     anchor = canvas && canvas.parentNode === document.body
}
        ? canvas.nextSibling
        : document.body.firstChild;


function getSidebarLanguageStatusEntry() {
     document.body.insertBefore(topNav, anchor);
     var registry = sidebarLanguageStatusRegistry || {};
     document.body.insertBefore(contentWrapper, topNav.nextSibling);
    var pages = registry.pages && typeof registry.pages === 'object' ? registry.pages : registry;
     document.body.insertBefore(bottomNav, contentWrapper.nextSibling);
    var raw = String(mw.config.get('wgPageName') || '').trim();
    var normalized = normalizePageName(raw);
     var title = String(mw.config.get('wgTitle') || '').trim();
     var keys = [
        normalized,
        raw,
        raw.replace(/_/g, ' '),
        normalized.replace(/ /g, '_'),
        title,
        title.replace(/_/g, ' ')
    ];
    var i;


     for (i = 0; i < keys.length; i += 1) {
     document.body.classList.add('clbi-shell-ready');
        if (keys[i] && pages[keys[i]] && typeof pages[keys[i]] === 'object') {
            return pages[keys[i]];
        }
    }
 
    return {};
}
}


function getSidebarLanguageStatusOverride(lang) {
window.normalizeClbiShellDomOrder = normalizeClbiShellDomOrder;
    var entry = getSidebarLanguageStatusEntry();
    return normalizeSidebarLanguageStatusValue(entry[lang]);
}


function flushSidebarLanguageStatusCallbacks() {
    var callbacks = sidebarLanguageStatusCallbacks.slice();
    sidebarLanguageStatusCallbacks.length = 0;


    callbacks.forEach(function(callback) {
function ensureClbiVerticalScaleHost() {
        if (typeof callback === 'function') {
    var topNav = document.getElementById('clbi-top-nav-wrap');
            callback(sidebarLanguageStatusRegistry);
    var contentWrapper = document.querySelector('.content-wrapper');
        }
    var bottomNav = document.getElementById('clbi-bottom-nav-wrap');
     });
    var host;
}
     var existing;
    var parent;


function loadSidebarLanguageStatusRegistry(callback, force) {
     if (!topNav || !contentWrapper || !bottomNav || !document.body) return null;
     if (typeof callback === 'function') {
        sidebarLanguageStatusCallbacks.push(callback);
    }


     if (sidebarLanguageStatusLoaded && !force) {
    existing = document.getElementById('clbi-shell-scale-host');
         flushSidebarLanguageStatusCallbacks();
 
         return;
     if (existing && existing.contains(topNav) && existing.contains(contentWrapper) && existing.contains(bottomNav)) {
         existing.classList.add('clbi-shell-host');
         return existing;
     }
     }


     if (sidebarLanguageStatusLoading) return;
     parent = topNav.parentElement === contentWrapper.parentElement && contentWrapper.parentElement === bottomNav.parentElement
        ? topNav.parentElement
        : null;


     sidebarLanguageStatusLoading = true;
     if (parent && parent !== document.body) {
        parent.classList.add('clbi-shell-host');
        parent.id = parent.id || 'clbi-shell-scale-host';
        return parent;
    }


     function finishLanguageStatus(parsed) {
     host = existing || document.createElement('div');
        sidebarLanguageStatusRegistry = parsed && typeof parsed === 'object' ? parsed : {};
    host.id = 'clbi-shell-scale-host';
        sidebarLanguageStatusLoaded = true;
    host.className = 'clbi-shell-host';
        sidebarLanguageStatusLoading = false;
        flushSidebarLanguageStatusCallbacks();
    }


     if (!force && window.EntryStore && typeof window.EntryStore.fetchJsonRef === 'function') {
     if (!host.parentNode) {
         window.EntryStore.fetchJsonRef(SIDEBAR_LANGUAGE_STATUS_TITLE, { noStore: false })
         document.body.insertBefore(host, topNav);
            .then(function (parsed) { finishLanguageStatus(parsed); })
            .catch(function () { finishLanguageStatus({}); });
        return;
     }
     }


     (function () {
     host.appendChild(topNav);
        var url = mw.util.getUrl(SIDEBAR_LANGUAGE_STATUS_TITLE, {
    host.appendChild(contentWrapper);
            action: 'raw',
    host.appendChild(bottomNav);
            ctype: 'application/json'
        });
        if (window.RevisionManifest && typeof window.RevisionManifest.addRevisionParam === 'function') {
            url = window.RevisionManifest.addRevisionParam(url, SIDEBAR_LANGUAGE_STATUS_TITLE);
        }
        $.ajax({
            url: url,
            dataType: 'text',
            cache: true
        }).done(function(text) {
            var parsed = {};


            try {
     return host;
                parsed = text ? JSON.parse(text) : {};
            } catch (err) {
                console.error('LanguageStatus.json parse failed:', err);
                parsed = {};
            }
 
            finishLanguageStatus(parsed);
        }).fail(function() {
            finishLanguageStatus({});
        });
     })();
}
}


window.CLBI_LANGUAGE_STATUS = {
function readClbiRootPx(name, fallback) {
    title: SIDEBAR_LANGUAGE_STATUS_TITLE,
     var raw = '';
    languages: sidebarLanguageState.order.slice(),
     var value;
    labels: SIDEBAR_LANGUAGE_LABELS,
    dialLabels: SIDEBAR_LANGUAGE_DIAL_LABELS,
    getPageKey: getSidebarLanguageStatusPageKey,
    getRegistry: function() {
        return sidebarLanguageStatusRegistry || {};
    },
     reload: function(callback) {
        sidebarLanguageStatusLoaded = false;
        loadSidebarLanguageStatusRegistry(function() {
            renderSidebarLanguageBox();
            if (typeof callback === 'function') callback(sidebarLanguageStatusRegistry);
        }, true);
     },
    refreshDial: function() {
        renderSidebarLanguageBox();
    }
};


function getSidebarLanguageMeta(lang) {
    try {
    var currentLang = getCurrentLang();
        raw = getComputedStyle(document.documentElement).getPropertyValue(name);
     var targetTitle = getLanguageTargetTitle(lang);
     } catch (err) {}
    var isCurrent = lang === currentLang;


     return {
     value = parseFloat(raw);
        lang: lang,
    return isFinite(value) && value > 0 ? value : fallback;
        code: getLangShortCode(lang),
        name: getSidebarLanguageName(lang),
        dialName: getSidebarLanguageDialName(lang),
        targetTitle: targetTitle,
        isCurrent: isCurrent,
        canMove: !!targetTitle && !isCurrent
    };
}
}


function getSidebarLanguageStatus(meta) {
function resetLeftRecentAdaptiveState() {
     var override;
     var list = document.getElementById('clbi-left-recent-list');
    var newsBox = list ? list.closest('.clbi-left-news-box') : null;
    var items = list ? Array.prototype.slice.call(list.querySelectorAll('.news-recent-item')) : [];


     if (!meta) {
     if (newsBox) {
         return {
         newsBox.classList.remove('is-adaptive-constrained');
            className: 'is-locked',
        newsBox.style.removeProperty('--adaptive-news-h');
            label: 'UNAVAILABLE',
            canApply: false
        };
     }
     }


     if (meta.isCurrent) {
     if (list) {
         return {
         list.classList.remove('is-adaptive-faded');
            className: 'is-current',
        list.removeAttribute('data-adaptive-limit');
            label: 'CURRENT',
         list.style.removeProperty('--adaptive-recent-h');
            canApply: false
         };
     }
     }


     override = getSidebarLanguageStatusOverride(meta.lang);
     items.forEach(function (item) {
        item.classList.remove('is-adaptive-hidden');
    });
}


    if (override === 'wip') {
function resetLeftBillboardAdaptiveState() {
        return {
    var box = document.querySelector('#clbi-left-sidebar .left-billboard-box');
            className: 'is-locked',
            label: 'WIP',
            canApply: false
        };
    }


     if (override === 'unavailable') {
     if (!box) return;
        return {
            className: 'is-locked',
            label: 'UNAVAILABLE',
            canApply: false
        };
    }


     if (override === 'available' || meta.targetTitle) {
     box.classList.remove('is-left-ad-title-only', 'is-left-ad-extended');
        return {
    box.style.removeProperty('--left-billboard-h');
            className: meta.targetTitle ? 'is-ready' : 'is-locked',
    box.style.removeProperty('--left-billboard-finish-h');
            label: meta.targetTitle ? 'AVAILABLE' : 'UNAVAILABLE',
}
            canApply: !!meta.targetTitle
        };
    }


     return {
function updateClbiShellVerticalScale() {
        className: 'is-locked',
    var root = document.documentElement;
        label: 'UNAVAILABLE',
    var body = document.body;
        canApply: false
    var host;
     };
    var topInner;
}
    var bottomInner;
    var thresholdH;
    var gap;
    var outerGapTotal;
    var baseStageH;
    var stageW;
    var stageH;
    var viewportW;
    var viewportH;
    var availableW;
    var availableH;
     var topH;
    var bottomH;
    var contentH;
    var widthScale;
     var heightScale;
    var scale;
    var shouldScale;


function sidebarLanguageRad(deg) {
    if (!root || !body) return;
    return (deg * Math.PI) / 180;
}


function sidebarLanguagePointAt(radius, deg) {
    host = ensureClbiVerticalScaleHost();
    var state = sidebarLanguageState;
     if (!host) return;
     var angle = sidebarLanguageRad(deg);


     return {
     thresholdH = readClbiRootPx('--clbi-vertical-scale-threshold-h', 1080);
        x: state.cx + Math.sin(angle) * radius,
    gap = readClbiRootPx('--layout-gap', 8);
        y: state.cy - Math.cos(angle) * radius
    outerGapTotal = gap * 2;
     };
    baseStageH = Math.max(420, thresholdH - outerGapTotal);
}
     stageW = readClbiRootPx('--layout-shell-w', 1880);


function getSidebarLanguageSectorPath(start, end) {
     viewportW = Math.max(320, window.innerWidth || document.documentElement.clientWidth || stageW);
     var state = sidebarLanguageState;
     viewportH = Math.max(320, window.innerHeight || document.documentElement.clientHeight || thresholdH);
    var p1 = sidebarLanguagePointAt(state.outerR, start);
     availableW = Math.max(240, viewportW - outerGapTotal);
     var p2 = sidebarLanguagePointAt(state.outerR, end);
     availableH = Math.max(240, viewportH - outerGapTotal);
     var p3 = sidebarLanguagePointAt(state.innerR, end);
    var p4 = sidebarLanguagePointAt(state.innerR, start);
     var largeArc = Math.abs(end - start) > 180 ? 1 : 0;


     return [
     /*
        'M', p1.x.toFixed(3), p1.y.toFixed(3),
    평상시에는 기존 세로 채움 레이아웃을 기준으로 삼는다.
        'A', state.outerR, state.outerR, 0, largeArc, 1, p2.x.toFixed(3), p2.y.toFixed(3),
    세로가 기준점보다 작아지는 경우에는 기준 높이를 고정점으로 삼고,
        'L', p3.x.toFixed(3), p3.y.toFixed(3),
    가로만 부족한 경우에는 현재 사용 가능한 세로 높이를 고정점으로 삼는다.
        'A', state.innerR, state.innerR, 0, largeArc, 0, p4.x.toFixed(3), p4.y.toFixed(3),
    이렇게 해야 가로 부족으로 scale에 들어갈 때 본문 높이가 갑자기 접히지 않는다.
        'Z'
    */
     ].join(' ');
     stageH = availableH >= baseStageH ? availableH : baseStageH;
}


function getSidebarLanguageShellPath() {
    topInner = document.getElementById('clbi-top-nav');
     return getSidebarLanguageSectorPath(-68, 68);
     bottomInner = document.getElementById('clbi-bottom-nav');
}


function getSidebarLanguageByStep(step) {
    topH = topInner ? Math.ceil(topInner.offsetHeight || topInner.getBoundingClientRect().height || 38) : 38;
     var state = sidebarLanguageState;
     bottomH = bottomInner ? Math.ceil(bottomInner.offsetHeight || bottomInner.getBoundingClientRect().height || 38) : 38;
     var index = normalizeSidebarLanguageIndex(state.baseIndex + step);
     contentH = Math.max(360, Math.floor(stageH - topH - bottomH - (gap * 2)));


     return {
     widthScale = availableW < stageW ? availableW / stageW : 1;
        index: index,
    heightScale = availableH < baseStageH ? availableH / baseStageH : 1;
        meta: getSidebarLanguageMeta(state.order[index])
    scale = Math.min(1, widthScale, heightScale);
     };
    scale = Math.max(0.50, Math.min(1, Math.floor(scale * 1000) / 1000));
}
     shouldScale = scale < 0.999;


function getSidebarLanguagePreviewIndex() {
    setClbiRootMetric(root, '--clbi-stage-design-w', stageW + 'px');
    var state = sidebarLanguageState;
     setClbiRootMetric(root, '--clbi-stage-design-h', Math.floor(stageH) + 'px');
     var step = Math.round(-state.rotation / state.sectorAngle);
     setClbiRootMetric(root, '--clbi-stage-content-h', contentH + 'px');
     return normalizeSidebarLanguageIndex(state.baseIndex + step);
    setClbiRootMetric(root, '--clbi-shell-scale', String(scale));
}


function getSidebarLanguagePreviewMeta() {
    if (body.classList.contains('clbi-shell-vertical-scale') !== shouldScale) {
    var state = sidebarLanguageState;
        body.classList.toggle('clbi-shell-vertical-scale', shouldScale);
    return getSidebarLanguageMeta(state.order[getSidebarLanguagePreviewIndex()]);
    }
}


function makeSidebarLanguageSector(step) {
    if (shouldScale) {
     var state = sidebarLanguageState;
        resetLeftRecentAdaptiveState();
    var item = getSidebarLanguageByStep(step);
        resetLeftBillboardAdaptiveState();
     var group = createSidebarLanguageSvgEl('g');
     }
     var path = createSidebarLanguageSvgEl('path');
}
     var label = createSidebarLanguageSvgEl('text');
window.updateClbiShellVerticalScale = updateClbiShellVerticalScale;
     var labelY = state.cy - 78;
 
     var angle = step * state.sectorAngle;
var $contentWrapper = $('.content-wrapper').first();
 
if ($contentWrapper.length) {
     $('#clbi-top-nav-wrap, #clbi-bottom-nav-wrap').remove();
     $contentWrapper.before(buildClbiNavHtml('top'));
     $contentWrapper.after(buildClbiNavHtml('bottom'));
    renderClbiBottomShortcutGuide();
     initClbiNationsTabpanelControls(document);
     if (typeof window.normalizeClbiShellDomOrder === 'function') window.normalizeClbiShellDomOrder();
}


    group.setAttribute('class', 'sidebar-lang-sector-group');
var CLBI_SHELL_METRICS_RAF = null;
    group.setAttribute('data-step', String(step));
var CLBI_SHELL_METRICS_SETTLE_TIMER = null;
    group.setAttribute('data-index', String(item.index));
var CLBI_SHELL_METRICS_LAST = { topH:-1, bottomH:-1 };
    group.setAttribute('data-lang', item.meta.lang);
    group.setAttribute('transform', 'rotate(' + angle + ' ' + state.cx + ' ' + state.cy + ')');


     path.setAttribute('class', 'sidebar-lang-sector');
function setClbiRootMetric(root, name, value) {
     path.setAttribute('d', getSidebarLanguageSectorPath(-state.halfSector, state.halfSector));
    var next = String(value);
     if (root.style.getPropertyValue(name) === next) return false;
     root.style.setProperty(name, next);
    return true;
}


     label.setAttribute('class', 'sidebar-lang-sector-label');
function runClbiShellMetricsBatch() {
     label.setAttribute('x', String(state.cx));
     var top = document.getElementById('clbi-top-nav-wrap');
     label.setAttribute('y', String(labelY + 5));
     var bottom = document.getElementById('clbi-bottom-nav-wrap');
     label.textContent = item.meta.dialName || item.meta.name;
     var root = document.documentElement;
    var topH = 0;
     var bottomH = 0;


     group.appendChild(path);
     CLBI_SHELL_METRICS_RAF = null;
     group.appendChild(label);
     if (!root) return;


     group.addEventListener('click', function(e) {
     if (top) topH = Math.ceil(top.offsetHeight || top.getBoundingClientRect().height || 0);
        if (sidebarLanguageState.dragging || performance.now() < sidebarLanguageState.suppressClickUntil) return;
    if (bottom) bottomH = Math.ceil(bottom.offsetHeight || bottom.getBoundingClientRect().height || 0);


         e.preventDefault();
    if (topH !== CLBI_SHELL_METRICS_LAST.topH) {
         e.stopPropagation();
         CLBI_SHELL_METRICS_LAST.topH = topH;
        setClbiRootMetric(root, '--clbi-top-nav-outer-h', topH + 'px');
    }
    if (bottomH !== CLBI_SHELL_METRICS_LAST.bottomH) {
         CLBI_SHELL_METRICS_LAST.bottomH = bottomH;
        setClbiRootMetric(root, '--clbi-bottom-nav-outer-h', bottomH + 'px');
    }


        cancelSidebarLanguageSpin();
    if (typeof updateClbiShellVerticalScale === 'function') updateClbiShellVerticalScale();
        snapSidebarLanguageToStep(parseInt(group.getAttribute('data-step') || '0', 10), true);
    if (typeof scheduleAdaptiveLeftRecentItems === 'function') scheduleAdaptiveLeftRecentItems();
    });
    if (typeof scheduleClbiContentBottomGap === 'function') scheduleClbiContentBottomGap();
}


     return group;
function requestClbiShellMetricsFrame() {
     if (CLBI_SHELL_METRICS_RAF !== null) return;
    CLBI_SHELL_METRICS_RAF = window.requestAnimationFrame
        ? window.requestAnimationFrame(runClbiShellMetricsBatch)
        : window.setTimeout(runClbiShellMetricsBatch, 16);
}
}


function renderSidebarLanguageWheel() {
function scheduleClbiShellMetrics() {
     var state = sidebarLanguageState;
     requestClbiShellMetricsFrame();
     var fan = document.getElementById('clbi-sidebar-lang-fan');
     window.clearTimeout(CLBI_SHELL_METRICS_SETTLE_TIMER);
     var svg;
     CLBI_SHELL_METRICS_SETTLE_TIMER = window.setTimeout(function () {
    var defs;
        CLBI_SHELL_METRICS_SETTLE_TIMER = null;
    var clip;
        requestClbiShellMetricsFrame();
     var clipPath;
     }, 120);
    var shadowBlur;
}
    var blur;
function watchClbiShellMetrics() {
     var fixedDepthGradient;
     var top = document.getElementById('clbi-top-nav-wrap');
     var shell;
     var bottom = document.getElementById('clbi-bottom-nav-wrap');
     var clipped;
     var observer;
    var rotor;
 
     var fixedDepthPath;
     scheduleClbiShellMetrics();
    var fixedFocus;
    var shadowSoft;
    var shadowHard;
    var rim;
    var pointer;
    var tri;
    var line;
    var step;


     if (!fan) return;
     $(window).on('resize orientationchange', scheduleClbiShellMetrics);
    $(window).on('pageshow.clbiShellScale focus.clbiShellScale', scheduleClbiShellMetrics);
    document.addEventListener('visibilitychange', function () {
        if (!document.hidden) scheduleClbiShellMetrics();
    });
    $(window).on('resize.clbiLeftBillboard orientationchange.clbiLeftBillboard', scheduleLeftSidebarVerticalFit);
    $(window).on('resize.clbiRecentViewport orientationchange.clbiRecentViewport', function () { scheduleAdaptiveLeftRecentItems(); scheduleClbiContentBottomGap(); });
    $(window).on('resize.clbiContentBottomGap orientationchange.clbiContentBottomGap', scheduleClbiContentBottomGap);


     fan.innerHTML = '';
     if (window.ResizeObserver) {
        observer = new ResizeObserver(scheduleClbiShellMetrics);
        if (top) observer.observe(top);
        if (bottom) observer.observe(bottom);
        window.CLBI_SHELL_RESIZE_OBSERVER = observer;
    }
}


    svg = createSidebarLanguageSvgEl('svg');
function bindClbiWorldbuildingToggle(buttonSelector, menuSelector) {
     svg.setAttribute('class', 'sidebar-lang-fan-svg');
     $(buttonSelector).on('click', function() {
    svg.setAttribute('viewBox', '0 0 202 150');
        var $menu = $(menuSelector);
    svg.setAttribute('preserveAspectRatio', 'xMidYMid meet');
        var $btn = $(this);
    svg.setAttribute('role', 'img');
    svg.setAttribute('aria-label', '언어 선택 다이얼');


    defs = createSidebarLanguageSvgEl('defs');
        $menu.toggleClass('worldbuilding-open');
        $btn.toggleClass('clbi-tnav-active', $menu.hasClass('worldbuilding-open'));
        scheduleClbiShellMetrics();
    });
}


    clip = createSidebarLanguageSvgEl('clipPath');
bindClbiWorldbuildingToggle('#clbi-tnav-worldbuilding', '#clbi-sub-worldbuilding');
    clip.setAttribute('id', 'clbi-sidebar-language-fan-clip');
bindClbiWorldbuildingToggle('#clbi-bnav-worldbuilding', '#clbi-bottom-sub-worldbuilding');
    clipPath = createSidebarLanguageSvgEl('path');
    clipPath.setAttribute('d', getSidebarLanguageShellPath());
    clip.appendChild(clipPath);


    shadowBlur = createSidebarLanguageSvgEl('filter');
$('#clbi-top-search-input, #clbi-bottom-search-input').on('keydown', function(e) {
    shadowBlur.setAttribute('id', 'clbi-sidebar-language-shadow-blur');
     if (e.key === 'Enter') {
    shadowBlur.setAttribute('x', '-20%');
        var q = $(this).val().trim();
     shadowBlur.setAttribute('y', '-20%');
        if (q) window.location.href = '/index.php?search=' + encodeURIComponent(q);
    shadowBlur.setAttribute('width', '140%');
     }
    shadowBlur.setAttribute('height', '140%');
});
    blur = createSidebarLanguageSvgEl('feGaussianBlur');
    blur.setAttribute('stdDeviation', '3');
     shadowBlur.appendChild(blur);


    fixedDepthGradient = createSidebarLanguageSvgEl('linearGradient');
if (window.mw && mw.hook) {
    fixedDepthGradient.setAttribute('id', 'clbi-sidebar-language-fixed-depth');
     mw.hook('wikipage.content').add(function ($content) {
    fixedDepthGradient.setAttribute('x1', '0');
         initClbiBottomShortcutSystem($content && $content[0] ? $content[0] : document);
     fixedDepthGradient.setAttribute('y1', '0');
    fixedDepthGradient.setAttribute('x2', '0');
    fixedDepthGradient.setAttribute('y2', '1');
 
    [
        ['0%', '#ffffff', '0.030'],
        ['34%', '#ffffff', '0.006'],
        ['58%', '#000000', '0.030'],
        ['100%', '#000000', '0.250']
    ].forEach(function(item) {
         var stop = createSidebarLanguageSvgEl('stop');
        stop.setAttribute('offset', item[0]);
        stop.setAttribute('stop-color', item[1]);
        stop.setAttribute('stop-opacity', item[2]);
        fixedDepthGradient.appendChild(stop);
     });
     });
}


    defs.appendChild(clip);
watchClbiShellMetrics();
    defs.appendChild(shadowBlur);
    defs.appendChild(fixedDepthGradient);
    svg.appendChild(defs);


    shell = createSidebarLanguageSvgEl('path');
});
    shell.setAttribute('class', 'sidebar-lang-shell');
    shell.setAttribute('d', getSidebarLanguageShellPath());
    svg.appendChild(shell);


    clipped = createSidebarLanguageSvgEl('g');
// 페이지 전환 사운드
    clipped.setAttribute('clip-path', 'url(#clbi-sidebar-language-fan-clip)');
var transitionSound = new Audio('/index.php?title=특수:Redirect/file/Sfx-ui-001.mp3');


     rotor = createSidebarLanguageSvgEl('g');
(function() {
     rotor.setAttribute('id', 'clbi-sidebar-lang-wheel-rotor');
     var master = parseFloat(localStorage.getItem('clbi-audio-master') || 80) / 100;
     rotor.setAttribute('class', 'sidebar-lang-wheel-rotor');
     var sfx = parseFloat(localStorage.getItem('clbi-audio-sfx') || 60) / 100;
     var sfxOn = localStorage.getItem('clbi-audio-sfxOn') !== 'false';
    transitionSound.volume = sfxOn ? master * sfx : 0;
})();


     for (step = -state.repeats; step <= state.repeats; step += 1) {
function playStaticSound() {
        rotor.appendChild(makeSidebarLanguageSector(step));
     var master = parseFloat(localStorage.getItem('clbi-audio-master') || 80) / 100;
    }
    var sfx = parseFloat(localStorage.getItem('clbi-audio-sfx') || 60) / 100;
    var sfxOn = localStorage.getItem('clbi-audio-sfxOn') !== 'false';


     clipped.appendChild(rotor);
     if (!sfxOn) return;
    svg.appendChild(clipped);


     fixedDepthPath = createSidebarLanguageSvgEl('path');
     transitionSound.volume = master * sfx;
     fixedDepthPath.setAttribute('class', 'sidebar-lang-fixed-depth');
    transitionSound.currentTime = 0;
     fixedDepthPath.setAttribute('d', getSidebarLanguageShellPath());
    transitionSound.play();
    svg.appendChild(fixedDepthPath);
}
 
// 현재 언어 감지
function getCurrentLang() {
     var langData = document.getElementById('clbi-lang-data');
     return langData ? (langData.getAttribute('data-lang') || 'ko') : 'ko';
}


     fixedFocus = createSidebarLanguageSvgEl('path');
function normalizePageName(value) {
    fixedFocus.setAttribute('class', 'sidebar-lang-fixed-focus');
     return String(value || '')
    fixedFocus.setAttribute('d', getSidebarLanguageSectorPath(-state.halfSector, state.halfSector));
        .split('?')[0]
    svg.appendChild(fixedFocus);
        .replace(/^\/index\.php\//, '')
        .replace(/_/g, ' ')
        .trim();
}


    shadowSoft = createSidebarLanguageSvgEl('path');
function buildWikiPath(title) {
     shadowSoft.setAttribute('class', 'sidebar-lang-inner-shadow-soft');
     return '/index.php/' + encodeURI(String(title || '').replace(/ /g, '_'));
    shadowSoft.setAttribute('d', getSidebarLanguageShellPath());
}
    svg.appendChild(shadowSoft);


     shadowHard = createSidebarLanguageSvgEl('path');
function getLangShortCode(lang) {
    shadowHard.setAttribute('class', 'sidebar-lang-inner-shadow-hard');
     var map = { ko: 'KR', en: 'EN', zh: 'ZH', ja: 'JA', ru: 'RU', es: 'ES' };
     shadowHard.setAttribute('d', getSidebarLanguageShellPath());
     return map[lang] || String(lang || '').toUpperCase();
    svg.appendChild(shadowHard);
}


    rim = createSidebarLanguageSvgEl('path');
function getLanguageTargetTitle(lang) {
     rim.setAttribute('class', 'sidebar-lang-rim');
     var data = document.getElementById('clbi-lang-data');
     rim.setAttribute('d', getSidebarLanguageShellPath());
     if (!data || !lang) return '';
    svg.appendChild(rim);


     pointer = createSidebarLanguageSvgEl('g');
     var keys = [
    pointer.setAttribute('class', 'sidebar-lang-fixed-pointer');
        'data-' + lang,
    pointer.setAttribute('clip-path', 'url(#clbi-sidebar-language-fan-clip)');
        'data-page-' + lang,
        'data-title-' + lang,
        'data-target-' + lang,
        'data-lang-' + lang
    ];


     tri = createSidebarLanguageSvgEl('path');
     for (var i = 0; i < keys.length; i++) {
    tri.setAttribute('class', 'sidebar-lang-pointer-triangle');
        var value = data.getAttribute(keys[i]);
    tri.setAttribute('d', 'M ' + (state.cx - 10) + ' 10 L ' + (state.cx + 10) + ' 10 L ' + state.cx + ' 26 Z');
        if (value) return value;
    pointer.appendChild(tri);
    }


     line = createSidebarLanguageSvgEl('line');
     return '';
    line.setAttribute('class', 'sidebar-lang-pointer-line');
}
    line.setAttribute('x1', String(state.cx));
    line.setAttribute('x2', String(state.cx));
    line.setAttribute('y1', '24');
    line.setAttribute('y2', '112');
    pointer.appendChild(line);


     svg.appendChild(pointer);
function escapeClbiHtml(value) {
    fan.appendChild(svg);
     return String(value == null ? '' : value)
 
        .replace(/&/g, '&amp;')
    state.rotor = rotor;
        .replace(/</g, '&lt;')
    setSidebarLanguageRotation(state.rotation, false);
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}
}


function updateSidebarLanguageDial() {
    var state = sidebarLanguageState;
    var meta = getSidebarLanguagePreviewMeta();
    var status = getSidebarLanguageStatus(meta);
    var selector = document.getElementById('clbi-sidebar-lang-selector');
    var apply = document.getElementById('clbi-sidebar-lang-apply');
    var selectedValue = document.getElementById('clbi-sidebar-lang-selected-value');
    var availabilityPanel = document.getElementById('clbi-sidebar-lang-availability-panel');
    var availabilityValue = document.getElementById('clbi-sidebar-lang-availability-value');


     if (selectedValue) {
var SIDEBAR_LANG_SVG_NS = 'http://www.w3.org/2000/svg';
        selectedValue.textContent = meta.name;
var SIDEBAR_LANGUAGE_STATUS_TITLE = 'MediaWiki:LanguageStatus.json';
     }
var SIDEBAR_LANGUAGE_LABELS = {
    ko: '한국어',
    en: 'English',
     zh: '中文',
    ja: '日本語',
    ru: 'Русский',
    es: 'Español'
};
var SIDEBAR_LANGUAGE_DIAL_LABELS = {
    ko: '한국어',
    en: 'ENG',
    zh: '中文',
    ja: '日本語',
    ru: 'РУС',
    es: 'ESP'
};
var SIDEBAR_LANGUAGE_STATUS_VALUES = {
    available: true,
    wip: true,
     unavailable: true
};


    if (availabilityPanel) {
var sidebarLanguageStatusRegistry = {};
        availabilityPanel.classList.remove('is-ready', 'is-current', 'is-locked');
var sidebarLanguageStatusLoaded = false;
        availabilityPanel.classList.add(status.className);
var sidebarLanguageStatusLoading = false;
    }
var sidebarLanguageStatusCallbacks = [];


    if (availabilityValue) {
var sidebarLanguageState = {
        availabilityValue.textContent = status.label;
     order: ['ko', 'en', 'zh', 'ja', 'ru', 'es'],
     }
    currentLang: 'ko',
 
    baseIndex: 0,
    if (apply) {
    selectedIndex: 0,
        apply.classList.toggle('is-disabled', !status.canApply);
    rotation: 0,
        apply.setAttribute('aria-disabled', status.canApply ? 'false' : 'true');
    dragging: false,
        apply.setAttribute('aria-label', status.canApply ? (meta.name + ' 적용') : (meta.isCurrent ? '현재 언어' : '사용할 수 없는 언어'));
    dragMoved: false,
     }
    dragStartX: 0,
    dragStartY: 0,
    dragStartRotation: 0,
    dragAxis: null,
    pointerCaptured: false,
    lastX: 0,
    lastTime: 0,
    releaseVelocity: 0,
    suppressClickUntil: 0,
    raf: null,
    pendingRotation: 0,
    snapTimer: null,
    inertiaRaf: null,
    navigateTimer: null,
    bound: false,
    boundElement: null,
    rotor: null,
    cx: 101,
    cy: 119,
    outerR: 109,
    innerR: 28,
    sectorAngle: 30,
    halfSector: 15,
    repeats: 8,
    dragSensitivity: 0.58,
    maxSpinVelocity: 1.75,
    minSpinVelocity: 0.055,
     spinDecel: 0.00185
};


    if (selector) {
function createSidebarLanguageSvgEl(tag) {
        selector.setAttribute('data-selected-lang', meta.lang);
    return document.createElementNS(SIDEBAR_LANG_SVG_NS, tag);
        selector.setAttribute('data-selected-code', meta.code);
}
        selector.classList.toggle('is-current', meta.isCurrent);
        selector.classList.toggle('is-ready', status.canApply);
        selector.classList.toggle('is-locked', !status.canApply && !meta.isCurrent);
        selector.classList.toggle('is-dragging', !!state.dragging);
        selector.classList.toggle('is-spinning', !!state.inertiaRaf);
    }


    return {
function normalizeSidebarLanguageIndex(index) {
        meta: meta,
    var length = sidebarLanguageState.order.length;
        status: status
    var normalized = index % length;
     };
     return normalized < 0 ? normalized + length : normalized;
}
}


function setSidebarLanguageRotation(value, animate) {
function getSidebarLanguageName(lang) {
     var state = sidebarLanguageState;
     return SIDEBAR_LANGUAGE_LABELS[lang] || String(lang || '').toUpperCase();
    state.rotation = value;
}
    updateSidebarLanguageDial();


     if (!state.rotor) return;
function getSidebarLanguageDialName(lang) {
     return SIDEBAR_LANGUAGE_DIAL_LABELS[lang] || getSidebarLanguageName(lang);
}


    if (animate) {
function normalizeSidebarLanguageStatusValue(value) {
        $('#clbi-sidebar-lang-selector').addClass('is-snapping');
    value = String(value == null ? '' : value).toLowerCase().trim();
    } else {
     return SIDEBAR_LANGUAGE_STATUS_VALUES[value] ? value : '';
        $('#clbi-sidebar-lang-selector').removeClass('is-snapping');
     }
 
    state.rotor.style.transform = 'rotate(' + state.rotation.toFixed(3) + 'deg)';
}
}


function requestSidebarLanguageRotation(value) {
function getSidebarLanguageStatusPageKey() {
     var state = sidebarLanguageState;
     var raw = String(mw.config.get('wgPageName') || '').trim();
     state.pendingRotation = value;
     var normalized = normalizePageName(raw);


     if (state.raf) return;
     return normalized || raw || '대문';
 
    state.raf = requestAnimationFrame(function() {
        state.raf = null;
        setSidebarLanguageRotation(state.pendingRotation, false);
    });
}
}


function cancelSidebarLanguageSpin() {
function getSidebarLanguageStatusEntry() {
     var state = sidebarLanguageState;
     var registry = sidebarLanguageStatusRegistry || {};
    var pages = registry.pages && typeof registry.pages === 'object' ? registry.pages : registry;
    var raw = String(mw.config.get('wgPageName') || '').trim();
    var normalized = normalizePageName(raw);
    var title = String(mw.config.get('wgTitle') || '').trim();
    var keys = [
        normalized,
        raw,
        raw.replace(/_/g, ' '),
        normalized.replace(/ /g, '_'),
        title,
        title.replace(/_/g, ' ')
    ];
    var i;


     if (state.inertiaRaf) {
     for (i = 0; i < keys.length; i += 1) {
         cancelAnimationFrame(state.inertiaRaf);
         if (keys[i] && pages[keys[i]] && typeof pages[keys[i]] === 'object') {
         state.inertiaRaf = null;
            return pages[keys[i]];
         }
     }
     }


     $('#clbi-sidebar-lang-selector').removeClass('is-spinning');
     return {};
}
}


function finishSidebarLanguageSnap(nearestIndex, callback) {
function getSidebarLanguageStatusOverride(lang) {
     var state = sidebarLanguageState;
     var entry = getSidebarLanguageStatusEntry();
    return normalizeSidebarLanguageStatusValue(entry[lang]);
}


    state.baseIndex = normalizeSidebarLanguageIndex(nearestIndex);
function flushSidebarLanguageStatusCallbacks() {
     state.selectedIndex = state.baseIndex;
     var callbacks = sidebarLanguageStatusCallbacks.slice();
     state.rotation = 0;
     sidebarLanguageStatusCallbacks.length = 0;
    state.dragging = false;


     $('#clbi-sidebar-lang-selector').removeClass('is-snapping is-dragging is-spinning');
     callbacks.forEach(function(callback) {
 
        if (typeof callback === 'function') {
    renderSidebarLanguageWheel();
            callback(sidebarLanguageStatusRegistry);
     updateSidebarLanguageDial();
        }
     });
}


function loadSidebarLanguageStatusRegistry(callback, force) {
     if (typeof callback === 'function') {
     if (typeof callback === 'function') {
         callback(getSidebarLanguageMeta(state.order[state.selectedIndex]));
         sidebarLanguageStatusCallbacks.push(callback);
     }
     }
}


function snapSidebarLanguageToStep(step, animate, callback) {
    if (sidebarLanguageStatusLoaded && !force) {
    var state = sidebarLanguageState;
        flushSidebarLanguageStatusCallbacks();
    var targetRotation = -step * state.sectorAngle;
        return;
     var nearestIndex = normalizeSidebarLanguageIndex(state.baseIndex + step);
     }


     cancelSidebarLanguageSpin();
     if (sidebarLanguageStatusLoading) return;
    clearTimeout(state.snapTimer);


     state.selectedIndex = nearestIndex;
     sidebarLanguageStatusLoading = true;
    setSidebarLanguageRotation(targetRotation, !!animate);


     state.snapTimer = setTimeout(function() {
     function finishLanguageStatus(parsed) {
         finishSidebarLanguageSnap(nearestIndex, callback);
         sidebarLanguageStatusRegistry = parsed && typeof parsed === 'object' ? parsed : {};
     }, animate ? 230 : 0);
        sidebarLanguageStatusLoaded = true;
}
        sidebarLanguageStatusLoading = false;
        flushSidebarLanguageStatusCallbacks();
     }


function snapSidebarLanguageNearest(callback) {
    if (!force && window.EntryStore && typeof window.EntryStore.fetchJsonRef === 'function') {
    var state = sidebarLanguageState;
        window.EntryStore.fetchJsonRef(SIDEBAR_LANGUAGE_STATUS_TITLE, { noStore: false })
    var step = Math.round(-state.rotation / state.sectorAngle);
            .then(function (parsed) { finishLanguageStatus(parsed); })
    snapSidebarLanguageToStep(step, true, callback);
            .catch(function () { finishLanguageStatus({}); });
}
 
function startSidebarLanguageInertiaSpin(initialVelocity) {
    var state = sidebarLanguageState;
    var velocity;
    var lastFrame;
 
    cancelSidebarLanguageSpin();
 
    velocity = Math.max(-state.maxSpinVelocity, Math.min(state.maxSpinVelocity, initialVelocity));
 
    if (Math.abs(velocity) < state.minSpinVelocity) {
        snapSidebarLanguageNearest();
         return;
         return;
     }
     }


     $('#clbi-sidebar-lang-selector').addClass('is-spinning');
     (function () {
    lastFrame = performance.now();
         var url = mw.util.getUrl(SIDEBAR_LANGUAGE_STATUS_TITLE, {
 
            action: 'raw',
    function frame(now) {
            ctype: 'application/json'
         var dt = Math.min(34, Math.max(1, now - lastFrame));
         });
        var sign = velocity < 0 ? -1 : 1;
         if (window.RevisionManifest && typeof window.RevisionManifest.addRevisionParam === 'function') {
        var nextSpeed;
             url = window.RevisionManifest.addRevisionParam(url, SIDEBAR_LANGUAGE_STATUS_TITLE);
 
         lastFrame = now;
         state.rotation += velocity * dt;
        setSidebarLanguageRotation(state.rotation, false);
 
        nextSpeed = Math.max(0, Math.abs(velocity) - (state.spinDecel * dt));
        velocity = sign * nextSpeed;
 
        if (nextSpeed <= state.minSpinVelocity) {
             state.inertiaRaf = null;
            $('#clbi-sidebar-lang-selector').removeClass('is-spinning');
            snapSidebarLanguageNearest();
            return;
         }
         }
        $.ajax({
            url: url,
            dataType: 'text',
            cache: true
        }).done(function(text) {
            var parsed = {};


        state.inertiaRaf = requestAnimationFrame(frame);
            try {
    }
                parsed = text ? JSON.parse(text) : {};
            } catch (err) {
                console.error('LanguageStatus.json parse failed:', err);
                parsed = {};
            }


     state.inertiaRaf = requestAnimationFrame(frame);
            finishLanguageStatus(parsed);
        }).fail(function() {
            finishLanguageStatus({});
        });
     })();
}
}


function scheduleSidebarLanguageNavigation(meta) {
window.CLBI_LANGUAGE_STATUS = {
     var status = getSidebarLanguageStatus(meta);
    title: SIDEBAR_LANGUAGE_STATUS_TITLE,
    languages: sidebarLanguageState.order.slice(),
    labels: SIDEBAR_LANGUAGE_LABELS,
    dialLabels: SIDEBAR_LANGUAGE_DIAL_LABELS,
    getPageKey: getSidebarLanguageStatusPageKey,
    getRegistry: function() {
        return sidebarLanguageStatusRegistry || {};
     },
    reload: function(callback) {
        sidebarLanguageStatusLoaded = false;
        loadSidebarLanguageStatusRegistry(function() {
            renderSidebarLanguageBox();
            if (typeof callback === 'function') callback(sidebarLanguageStatusRegistry);
        }, true);
    },
    refreshDial: function() {
        renderSidebarLanguageBox();
    }
};


     if (!meta || !status.canApply) return;
function getSidebarLanguageMeta(lang) {
    var currentLang = getCurrentLang();
     var targetTitle = getLanguageTargetTitle(lang);
    var isCurrent = lang === currentLang;


     clearTimeout(sidebarLanguageState.navigateTimer);
     return {
    sidebarLanguageState.navigateTimer = setTimeout(function() {
        lang: lang,
         var title = getLanguageTargetTitle(meta.lang);
        code: getLangShortCode(lang),
 
         name: getSidebarLanguageName(lang),
         if (!title || meta.lang === getCurrentLang()) return;
         dialName: getSidebarLanguageDialName(lang),
 
        targetTitle: targetTitle,
         window.location.href = buildWikiPath(title);
         isCurrent: isCurrent,
     }, 70);
        canMove: !!targetTitle && !isCurrent
     };
}
}


function setSidebarLanguageSelection(lang) {
function getSidebarLanguageStatus(meta) {
     var state = sidebarLanguageState;
     var override;
    var index = state.order.indexOf(lang);


     if (index < 0) index = state.order.indexOf(getCurrentLang());
     if (!meta) {
     if (index < 0) index = 0;
        return {
            className: 'is-locked',
            label: 'UNAVAILABLE',
            canApply: false
        };
     }


     if (state.raf) {
     if (meta.isCurrent) {
         cancelAnimationFrame(state.raf);
         return {
         state.raf = null;
            className: 'is-current',
            label: 'CURRENT',
            canApply: false
         };
     }
     }


     cancelSidebarLanguageSpin();
     override = getSidebarLanguageStatusOverride(meta.lang);
    clearTimeout(state.snapTimer);


     state.currentLang = lang;
     if (override === 'wip') {
    state.baseIndex = index;
        return {
    state.selectedIndex = index;
            className: 'is-locked',
    state.rotation = 0;
            label: 'WIP',
    state.dragging = false;
            canApply: false
    state.dragMoved = false;
        };
     state.releaseVelocity = 0;
     }


     renderSidebarLanguageWheel();
     if (override === 'unavailable') {
     updateSidebarLanguageDial();
        return {
}
            className: 'is-locked',
            label: 'UNAVAILABLE',
            canApply: false
        };
     }


function moveSidebarLanguageSelection(delta) {
    if (override === 'available' || meta.targetTitle) {
     snapSidebarLanguageToStep(-delta, true);
        return {
            className: meta.targetTitle ? 'is-ready' : 'is-locked',
            label: meta.targetTitle ? 'AVAILABLE' : 'UNAVAILABLE',
            canApply: !!meta.targetTitle
        };
     }
 
    return {
        className: 'is-locked',
        label: 'UNAVAILABLE',
        canApply: false
    };
}
}


function bindSidebarLanguageSelector() {
function sidebarLanguageRad(deg) {
    return (deg * Math.PI) / 180;
}
 
function sidebarLanguagePointAt(radius, deg) {
     var state = sidebarLanguageState;
     var state = sidebarLanguageState;
     var selector = document.getElementById('clbi-sidebar-lang-selector');
     var angle = sidebarLanguageRad(deg);
    var fan = document.getElementById('clbi-sidebar-lang-fan');
    var apply = document.getElementById('clbi-sidebar-lang-apply');


     if (!selector || !fan || !apply) return;
     return {
        x: state.cx + Math.sin(angle) * radius,
        y: state.cy - Math.cos(angle) * radius
    };
}


     if (state.bound && state.boundElement === selector) return;
function getSidebarLanguageSectorPath(start, end) {
    var state = sidebarLanguageState;
     var p1 = sidebarLanguagePointAt(state.outerR, start);
    var p2 = sidebarLanguagePointAt(state.outerR, end);
    var p3 = sidebarLanguagePointAt(state.innerR, end);
    var p4 = sidebarLanguagePointAt(state.innerR, start);
    var largeArc = Math.abs(end - start) > 180 ? 1 : 0;


     state.bound = true;
     return [
     state.boundElement = selector;
        'M', p1.x.toFixed(3), p1.y.toFixed(3),
        'A', state.outerR, state.outerR, 0, largeArc, 1, p2.x.toFixed(3), p2.y.toFixed(3),
        'L', p3.x.toFixed(3), p3.y.toFixed(3),
        'A', state.innerR, state.innerR, 0, largeArc, 0, p4.x.toFixed(3), p4.y.toFixed(3),
        'Z'
     ].join(' ');
}


    fan.addEventListener('pointerdown', function(e) {
function getSidebarLanguageShellPath() {
        cancelSidebarLanguageSpin();
    return getSidebarLanguageSectorPath(-68, 68);
        clearTimeout(state.snapTimer);
}


        state.dragging = true;
function getSidebarLanguageByStep(step) {
        state.dragMoved = false;
    var state = sidebarLanguageState;
        state.dragStartX = e.clientX;
    var index = normalizeSidebarLanguageIndex(state.baseIndex + step);
        state.dragStartY = e.clientY || 0;
        state.dragStartRotation = state.rotation;
        state.dragAxis = null;
        state.pointerCaptured = false;
        state.lastX = e.clientX;
        state.lastTime = performance.now();
        state.releaseVelocity = 0;


         selector.classList.add('is-dragging');
    return {
         selector.classList.remove('is-snapping');
         index: index,
         meta: getSidebarLanguageMeta(state.order[index])
    };
}


        /*
function getSidebarLanguagePreviewIndex() {
        Vertical page scrolling must stay available when the pointer starts on
    var state = sidebarLanguageState;
        the language dial. Capture and preventDefault are delayed until a
    var step = Math.round(-state.rotation / state.sectorAngle);
        horizontal drag is confirmed.
     return normalizeSidebarLanguageIndex(state.baseIndex + step);
        */
}
     });


    fan.addEventListener('pointermove', function(e) {
function getSidebarLanguagePreviewMeta() {
        var now;
    var state = sidebarLanguageState;
        var totalDx;
    return getSidebarLanguageMeta(state.order[getSidebarLanguagePreviewIndex()]);
        var totalDy;
}
        var frameDx;
        var dt;
        var instantVelocity;


        if (!state.dragging) return;
function makeSidebarLanguageSector(step) {
    var state = sidebarLanguageState;
    var item = getSidebarLanguageByStep(step);
    var group = createSidebarLanguageSvgEl('g');
    var path = createSidebarLanguageSvgEl('path');
    var label = createSidebarLanguageSvgEl('text');
    var labelY = state.cy - 78;
    var angle = step * state.sectorAngle;


        totalDx = e.clientX - state.dragStartX;
    group.setAttribute('class', 'sidebar-lang-sector-group');
        totalDy = (e.clientY || 0) - state.dragStartY;
    group.setAttribute('data-step', String(step));
    group.setAttribute('data-index', String(item.index));
    group.setAttribute('data-lang', item.meta.lang);
    group.setAttribute('transform', 'rotate(' + angle + ' ' + state.cx + ' ' + state.cy + ')');


        if (!state.dragAxis && (Math.abs(totalDx) > 4 || Math.abs(totalDy) > 4)) {
    path.setAttribute('class', 'sidebar-lang-sector');
            state.dragAxis = Math.abs(totalDx) >= Math.abs(totalDy) ? 'x' : 'y';
    path.setAttribute('d', getSidebarLanguageSectorPath(-state.halfSector, state.halfSector));


            if (state.dragAxis === 'y') {
    label.setAttribute('class', 'sidebar-lang-sector-label');
                state.dragging = false;
    label.setAttribute('x', String(state.cx));
                state.dragMoved = false;
    label.setAttribute('y', String(labelY + 5));
                state.dragAxis = null;
    label.textContent = item.meta.dialName || item.meta.name;
                state.pointerCaptured = false;
                selector.classList.remove('is-dragging');
                return;
            }


            if (fan.setPointerCapture && e.pointerId != null) {
    group.appendChild(path);
                try {
    group.appendChild(label);
                    fan.setPointerCapture(e.pointerId);
                    state.pointerCaptured = true;
                } catch (err) {
                    state.pointerCaptured = false;
                }
            }
        }


         if (state.dragAxis !== 'x') return;
    group.addEventListener('click', function(e) {
         if (sidebarLanguageState.dragging || performance.now() < sidebarLanguageState.suppressClickUntil) return;


         now = performance.now();
         e.preventDefault();
         frameDx = e.clientX - state.lastX;
         e.stopPropagation();
        dt = Math.max(1, now - state.lastTime);


         if (Math.abs(totalDx) > 3) state.dragMoved = true;
         cancelSidebarLanguageSpin();
 
         snapSidebarLanguageToStep(parseInt(group.getAttribute('data-step') || '0', 10), true);
         instantVelocity = (frameDx * state.dragSensitivity) / dt;
        state.releaseVelocity = (state.releaseVelocity * 0.62) + (instantVelocity * 0.38);
        state.lastX = e.clientX;
        state.lastTime = now;
 
        requestSidebarLanguageRotation(state.dragStartRotation + totalDx * state.dragSensitivity);
        e.preventDefault();
        e.stopPropagation();
     });
     });


     function finishDrag(e) {
     return group;
        var velocityAge;
}
        var throwVelocity;
        var wasHorizontal;


        if (!state.dragging) return;
function renderSidebarLanguageWheel() {
    var state = sidebarLanguageState;
    var fan = document.getElementById('clbi-sidebar-lang-fan');
    var svg;
    var defs;
    var clip;
    var clipPath;
    var shadowBlur;
    var blur;
    var fixedDepthGradient;
    var shell;
    var clipped;
    var rotor;
    var fixedDepthPath;
    var fixedFocus;
    var shadowSoft;
    var shadowHard;
    var rim;
    var pointer;
    var tri;
    var line;
    var step;


        wasHorizontal = state.dragAxis === 'x';
    if (!fan) return;
        state.dragging = false;
        selector.classList.remove('is-dragging');


        if (fan.releasePointerCapture && state.pointerCaptured && e && e.pointerId != null) {
    fan.innerHTML = '';
            try { fan.releasePointerCapture(e.pointerId); } catch (err) {}
        }


        state.pointerCaptured = false;
    svg = createSidebarLanguageSvgEl('svg');
        state.dragAxis = null;
    svg.setAttribute('class', 'sidebar-lang-fan-svg');
    svg.setAttribute('viewBox', '0 0 202 150');
    svg.setAttribute('preserveAspectRatio', 'xMidYMid meet');
    svg.setAttribute('role', 'img');
    svg.setAttribute('aria-label', '언어 선택 다이얼');


        if (!wasHorizontal && !state.dragMoved) {
    defs = createSidebarLanguageSvgEl('defs');
            return;
        }


        velocityAge = performance.now() - state.lastTime;
    clip = createSidebarLanguageSvgEl('clipPath');
        throwVelocity = velocityAge > 120 ? 0 : state.releaseVelocity;
    clip.setAttribute('id', 'clbi-sidebar-language-fan-clip');
    clipPath = createSidebarLanguageSvgEl('path');
    clipPath.setAttribute('d', getSidebarLanguageShellPath());
    clip.appendChild(clipPath);


        if (state.dragMoved) {
    shadowBlur = createSidebarLanguageSvgEl('filter');
            state.suppressClickUntil = performance.now() + 180;
    shadowBlur.setAttribute('id', 'clbi-sidebar-language-shadow-blur');
        }
    shadowBlur.setAttribute('x', '-20%');
    shadowBlur.setAttribute('y', '-20%');
    shadowBlur.setAttribute('width', '140%');
    shadowBlur.setAttribute('height', '140%');
    blur = createSidebarLanguageSvgEl('feGaussianBlur');
    blur.setAttribute('stdDeviation', '3');
    shadowBlur.appendChild(blur);


        if (state.dragMoved && Math.abs(throwVelocity) >= state.minSpinVelocity) {
    fixedDepthGradient = createSidebarLanguageSvgEl('linearGradient');
            startSidebarLanguageInertiaSpin(throwVelocity);
    fixedDepthGradient.setAttribute('id', 'clbi-sidebar-language-fixed-depth');
        } else {
    fixedDepthGradient.setAttribute('x1', '0');
            snapSidebarLanguageNearest();
    fixedDepthGradient.setAttribute('y1', '0');
        }
    fixedDepthGradient.setAttribute('x2', '0');
    fixedDepthGradient.setAttribute('y2', '1');


         if (e) {
    [
            e.preventDefault();
        ['0%', '#ffffff', '0.030'],
            e.stopPropagation();
        ['34%', '#ffffff', '0.006'],
         }
        ['58%', '#000000', '0.030'],
     }
         ['100%', '#000000', '0.250']
    ].forEach(function(item) {
        var stop = createSidebarLanguageSvgEl('stop');
        stop.setAttribute('offset', item[0]);
        stop.setAttribute('stop-color', item[1]);
        stop.setAttribute('stop-opacity', item[2]);
         fixedDepthGradient.appendChild(stop);
     });


     fan.addEventListener('pointerup', finishDrag);
     defs.appendChild(clip);
     fan.addEventListener('pointercancel', finishDrag);
     defs.appendChild(shadowBlur);
     fan.addEventListener('lostpointercapture', function() {
     defs.appendChild(fixedDepthGradient);
        if (!state.dragging) return;
    svg.appendChild(defs);


        state.dragging = false;
    shell = createSidebarLanguageSvgEl('path');
        state.pointerCaptured = false;
    shell.setAttribute('class', 'sidebar-lang-shell');
        state.dragAxis = null;
    shell.setAttribute('d', getSidebarLanguageShellPath());
        selector.classList.remove('is-dragging');
    svg.appendChild(shell);


        if (state.dragMoved && Math.abs(state.releaseVelocity) >= state.minSpinVelocity) {
    clipped = createSidebarLanguageSvgEl('g');
            state.suppressClickUntil = performance.now() + 180;
    clipped.setAttribute('clip-path', 'url(#clbi-sidebar-language-fan-clip)');
            startSidebarLanguageInertiaSpin(state.releaseVelocity);
        } else {
            snapSidebarLanguageNearest();
        }
    });


     apply.addEventListener('click', function(e) {
     rotor = createSidebarLanguageSvgEl('g');
        e.preventDefault();
    rotor.setAttribute('id', 'clbi-sidebar-lang-wheel-rotor');
        e.stopPropagation();
    rotor.setAttribute('class', 'sidebar-lang-wheel-rotor');


        snapSidebarLanguageNearest(function(meta) {
    for (step = -state.repeats; step <= state.repeats; step += 1) {
            scheduleSidebarLanguageNavigation(meta);
        rotor.appendChild(makeSidebarLanguageSector(step));
        });
     }
     });


     selector.addEventListener('keydown', function(e) {
     clipped.appendChild(rotor);
        if (e.key === 'ArrowLeft') {
    svg.appendChild(clipped);
            moveSidebarLanguageSelection(-1);
            e.preventDefault();
        }


        if (e.key === 'ArrowRight') {
    fixedDepthPath = createSidebarLanguageSvgEl('path');
            moveSidebarLanguageSelection(1);
    fixedDepthPath.setAttribute('class', 'sidebar-lang-fixed-depth');
            e.preventDefault();
    fixedDepthPath.setAttribute('d', getSidebarLanguageShellPath());
        }
    svg.appendChild(fixedDepthPath);


        if (e.key === 'Enter' || e.key === ' ') {
    fixedFocus = createSidebarLanguageSvgEl('path');
            apply.click();
    fixedFocus.setAttribute('class', 'sidebar-lang-fixed-focus');
            e.preventDefault();
    fixedFocus.setAttribute('d', getSidebarLanguageSectorPath(-state.halfSector, state.halfSector));
        }
     svg.appendChild(fixedFocus);
     });
}


function renderSidebarLanguageBox() {
    shadowSoft = createSidebarLanguageSvgEl('path');
     bindSidebarLanguageSelector();
     shadowSoft.setAttribute('class', 'sidebar-lang-inner-shadow-soft');
     setSidebarLanguageSelection(getCurrentLang());
     shadowSoft.setAttribute('d', getSidebarLanguageShellPath());
    svg.appendChild(shadowSoft);


     if (!sidebarLanguageStatusLoaded) {
     shadowHard = createSidebarLanguageSvgEl('path');
        loadSidebarLanguageStatusRegistry(function() {
    shadowHard.setAttribute('class', 'sidebar-lang-inner-shadow-hard');
            setSidebarLanguageSelection(getCurrentLang());
    shadowHard.setAttribute('d', getSidebarLanguageShellPath());
        });
    svg.appendChild(shadowHard);
    }
}


function loadRecentChangesList(targetSelector, limit) {
    rim = createSidebarLanguageSvgEl('path');
     var $target = $(targetSelector);
    rim.setAttribute('class', 'sidebar-lang-rim');
    rim.setAttribute('d', getSidebarLanguageShellPath());
     svg.appendChild(rim);


     if (!$target.length) return;
     pointer = createSidebarLanguageSvgEl('g');
    pointer.setAttribute('class', 'sidebar-lang-fixed-pointer');
    pointer.setAttribute('clip-path', 'url(#clbi-sidebar-language-fan-clip)');


     var lang = getCurrentLang();
     tri = createSidebarLanguageSvgEl('path');
     var t = (window.LANG && window.LANG[lang]) ? window.LANG[lang] : (window.LANG ? window.LANG.ko : null);
     tri.setAttribute('class', 'sidebar-lang-pointer-triangle');
     var isNewsList = $target.closest('.clbi-left-news-box').length > 0;
    tri.setAttribute('d', 'M ' + (state.cx - 10) + ' 10 L ' + (state.cx + 10) + ' 10 L ' + state.cx + ' 26 Z');
    pointer.appendChild(tri);
 
     line = createSidebarLanguageSvgEl('line');
    line.setAttribute('class', 'sidebar-lang-pointer-line');
    line.setAttribute('x1', String(state.cx));
    line.setAttribute('x2', String(state.cx));
    line.setAttribute('y1', '24');
    line.setAttribute('y2', '112');
    pointer.appendChild(line);
 
    svg.appendChild(pointer);
    fan.appendChild(svg);


     function escapeHtml(value) {
     state.rotor = rotor;
        return String(value == null ? '' : value)
    setSidebarLanguageRotation(state.rotation, false);
            .replace(/&/g, '&amp;')
}
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }


     $target.html((t && t.loading) ? t.loading : '불러오는 중...');
function updateSidebarLanguageDial() {
    var state = sidebarLanguageState;
     var meta = getSidebarLanguagePreviewMeta();
    var status = getSidebarLanguageStatus(meta);
    var selector = document.getElementById('clbi-sidebar-lang-selector');
    var apply = document.getElementById('clbi-sidebar-lang-apply');
    var selectedValue = document.getElementById('clbi-sidebar-lang-selected-value');
    var availabilityPanel = document.getElementById('clbi-sidebar-lang-availability-panel');
    var availabilityValue = document.getElementById('clbi-sidebar-lang-availability-value');


     $.getJSON(
     if (selectedValue) {
         '/api.php?action=query&list=recentchanges&rclimit=' + encodeURIComponent(limit || 5) + '&rcprop=title|timestamp|user&format=json&rcnamespace=0&rctype=edit|new',
         selectedValue.textContent = meta.name;
        function(data) {
    }
            var items = data && data.query ? data.query.recentchanges : [];
            var html = '';


            if (!items || !items.length) {
    if (availabilityPanel) {
                $target.html('표시할 변경 사항이 없습니다.');
        availabilityPanel.classList.remove('is-ready', 'is-current', 'is-locked');
                return;
        availabilityPanel.classList.add(status.className);
            }
    }


            $.each(items, function(i, item) {
    if (availabilityValue) {
                var label = timeAgo(item.timestamp);
        availabilityValue.textContent = status.label;
                var title = item.title || '';
    }
                var userName = item.user || 'Unknown';
                var pageHref = buildWikiPath(title);
                var avatarSrc = '/index.php?title=특수:Redirect/file/Pfp-' + encodeURIComponent(userName) + '.png';


                if (isNewsList) {
    if (apply) {
                    html +=
        apply.classList.toggle('is-disabled', !status.canApply);
                        '<a href="' + escapeHtml(pageHref) + '" class="news-recent-item">' +
        apply.setAttribute('aria-disabled', status.canApply ? 'false' : 'true');
                            '<img class="news-recent-avatar" src="' + escapeHtml(avatarSrc) + '" alt="" onerror="this.onerror=null;this.src=\'/index.php?title=특수:Redirect/file/Pfp-default.png\';">' +
        apply.setAttribute('aria-label', status.canApply ? (meta.name + ' 적용') : (meta.isCurrent ? '현재 언어' : '사용할 수 없는 언어'));
                            '<div class="news-recent-main">' +
    }
                                '<div class="news-recent-title-wrap">' +
                                    '<span class="news-recent-title">' + escapeHtml(title) + '</span>' +
                                '</div>' +
                                '<div class="news-recent-meta">' +
                                    '<span class="news-recent-user">@' + escapeHtml(userName) + '</span>' +
                                '</div>' +
                            '</div>' +
                            '<span class="news-recent-time">' + escapeHtml(label) + '</span>' +
                        '</a>';
                } else {
                    html +=
                        '<div class="clbi-recent-item">' +
                            '<div class="clbi-recent-title-wrap">' +
                                '<a href="' + escapeHtml(pageHref) + '" class="clbi-recent-title">' + escapeHtml(title) + '</a>' +
                            '</div>' +
                            '<span class="clbi-recent-time">' + escapeHtml(label) + '</span>' +
                        '</div>';
                }
            });


            if (isNewsList) {
    if (selector) {
                $target.html(
        selector.setAttribute('data-selected-lang', meta.lang);
                    '<div class="news-recent-viewport">' +
        selector.setAttribute('data-selected-code', meta.code);
                        '<div class="news-recent-stack">' + html + '</div>' +
        selector.classList.toggle('is-current', meta.isCurrent);
                    '</div>'
        selector.classList.toggle('is-ready', status.canApply);
                );
        selector.classList.toggle('is-locked', !status.canApply && !meta.isCurrent);
        selector.classList.toggle('is-dragging', !!state.dragging);
        selector.classList.toggle('is-spinning', !!state.inertiaRaf);
    }


                if (typeof ensureNewsBottomFinish === 'function') {
    return {
                    ensureNewsBottomFinish();
        meta: meta,
                }
        status: status
            } else {
    };
                $target.html(html);
}
            }


            if (isNewsList && typeof scheduleAdaptiveLeftRecentItems === 'function') {
function setSidebarLanguageRotation(value, animate) {
                scheduleAdaptiveLeftRecentItems();
    var state = sidebarLanguageState;
            }
    state.rotation = value;
    updateSidebarLanguageDial();


            $target.find(isNewsList ? '.news-recent-item' : '.clbi-recent-item').each(function() {
    if (!state.rotor) return;
                var wrap = $(this).find(isNewsList ? '.news-recent-title-wrap' : '.clbi-recent-title-wrap');
                var title = $(this).find(isNewsList ? '.news-recent-title' : '.clbi-recent-title');


                if (!wrap.length || !title.length) return;
    if (animate) {
        $('#clbi-sidebar-lang-selector').addClass('is-snapping');
    } else {
        $('#clbi-sidebar-lang-selector').removeClass('is-snapping');
    }


                var wrapW = wrap.width();
    state.rotor.style.transform = 'rotate(' + state.rotation.toFixed(3) + 'deg)';
                var titleW = title[0].scrollWidth;
}


                if (titleW > wrapW + 20) {
function requestSidebarLanguageRotation(value) {
                    var duration = titleW / 40;
    var state = sidebarLanguageState;
    state.pendingRotation = value;


                    title.css({
     if (state.raf) return;
                        animation: 'clbi-scroll ' + duration + 's linear infinite',
                        '--scroll-dist': '-' + (titleW - wrapW + 8) + 'px'
                    });
                }
            });
        }
     ).fail(function() {
        var lang = getCurrentLang();
        var t = (window.LANG && window.LANG[lang]) ? window.LANG[lang] : (window.LANG ? window.LANG.ko : null);


        $target.html((t && t.loadFail) ? t.loadFail : '불러오기 실패');
    state.raf = requestAnimationFrame(function() {
        state.raf = null;
        setSidebarLanguageRotation(state.pendingRotation, false);
     });
     });
}
}


function cancelSidebarLanguageSpin() {
    var state = sidebarLanguageState;


function ensureRecentViewport() {
    if (state.inertiaRaf) {
    var list = document.getElementById('clbi-left-recent-list');
        cancelAnimationFrame(state.inertiaRaf);
    var viewport;
        state.inertiaRaf = null;
    var stack;
     }
     var children;


     if (!list) return null;
     $('#clbi-sidebar-lang-selector').removeClass('is-spinning');
}


    viewport = list.querySelector(':scope > .news-recent-viewport');
function finishSidebarLanguageSnap(nearestIndex, callback) {
     stack = viewport ? viewport.querySelector(':scope > .news-recent-stack') : null;
     var state = sidebarLanguageState;


     if (viewport && stack) return viewport;
     state.baseIndex = normalizeSidebarLanguageIndex(nearestIndex);
    state.selectedIndex = state.baseIndex;
    state.rotation = 0;
    state.dragging = false;


     children = Array.prototype.slice.call(list.children || []);
     $('#clbi-sidebar-lang-selector').removeClass('is-snapping is-dragging is-spinning');


     viewport = document.createElement('div');
     renderSidebarLanguageWheel();
     viewport.className = 'news-recent-viewport';
     updateSidebarLanguageDial();


     stack = document.createElement('div');
     if (typeof callback === 'function') {
     stack.className = 'news-recent-stack';
        callback(getSidebarLanguageMeta(state.order[state.selectedIndex]));
     }
}


    children.forEach(function (child) {
function snapSidebarLanguageToStep(step, animate, callback) {
        if (child.classList && child.classList.contains('news-recent-viewport')) return;
    var state = sidebarLanguageState;
        stack.appendChild(child);
    var targetRotation = -step * state.sectorAngle;
     });
     var nearestIndex = normalizeSidebarLanguageIndex(state.baseIndex + step);


     viewport.appendChild(stack);
     cancelSidebarLanguageSpin();
     list.appendChild(viewport);
     clearTimeout(state.snapTimer);


     return viewport;
     state.selectedIndex = nearestIndex;
    setSidebarLanguageRotation(targetRotation, !!animate);
 
    state.snapTimer = setTimeout(function() {
        finishSidebarLanguageSnap(nearestIndex, callback);
    }, animate ? 230 : 0);
}
 
function snapSidebarLanguageNearest(callback) {
    var state = sidebarLanguageState;
    var step = Math.round(-state.rotation / state.sectorAngle);
    snapSidebarLanguageToStep(step, true, callback);
}
}


function ensureNewsBottomFinish() {
function startSidebarLanguageInertiaSpin(initialVelocity) {
     var newsBox = document.querySelector('#clbi-left-sidebar .clbi-left-news-box');
     var state = sidebarLanguageState;
     var content = newsBox ? newsBox.querySelector('.clbi-news-box') : null;
     var velocity;
     var finish;
     var lastFrame;


     if (!content) return null;
     cancelSidebarLanguageSpin();


     finish = content.querySelector(':scope > .news-bottom-finish');
     velocity = Math.max(-state.maxSpinVelocity, Math.min(state.maxSpinVelocity, initialVelocity));


     if (!finish) {
     if (Math.abs(velocity) < state.minSpinVelocity) {
        finish = document.createElement('div');
         snapSidebarLanguageNearest();
        finish.className = 'news-bottom-finish';
         return;
         finish.setAttribute('aria-hidden', 'true');
         content.appendChild(finish);
     }
     }


     return finish;
     $('#clbi-sidebar-lang-selector').addClass('is-spinning');
}
    lastFrame = performance.now();
 
    function frame(now) {
        var dt = Math.min(34, Math.max(1, now - lastFrame));
        var sign = velocity < 0 ? -1 : 1;
        var nextSpeed;
 
        lastFrame = now;
        state.rotation += velocity * dt;
        setSidebarLanguageRotation(state.rotation, false);


function updateAdaptiveLeftRecentItems() {
        nextSpeed = Math.max(0, Math.abs(velocity) - (state.spinDecel * dt));
    /*
        velocity = sign * nextSpeed;
    134 기준: 좌측 사이드는 뉴스 확장형 flex 레이아웃이 높이를 담당한다.
    이전 adaptive 코드는 항목을 숨기거나 mask/fade를 걸기 위한 것이었으므로
    여기서는 잔여 상태만 정리하고 DOM 래퍼만 보장한다.
    */
    resetLeftRecentAdaptiveState();


    if (typeof ensureRecentViewport === 'function') {
        if (nextSpeed <= state.minSpinVelocity) {
        ensureRecentViewport();
            state.inertiaRaf = null;
    }
            $('#clbi-sidebar-lang-selector').removeClass('is-spinning');
            snapSidebarLanguageNearest();
            return;
        }


    if (typeof ensureNewsBottomFinish === 'function') {
        state.inertiaRaf = requestAnimationFrame(frame);
        ensureNewsBottomFinish();
     }
     }


     if (typeof scheduleClbiContentBottomGap === 'function') {
     state.inertiaRaf = requestAnimationFrame(frame);
        scheduleClbiContentBottomGap();
    }
}
}


function scheduleAdaptiveLeftRecentItems() {
function scheduleSidebarLanguageNavigation(meta) {
     window.requestAnimationFrame(function () {
     var status = getSidebarLanguageStatus(meta);
        updateAdaptiveLeftRecentItems();
    });


     window.setTimeout(updateAdaptiveLeftRecentItems, 80);
     if (!meta || !status.canApply) return;
    window.setTimeout(updateAdaptiveLeftRecentItems, 240);
}


    clearTimeout(sidebarLanguageState.navigateTimer);
    sidebarLanguageState.navigateTimer = setTimeout(function() {
        var title = getLanguageTargetTitle(meta.lang);


        if (!title || meta.lang === getCurrentLang()) return;


function updateClbiContentBottomGap(iteration) {
        window.location.href = buildWikiPath(title);
    var content = document.querySelector('.container-fluid.liberty-content');
     }, 70);
    var main = document.querySelector('.liberty-content-main');
}
     var bottomNav = document.getElementById('clbi-bottom-nav-wrap');
    var desiredGap = 8;
    var rootStyle;
    var scale = 1;
    var contentRect;
    var bottomTop;
    var targetHeight;
    var currentHeight;
    var visualGap;


     iteration = iteration || 0;
function setSidebarLanguageSelection(lang) {
     var state = sidebarLanguageState;
    var index = state.order.indexOf(lang);


     if (!content || !main || !bottomNav) return;
     if (index < 0) index = state.order.indexOf(getCurrentLang());
    if (index < 0) index = 0;


    /*
     if (state.raf) {
    하단 간격은 scale 모드에서도 같은 기준으로 계산한다.
         cancelAnimationFrame(state.raf);
    transform:scale()이 걸리면 getBoundingClientRect()는 축소된 화면 좌표를 반환하므로,
         state.raf = null;
    목표 간격 8px도 scale을 곱한 화면 좌표로 비교하고 다시 design px로 환산한다.
 
    목표:
    .liberty-content-main.bottom === #clbi-bottom-nav-wrap.top - 8px
    */
     if (document.body && document.body.classList && document.body.classList.contains('clbi-shell-vertical-scale')) {
         rootStyle = window.getComputedStyle(document.documentElement);
         scale = parseFloat(rootStyle.getPropertyValue('--clbi-shell-scale')) || 1;
        scale = Math.max(0.25, scale);
     }
     }


     contentRect = content.getBoundingClientRect();
     cancelSidebarLanguageSpin();
    bottomTop = bottomNav.getBoundingClientRect().top;
     clearTimeout(state.snapTimer);
    visualGap = desiredGap * scale;
     targetHeight = Math.floor((bottomTop - contentRect.top - visualGap) / scale);
    targetHeight = Math.max(120, targetHeight);


     currentHeight = Math.round(content.getBoundingClientRect().height / scale);
     state.currentLang = lang;
 
    state.baseIndex = index;
     content.style.setProperty('--clbi-content-extra', '0px');
    state.selectedIndex = index;
     content.style.setProperty('height', targetHeight + 'px', 'important');
    state.rotation = 0;
     content.style.setProperty('max-height', targetHeight + 'px', 'important');
     state.dragging = false;
     state.dragMoved = false;
     state.releaseVelocity = 0;


     if (Math.abs(currentHeight - targetHeight) >= 1 && iteration < 4) {
     renderSidebarLanguageWheel();
        window.requestAnimationFrame(function () {
    updateSidebarLanguageDial();
            updateClbiContentBottomGap(iteration + 1);
        });
    }
}
}


function scheduleClbiContentBottomGap() {
function moveSidebarLanguageSelection(delta) {
     window.requestAnimationFrame(function () {
     snapSidebarLanguageToStep(-delta, true);
        updateClbiContentBottomGap(0);
    });
    window.setTimeout(function () {
        updateClbiContentBottomGap(0);
    }, 40);
    window.setTimeout(function () {
        updateClbiContentBottomGap(0);
    }, 120);
    window.setTimeout(function () {
        updateClbiContentBottomGap(0);
    }, 280);
    window.setTimeout(function () {
        updateClbiContentBottomGap(0);
    }, 520);
}
}


function bindSidebarLanguageSelector() {
    var state = sidebarLanguageState;
    var selector = document.getElementById('clbi-sidebar-lang-selector');
    var fan = document.getElementById('clbi-sidebar-lang-fan');
    var apply = document.getElementById('clbi-sidebar-lang-apply');


function updateLeftBillboardAdaptive() {
     if (!selector || !fan || !apply) return;
    /*
    134 기준: Ad는 이미지/CRT 비율을 유지하는 고정 슬롯이다.
    남는 세로 공간은 뉴스 박스가 흡수하므로, Ad에 하단 finish를 늘리거나
    title-only 상태로 접는 adaptive 보정은 사용하지 않는다.
    */
     resetLeftBillboardAdaptiveState();
}


function scheduleLeftBillboardAdaptive() {
     if (state.bound && state.boundElement === selector) return;
     window.requestAnimationFrame(updateLeftBillboardAdaptive);
    window.setTimeout(updateLeftBillboardAdaptive, 80);
    window.setTimeout(updateLeftBillboardAdaptive, 240);
}


function scheduleLeftSidebarVerticalFit() {
     state.bound = true;
     if (typeof scheduleAdaptiveLeftRecentItems === 'function') {
     state.boundElement = selector;
        scheduleAdaptiveLeftRecentItems();
     }


     if (typeof scheduleLeftBillboardAdaptive === 'function') {
     fan.addEventListener('pointerdown', function(e) {
         scheduleLeftBillboardAdaptive();
         cancelSidebarLanguageSpin();
    }
        clearTimeout(state.snapTimer);


    window.setTimeout(function () {
        state.dragging = true;
         if (typeof scheduleAdaptiveLeftRecentItems === 'function') {
        state.dragMoved = false;
            scheduleAdaptiveLeftRecentItems();
        state.dragStartX = e.clientX;
         }
        state.dragStartY = e.clientY || 0;
        state.dragStartRotation = state.rotation;
         state.dragAxis = null;
        state.pointerCaptured = false;
        state.lastX = e.clientX;
        state.lastTime = performance.now();
         state.releaseVelocity = 0;


         if (typeof scheduleLeftBillboardAdaptive === 'function') {
         selector.classList.add('is-dragging');
            scheduleLeftBillboardAdaptive();
         selector.classList.remove('is-snapping');
         }
    }, 120);
}


        /*
        Vertical page scrolling must stay available when the pointer starts on
        the language dial. Capture and preventDefault are delayed until a
        horizontal drag is confirmed.
        */
    });


// 국가_및_조합 전용 왼쪽 사이드바 이미지
     fan.addEventListener('pointermove', function(e) {
function updateLeftSidebarNationsImage() {
        var now;
     $('#clbi-left-nations-image').remove();
        var totalDx;
}
        var totalDy;
        var frameDx;
        var dt;
        var instantVelocity;


function setProfileActionLabel(selector, text) {
        if (!state.dragging) return;
    var target = $(selector);
    var label = target.find('.profile-action-label');


    if (label.length) {
        totalDx = e.clientX - state.dragStartX;
        label.text(text);
         totalDy = (e.clientY || 0) - state.dragStartY;
    } else {
         target.text(text);
    }
}


// 사이드바 업데이트
        if (!state.dragAxis && (Math.abs(totalDx) > 4 || Math.abs(totalDy) > 4)) {
function updateSidebar() {
            state.dragAxis = Math.abs(totalDx) >= Math.abs(totalDy) ? 'x' : 'y';
    if (!window.LANG) {
        setTimeout(updateSidebar, 100);
        return;
    }


    var currentLang = getCurrentLang();
            if (state.dragAxis === 'y') {
    var t = (window.LANG && window.LANG[currentLang]) ? window.LANG[currentLang] : window.LANG.ko;
                state.dragging = false;
                state.dragMoved = false;
                state.dragAxis = null;
                state.pointerCaptured = false;
                selector.classList.remove('is-dragging');
                return;
            }


    var newsTitle = t.news || '뉴스';
            if (fan.setPointerCapture && e.pointerId != null) {
    var changelogTitle = t.changelog || '체인지로그';
                try {
    var recentTitle = t.recentChanges || '최근 변경';
                    fan.setPointerCapture(e.pointerId);
    var languageTitle = t.language || '언어';
                    state.pointerCaptured = true;
                } catch (err) {
                    state.pointerCaptured = false;
                }
            }
        }
 
        if (state.dragAxis !== 'x') return;


    $('#clbi-title-left-language').text(languageTitle);
        now = performance.now();
    renderSidebarLanguageBox();
        frameDx = e.clientX - state.lastX;
        dt = Math.max(1, now - state.lastTime);


    $('#clbi-title-left-news').text(newsTitle);
        if (Math.abs(totalDx) > 3) state.dragMoved = true;
    $('#clbi-left-news-changelog-main').text(changelogTitle);
    $('#clbi-left-news-recent-main').text(recentTitle);


    $('#clbi-title-search a').text(t.search);
        instantVelocity = (frameDx * state.dragSensitivity) / dt;
    $('#clbi-search-input').attr('placeholder', t.search + '...');
        state.releaseVelocity = (state.releaseVelocity * 0.62) + (instantVelocity * 0.38);
    $('#clbi-title-recent a').text(recentTitle);
        state.lastX = e.clientX;
    $('#clbi-title-guide-label').text(t.guide);
        state.lastTime = now;
    $('#clbi-guide-link').text(t.getStarted);
    $('#clbi-title-links-label').text(t.links);


    setProfileActionLabel('#clbi-btn-contribution', t.contribution);
        requestSidebarLanguageRotation(state.dragStartRotation + totalDx * state.dragSensitivity);
    setProfileActionLabel('#clbi-btn-watchlist', t.watchlist);
        e.preventDefault();
    setProfileActionLabel('#clbi-btn-preferences', t.preferences);
        e.stopPropagation();
    setProfileActionLabel('#clbi-btn-logout', t.logout);
     });
     setProfileActionLabel('#clbi-btn-login', t.login);


     var pageName = normalizePageName(mw.config.get('wgPageName'));
     function finishDrag(e) {
    var specialPage = String(mw.config.get('wgCanonicalSpecialPageName') || '');
        var velocityAge;
        var throwVelocity;
        var wasHorizontal;


$('#clbi-left-news-changelog-main').text(changelogTitle);
        if (!state.dragging) return;
$('#clbi-left-news-recent-title').text('RECENT CHANGES');


    $('.clbi-user-btn').removeClass('clbi-user-btn-active');
        wasHorizontal = state.dragAxis === 'x';
        state.dragging = false;
        selector.classList.remove('is-dragging');


    if (
        if (fan.releasePointerCapture && state.pointerCaptured && e && e.pointerId != null) {
        specialPage === 'Contributions' ||
            try { fan.releasePointerCapture(e.pointerId); } catch (err) {}
        specialPage === '기여' ||
        }
        pageName.indexOf('특수:기여') === 0 ||
        pageName.indexOf('Special:Contributions') === 0
    ) {
        $('#clbi-btn-contribution').addClass('clbi-user-btn-active');
    }


    if (specialPage === 'Watchlist') {
        state.pointerCaptured = false;
         $('#clbi-btn-watchlist').addClass('clbi-user-btn-active');
         state.dragAxis = null;
    }


    if (
        if (!wasHorizontal && !state.dragMoved) {
         specialPage === '설정' ||
            return;
         pageName === '특수:설정' ||
         }
         pageName === 'Special:설정'
 
    ) {
         velocityAge = performance.now() - state.lastTime;
        $('#clbi-btn-preferences').addClass('clbi-user-btn-active');
         throwVelocity = velocityAge > 120 ? 0 : state.releaseVelocity;
    }


    $('.toggleBtn').each(function() {
        if (state.dragMoved) {
        var btn = $(this);
            state.suppressClickUntil = performance.now() + 180;
        }


         if (!$('#' + btn.data('target')).hasClass('folding-open')) {
         if (state.dragMoved && Math.abs(throwVelocity) >= state.minSpinVelocity) {
             btn.text(t.expand);
             startSidebarLanguageInertiaSpin(throwVelocity);
         } else {
         } else {
             btn.text(t.collapse);
             snapSidebarLanguageNearest();
         }
         }
    });


    updateLeftSidebarNationsImage();
        if (e) {
}
            e.preventDefault();
 
            e.stopPropagation();
function canShowContentTools() {
         }
    // 비로그인 사용자는 편집/역사/공유 버튼을 숨김
    if (!mw.config.get('wgUserName')) {
         return false;
     }
     }


     // MediaWiki가 현재 문서를 편집 가능하지 않다고 판단하면 숨김
     fan.addEventListener('pointerup', finishDrag);
     var isEditable = mw.config.get('wgIsProbablyEditable');
     fan.addEventListener('pointercancel', finishDrag);
     if (isEditable === false) {
     fan.addEventListener('lostpointercapture', function() {
         return false;
         if (!state.dragging) return;
    }


    var relevantEditable = mw.config.get('wgRelevantPageIsProbablyEditable');
        state.dragging = false;
    if (relevantEditable === false) {
        state.pointerCaptured = false;
         return false;
         state.dragAxis = null;
    }
        selector.classList.remove('is-dragging');


    return true;
        if (state.dragMoved && Math.abs(state.releaseVelocity) >= state.minSpinVelocity) {
}
            state.suppressClickUntil = performance.now() + 180;
            startSidebarLanguageInertiaSpin(state.releaseVelocity);
        } else {
            snapSidebarLanguageNearest();
        }
    });


function getCatlinkNodes(root) {
    apply.addEventListener('click', function(e) {
    var seen = [];
        e.preventDefault();
    var nodes = [];
        e.stopPropagation();
    var $root = root ? $(root) : $(document);


    $root.find('#catlinks, .catlinks').add($root.filter('#catlinks, .catlinks')).each(function () {
        snapSidebarLanguageNearest(function(meta) {
        if (seen.indexOf(this) !== -1) return;
            scheduleSidebarLanguageNavigation(meta);
        seen.push(this);
         });
         nodes.push(this);
     });
     });


     return nodes;
     selector.addEventListener('keydown', function(e) {
        if (e.key === 'ArrowLeft') {
            moveSidebarLanguageSelection(-1);
            e.preventDefault();
        }
 
        if (e.key === 'ArrowRight') {
            moveSidebarLanguageSelection(1);
            e.preventDefault();
        }
 
        if (e.key === 'Enter' || e.key === ' ') {
            apply.click();
            e.preventDefault();
        }
    });
}
}


function getCatlinksTarget(root) {
function renderSidebarLanguageBox() {
     var $root = root ? $(root) : $(document);
     bindSidebarLanguageSelector();
     var parserOutput = $root.find('.liberty-content-main .mw-parser-output').first();
     setSidebarLanguageSelection(getCurrentLang());
    var main = $root.find('.liberty-content-main').first();


     if (!parserOutput.length && root && $(root).is('.liberty-content-main')) {
     if (!sidebarLanguageStatusLoaded) {
        parserOutput = $(root).find('.mw-parser-output').first();
        loadSidebarLanguageStatusRegistry(function() {
         main = $(root);
            setSidebarLanguageSelection(getCurrentLang());
         });
     }
     }
}


    if (!parserOutput.length && root && $(root).is('.mw-parser-output')) {
function loadRecentChangesList(targetSelector, limit) {
        parserOutput = $(root);
    var $target = $(targetSelector);
     }
 
     if (!$target.length) return;


     if (parserOutput.length) return parserOutput;
     var lang = getCurrentLang();
     if (main.length) return main;
    var t = (window.LANG && window.LANG[lang]) ? window.LANG[lang] : (window.LANG ? window.LANG.ko : null);
     var isNewsList = $target.closest('.clbi-left-news-box').length > 0;


     if (!root) {
     function escapeHtml(value) {
         parserOutput = $('.liberty-content-main .mw-parser-output').first();
         return String(value == null ? '' : value)
        main = $('.liberty-content-main').first();
            .replace(/&/g, '&amp;')
        if (parserOutput.length) return parserOutput;
            .replace(/</g, '&lt;')
        if (main.length) return main;
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
     }
     }


     return $();
     $target.html((t && t.loading) ? t.loading : '불러오는 중...');
}


var CLBI_CATLINKS_FETCH_TOKEN = 0;
     $.getJSON(
 
         '/api.php?action=query&list=recentchanges&rclimit=' + encodeURIComponent(limit || 5) + '&rcprop=title|timestamp|user&format=json&rcnamespace=0&rctype=edit|new',
function getCurrentPageTitleForCatlinks() {
         function(data) {
     return String(
            var items = data && data.query ? data.query.recentchanges : [];
         mw.config.get('wgPageName') ||
            var html = '';
         mw.config.get('wgRelevantPageName') ||
        ''
    ).trim();
}


function shouldFetchCatlinks() {
            if (!items || !items.length) {
    var pageName = getCurrentPageTitleForCatlinks();
                $target.html('표시할 변경 사항이 없습니다.');
    var specialPage = mw.config.get('wgCanonicalSpecialPageName');
                return;
            }


    if (!pageName) return false;
            $.each(items, function(i, item) {
    if (specialPage) return false;
                var label = timeAgo(item.timestamp);
                var title = item.title || '';
                var userName = item.user || 'Unknown';
                var pageHref = buildWikiPath(title);
                var avatarSrc = '/index.php?title=특수:Redirect/file/Pfp-' + encodeURIComponent(userName) + '.png';


    return true;
                if (isNewsList) {
}
                    html +=
                        '<a href="' + escapeHtml(pageHref) + '" class="news-recent-item">' +
                            '<img class="news-recent-avatar" src="' + escapeHtml(avatarSrc) + '" alt="" onerror="this.onerror=null;this.src=\'/index.php?title=특수:Redirect/file/Pfp-default.png\';">' +
                            '<div class="news-recent-main">' +
                                '<div class="news-recent-title-wrap">' +
                                    '<span class="news-recent-title">' + escapeHtml(title) + '</span>' +
                                '</div>' +
                                '<div class="news-recent-meta">' +
                                    '<span class="news-recent-user">@' + escapeHtml(userName) + '</span>' +
                                '</div>' +
                            '</div>' +
                            '<span class="news-recent-time">' + escapeHtml(label) + '</span>' +
                        '</a>';
                } else {
                    html +=
                        '<div class="clbi-recent-item">' +
                            '<div class="clbi-recent-title-wrap">' +
                                '<a href="' + escapeHtml(pageHref) + '" class="clbi-recent-title">' + escapeHtml(title) + '</a>' +
                            '</div>' +
                            '<span class="clbi-recent-time">' + escapeHtml(label) + '</span>' +
                        '</div>';
                }
            });


function clearCatlinksInlineHiding(cat) {
            if (isNewsList) {
    if (!cat || !cat.style) return;
                $target.html(
                    '<div class="news-recent-viewport">' +
                        '<div class="news-recent-stack">' + html + '</div>' +
                    '</div>'
                );


    cat.style.removeProperty('display');
                if (typeof ensureNewsBottomFinish === 'function') {
    cat.style.removeProperty('visibility');
                    ensureNewsBottomFinish();
    cat.style.removeProperty('height');
                }
    cat.style.removeProperty('max-height');
            } else {
    cat.style.removeProperty('overflow');
                $target.html(html);
            }
 
            if (isNewsList && typeof scheduleAdaptiveLeftRecentItems === 'function') {
                scheduleAdaptiveLeftRecentItems();
            }
 
            $target.find(isNewsList ? '.news-recent-item' : '.clbi-recent-item').each(function() {
                var wrap = $(this).find(isNewsList ? '.news-recent-title-wrap' : '.clbi-recent-title-wrap');
                var title = $(this).find(isNewsList ? '.news-recent-title' : '.clbi-recent-title');


    $(cat).find('.mw-normal-catlinks, #mw-normal-catlinks, .mw-hidden-catlinks, #mw-hidden-catlinks, .mw-hidden-cats-hidden, .mw-hidden-cats-user-shown').each(function () {
                if (!wrap.length || !title.length) return;
        if (!this.style) return;
        this.style.removeProperty('display');
        this.style.removeProperty('visibility');
        this.style.removeProperty('height');
        this.style.removeProperty('max-height');
        this.style.removeProperty('overflow');
    });
}


function exposeHiddenCatlinks(cat) {
                var wrapW = wrap.width();
    if (!cat) return;
                var titleW = title[0].scrollWidth;


    $(cat).find('.mw-hidden-catlinks, #mw-hidden-catlinks, .mw-hidden-cats-hidden, .mw-hidden-cats-user-shown').each(function () {
                if (titleW > wrapW + 20) {
        this.classList.remove('mw-hidden-cats-hidden');
                    var duration = titleW / 40;
        this.classList.add('mw-hidden-cats-user-shown');


        if (this.style) {
                    title.css({
            this.style.removeProperty('display');
                        animation: 'clbi-scroll ' + duration + 's linear infinite',
            this.style.removeProperty('visibility');
                        '--scroll-dist': '-' + (titleW - wrapW + 8) + 'px'
            this.style.removeProperty('height');
                    });
            this.style.removeProperty('max-height');
                }
             this.style.removeProperty('overflow');
             });
         }
         }
    ).fail(function() {
        var lang = getCurrentLang();
        var t = (window.LANG && window.LANG[lang]) ? window.LANG[lang] : (window.LANG ? window.LANG.ko : null);
        $target.html((t && t.loadFail) ? t.loadFail : '불러오기 실패');
     });
     });
}
}


function getCatlinkTextContent(cat) {
    var clone;
    var text;


     if (!cat) return '';
function ensureRecentViewport() {
     var list = document.getElementById('clbi-left-recent-list');
    var viewport;
    var stack;
    var children;


     clone = cat.cloneNode(true);
     if (!list) return null;
    $(clone).find('script, style').remove();


     text = String(clone.textContent || '')
     viewport = list.querySelector(':scope > .news-recent-viewport');
        .replace(/\s+/g, ' ')
    stack = viewport ? viewport.querySelector(':scope > .news-recent-stack') : null;
        .replace(/^(분류|숨은 분류|Category|Hidden categories)\s*:\s*/i, '')
        .replace(/^(분류|숨은 분류|Category|Hidden categories)\s*$/i, '')
        .trim();


     return text;
     if (viewport && stack) return viewport;
}


function hasRenderedCatlinkItems(cat) {
    children = Array.prototype.slice.call(list.children || []);
     var hasLink;
 
     var hasListText;
     viewport = document.createElement('div');
     viewport.className = 'news-recent-viewport';


     if (!cat) return false;
     stack = document.createElement('div');
    stack.className = 'news-recent-stack';


     hasLink = false;
     children.forEach(function (child) {
    $(cat).find('a').each(function () {
         if (child.classList && child.classList.contains('news-recent-viewport')) return;
         var text = String($(this).text() || '').trim();
         stack.appendChild(child);
        var href = String(this.getAttribute('href') || '').trim();
         if (text || href) hasLink = true;
     });
     });
    if (hasLink) return true;


     hasListText = false;
     viewport.appendChild(stack);
    $(cat).find('li').each(function () {
     list.appendChild(viewport);
        if (String($(this).text() || '').trim()) hasListText = true;
     });
    if (hasListText) return true;


     return !!getCatlinkTextContent(cat);
     return viewport;
}
}


function normalizeCategoryTitle(rawTitle) {
function ensureNewsBottomFinish() {
     var title = String(rawTitle == null ? '' : rawTitle).trim();
     var newsBox = document.querySelector('#clbi-left-sidebar .clbi-left-news-box');
    var content = newsBox ? newsBox.querySelector('.clbi-news-box') : null;
    var finish;


     if (!title) return '';
     if (!content) return null;


     title = title.replace(/_/g, ' ');
     finish = content.querySelector(':scope > .news-bottom-finish');


     if (/^(Category|분류):/i.test(title)) {
     if (!finish) {
         return title;
        finish = document.createElement('div');
        finish.className = 'news-bottom-finish';
        finish.setAttribute('aria-hidden', 'true');
         content.appendChild(finish);
     }
     }


     return '분류:' + title;
     return finish;
}
}


function makeCategoryLinkTitle(rawTitle) {
function updateAdaptiveLeftRecentItems() {
     return String(rawTitle || '')
     /*
        .replace(/^Category:/i, '')
    134 기준: 좌측 사이드는 뉴스 확장형 flex 레이아웃이 높이를 담당한다.
        .replace(/^분류:/, '')
    이전 adaptive 코드는 항목을 숨기거나 mask/fade를 걸기 위한 것이었으므로
        .replace(/_/g, ' ')
    여기서는 잔여 상태만 정리하고 DOM 래퍼만 보장한다.
        .trim();
    */
}
    resetLeftRecentAdaptiveState();


function dedupeCatlinkCategories(categories) {
    if (typeof ensureRecentViewport === 'function') {
    var seen = {};
        ensureRecentViewport();
     var result = [];
     }


     (categories || []).forEach(function (item) {
     if (typeof ensureNewsBottomFinish === 'function') {
         var title = '';
         ensureNewsBottomFinish();
        var hidden = false;
    }


        if (typeof item === 'string') {
    if (typeof scheduleClbiContentBottomGap === 'function') {
            title = normalizeCategoryTitle(item);
        scheduleClbiContentBottomGap();
        } else if (item && typeof item === 'object') {
    }
            title = normalizeCategoryTitle(item.title || item.name || item.category || '');
}
            hidden = item.hidden !== undefined || item.isHidden === true;
        }


        if (!title) return;
function scheduleAdaptiveLeftRecentItems() {
        if (seen[title]) return;
    window.requestAnimationFrame(function () {
 
         updateAdaptiveLeftRecentItems();
         seen[title] = true;
        result.push({ title: title, hidden: hidden });
     });
     });


     return result;
     window.setTimeout(updateAdaptiveLeftRecentItems, 80);
    window.setTimeout(updateAdaptiveLeftRecentItems, 240);
}
}


function getConfigCatlinksCategories() {
    var normal = mw.config.get('wgCategories') || [];
    var hidden = mw.config.get('wgHiddenCategories') || [];
    var categories = [];


    if (!Array.isArray(normal)) normal = [];
    if (!Array.isArray(hidden)) hidden = [];


    normal.forEach(function (name) {
function updateClbiContentBottomGap(iteration) {
        categories.push({ title: normalizeCategoryTitle(name), hidden: false });
    var content = document.querySelector('.container-fluid.liberty-content');
     });
    var main = document.querySelector('.liberty-content-main');
    var bottomNav = document.getElementById('clbi-bottom-nav-wrap');
     var desiredGap = 8;
    var rootStyle;
    var scale = 1;
    var contentRect;
    var bottomTop;
    var targetHeight;
    var currentHeight;
    var visualGap;


     hidden.forEach(function (name) {
     iteration = iteration || 0;
        categories.push({ title: normalizeCategoryTitle(name), hidden: true });
    });


     return dedupeCatlinkCategories(categories);
     if (!content || !main || !bottomNav) return;
}


function markCatlinksReady(cat, pageTitle) {
    /*
     if (!cat) return;
    하단 간격은 scale 모드에서도 같은 기준으로 계산한다.
    transform:scale()이 걸리면 getBoundingClientRect()는 축소된 화면 좌표를 반환하므로,
     목표 간격 8px도 scale을 곱한 화면 좌표로 비교하고 다시 design px로 환산한다.


     cat.classList.add('catlinks');
     목표:
     cat.classList.add('clbi-catlinks-ready');
     .liberty-content-main.bottom === #clbi-bottom-nav-wrap.top - 8px
     cat.classList.remove('clbi-catlinks-empty');
    */
    cat.classList.remove('clbi-catlinks-pending');
     if (document.body && document.body.classList && document.body.classList.contains('clbi-shell-vertical-scale')) {
    cat.classList.remove('clbi-catlinks-loading');
        rootStyle = window.getComputedStyle(document.documentElement);
    cat.removeAttribute('data-clbi-catlinks-fetching');
        scale = parseFloat(rootStyle.getPropertyValue('--clbi-shell-scale')) || 1;
    cat.setAttribute('data-clbi-catlinks-page', pageTitle || getCurrentPageTitleForCatlinks());
        scale = Math.max(0.25, scale);
    clearCatlinksInlineHiding(cat);
     }
     exposeHiddenCatlinks(cat);
}


function markCatlinksEmpty(cat) {
    contentRect = content.getBoundingClientRect();
     if (!cat) return;
    bottomTop = bottomNav.getBoundingClientRect().top;
    visualGap = desiredGap * scale;
    targetHeight = Math.floor((bottomTop - contentRect.top - visualGap) / scale);
     targetHeight = Math.max(120, targetHeight);


     cat.classList.add('catlinks');
     currentHeight = Math.round(content.getBoundingClientRect().height / scale);
    cat.classList.add('clbi-catlinks-empty');
    cat.classList.remove('clbi-catlinks-ready');
    cat.classList.remove('clbi-catlinks-pending');
    cat.classList.remove('clbi-catlinks-loading');
    cat.removeAttribute('data-clbi-catlinks-fetching');
    cat.removeAttribute('data-clbi-catlinks-page');
}


function markCatlinksPending(cat, pageTitle) {
    content.style.setProperty('--clbi-content-extra', '0px');
     if (!cat) return;
     content.style.setProperty('height', targetHeight + 'px', 'important');
    content.style.setProperty('max-height', targetHeight + 'px', 'important');


     cat.classList.add('catlinks');
     if (Math.abs(currentHeight - targetHeight) >= 1 && iteration < 4) {
    cat.classList.remove('clbi-catlinks-ready');
        window.requestAnimationFrame(function () {
    cat.classList.remove('clbi-catlinks-empty');
            updateClbiContentBottomGap(iteration + 1);
    cat.classList.add('clbi-catlinks-pending');
        });
    cat.classList.add('clbi-catlinks-loading');
     }
    cat.setAttribute('data-clbi-catlinks-fetching', '1');
     cat.setAttribute('data-clbi-catlinks-page', pageTitle || getCurrentPageTitleForCatlinks());
}
}


function renderFetchedCatlinks(cat, categories, pageTitle) {
function scheduleClbiContentBottomGap() {
     var container;
    window.requestAnimationFrame(function () {
     var ul;
        updateClbiContentBottomGap(0);
     var normalized;
    });
    window.setTimeout(function () {
        updateClbiContentBottomGap(0);
    }, 40);
    window.setTimeout(function () {
        updateClbiContentBottomGap(0);
    }, 120);
    window.setTimeout(function () {
        updateClbiContentBottomGap(0);
     }, 280);
     window.setTimeout(function () {
        updateClbiContentBottomGap(0);
     }, 520);
}


    if (!cat) return false;


     normalized = dedupeCatlinkCategories(categories);
function updateLeftBillboardAdaptive() {
    /*
    134 기준: Ad는 이미지/CRT 비율을 유지하는 고정 슬롯이다.
    남는 세로 공간은 뉴스 박스가 흡수하므로, Ad에 하단 finish를 늘리거나
    title-only 상태로 접는 adaptive 보정은 사용하지 않는다.
    */
     resetLeftBillboardAdaptiveState();
}


     if (!normalized.length) {
function scheduleLeftBillboardAdaptive() {
        markCatlinksEmpty(cat);
     window.requestAnimationFrame(updateLeftBillboardAdaptive);
         return false;
    window.setTimeout(updateLeftBillboardAdaptive, 80);
    window.setTimeout(updateLeftBillboardAdaptive, 240);
}
 
function scheduleLeftSidebarVerticalFit() {
    if (typeof scheduleAdaptiveLeftRecentItems === 'function') {
         scheduleAdaptiveLeftRecentItems();
     }
     }


     cat.innerHTML = '';
     if (typeof scheduleLeftBillboardAdaptive === 'function') {
    cat.classList.add('catlinks');
        scheduleLeftBillboardAdaptive();
     cat.classList.add('clbi-catlinks-api-populated');
     }


     container = document.createElement('div');
     window.setTimeout(function () {
    container.className = 'mw-normal-catlinks';
        if (typeof scheduleAdaptiveLeftRecentItems === 'function') {
    container.appendChild(document.createTextNode('분류: '));
            scheduleAdaptiveLeftRecentItems();
        }


    ul = document.createElement('ul');
        if (typeof scheduleLeftBillboardAdaptive === 'function') {
            scheduleLeftBillboardAdaptive();
        }
    }, 120);
}


    normalized.forEach(function (item) {
        var title = String(item && item.title ? item.title : '').trim();
        var li;
        var a;


        if (!title) return;
// 시대 문서 전용 왼쪽 사이드바 이미지
function updateLeftSidebarNationsImage() {
    $('#clbi-left-nations-image').remove();
}


        li = document.createElement('li');
function setProfileActionLabel(selector, text) {
        a = document.createElement('a');
    var target = $(selector);
        a.href = mw.util.getUrl(title);
    var label = target.find('.profile-action-label');
        a.title = title;
        a.textContent = makeCategoryLinkTitle(title);


        if (item.hidden) {
    if (label.length) {
            li.className = 'clbi-hidden-category-item';
        label.text(text);
         }
    } else {
         target.text(text);
    }
}


        li.appendChild(a);
// 사이드바 업데이트
        ul.appendChild(li);
function updateSidebar() {
    });
     if (!window.LANG) {
 
         setTimeout(updateSidebar, 100);
     if (!ul.children.length) {
         return;
         markCatlinksEmpty(cat);
         return false;
     }
     }


     container.appendChild(ul);
     var currentLang = getCurrentLang();
     cat.appendChild(container);
    var t = (window.LANG && window.LANG[currentLang]) ? window.LANG[currentLang] : window.LANG.ko;
     markCatlinksReady(cat, pageTitle);
 
     return true;
    var newsTitle = t.news || '뉴스';
}
    var changelogTitle = t.changelog || '체인지로그';
    var recentTitle = t.recentChanges || '최근 변경';
    var languageTitle = t.language || '언어';
 
    $('#clbi-title-left-language').text(languageTitle);
    renderSidebarLanguageBox();
 
    $('#clbi-title-left-news').text(newsTitle);
    $('#clbi-left-news-changelog-main').text(changelogTitle);
    $('#clbi-left-news-recent-main').text(recentTitle);
 
     $('#clbi-title-search a').text(t.search);
     $('#clbi-search-input').attr('placeholder', t.search + '...');
    $('#clbi-title-recent a').text(recentTitle);
    $('#clbi-title-guide-label').text(t.guide);
    $('#clbi-guide-link').text(t.getStarted);
     $('#clbi-title-links-label').text(t.links);
 
    setProfileActionLabel('#clbi-btn-contribution', t.contribution);
    setProfileActionLabel('#clbi-btn-watchlist', t.watchlist);
    setProfileActionLabel('#clbi-btn-preferences', t.preferences);
    setProfileActionLabel('#clbi-btn-logout', t.logout);
    setProfileActionLabel('#clbi-btn-login', t.login);


function fetchCatlinksForPage(pageTitle, callback) {
    var pageName = normalizePageName(mw.config.get('wgPageName'));
     var api;
     var specialPage = String(mw.config.get('wgCanonicalSpecialPageName') || '');


    if (typeof pageTitle === 'function') {
$('#clbi-left-news-changelog-main').text(changelogTitle);
        callback = pageTitle;
$('#clbi-left-news-recent-title').text('RECENT CHANGES');
        pageTitle = getCurrentPageTitleForCatlinks();
    }


     pageTitle = String(pageTitle || '').trim();
     $('.clbi-user-btn').removeClass('clbi-user-btn-active');


     if (!pageTitle || !shouldFetchCatlinks()) {
     if (
         if (typeof callback === 'function') callback([], pageTitle);
        specialPage === 'Contributions' ||
        return;
        specialPage === '기여' ||
        pageName.indexOf('특수:기여') === 0 ||
         pageName.indexOf('Special:Contributions') === 0
    ) {
        $('#clbi-btn-contribution').addClass('clbi-user-btn-active');
     }
     }


     if (!mw.Api) {
     if (specialPage === 'Watchlist') {
         if (typeof callback === 'function') callback([], pageTitle);
         $('#clbi-btn-watchlist').addClass('clbi-user-btn-active');
        return;
     }
     }


     api = new mw.Api();
     if (
    api.get({
         specialPage === '설정' ||
         action: 'query',
         pageName === '특수:설정' ||
         prop: 'categories',
         pageName === 'Special:설정'
         titles: pageTitle,
    ) {
         cllimit: 'max',
         $('#clbi-btn-preferences').addClass('clbi-user-btn-active');
        clprop: 'hidden',
    }
        formatversion: 2
 
     }).done(function (data) {
     $('.toggleBtn').each(function() {
         var pages = data && data.query && data.query.pages ? data.query.pages : [];
         var btn = $(this);
        var page = pages && pages.length ? pages[0] : null;
        var categories = page && page.categories ? page.categories : [];


         if (typeof callback === 'function') callback(categories || [], pageTitle);
         if (!$('#' + btn.data('target')).hasClass('folding-open')) {
    }).fail(function () {
            btn.text(t.expand);
        if (typeof callback === 'function') callback([], pageTitle);
        } else {
            btn.text(t.collapse);
        }
     });
     });
    updateLeftSidebarNationsImage();
}
}


function finalizeEmptyCatlinks(cat) {
function canShowContentTools() {
     if (!cat) return;
     // 비로그인 사용자는 편집/역사/공유 버튼을 숨김
     if (!cat.isConnected) return;
     if (!mw.config.get('wgUserName')) {
        return false;
    }


     clearCatlinksInlineHiding(cat);
     // MediaWiki가 현재 문서를 편집 가능하지 않다고 판단하면 숨김
     exposeHiddenCatlinks(cat);
    var isEditable = mw.config.get('wgIsProbablyEditable');
     if (isEditable === false) {
        return false;
    }


     if (hasRenderedCatlinkItems(cat)) {
     var relevantEditable = mw.config.get('wgRelevantPageIsProbablyEditable');
        markCatlinksReady(cat, getCurrentPageTitleForCatlinks());
    if (relevantEditable === false) {
         return;
         return false;
     }
     }


     markCatlinksEmpty(cat);
     return true;
}
}


function fetchCatlinksIfNeeded(cat) {
function getCatlinkNodes(root) {
     var configCategories;
     var seen = [];
     var pageTitle;
     var nodes = [];
     var requestToken;
     var $root = root ? $(root) : $(document);


     if (!cat) return;
     $root.find('#catlinks, .catlinks').add($root.filter('#catlinks, .catlinks')).each(function () {
    if (!cat.isConnected) return;
        if (seen.indexOf(this) !== -1) return;
        seen.push(this);
        nodes.push(this);
    });


     pageTitle = getCurrentPageTitleForCatlinks();
     return nodes;
}


     clearCatlinksInlineHiding(cat);
function getCatlinksTarget(root) {
     exposeHiddenCatlinks(cat);
    var $root = root ? $(root) : $(document);
     var parserOutput = $root.find('.liberty-content-main .mw-parser-output').first();
     var main = $root.find('.liberty-content-main').first();


     if (hasRenderedCatlinkItems(cat)) {
     if (!parserOutput.length && root && $(root).is('.liberty-content-main')) {
         markCatlinksReady(cat, pageTitle);
         parserOutput = $(root).find('.mw-parser-output').first();
         return;
         main = $(root);
     }
     }


     configCategories = getConfigCatlinksCategories();
     if (!parserOutput.length && root && $(root).is('.mw-parser-output')) {
    if (configCategories.length) {
         parserOutput = $(root);
         renderFetchedCatlinks(cat, configCategories, pageTitle);
        return;
     }
     }


     if (!shouldFetchCatlinks()) {
    if (parserOutput.length) return parserOutput;
         finalizeEmptyCatlinks(cat);
    if (main.length) return main;
         return;
 
     if (!root) {
        parserOutput = $('.liberty-content-main .mw-parser-output').first();
        main = $('.liberty-content-main').first();
         if (parserOutput.length) return parserOutput;
         if (main.length) return main;
     }
     }


     if (cat.getAttribute('data-clbi-catlinks-fetching') === '1' && cat.getAttribute('data-clbi-catlinks-page') === pageTitle) return;
     return $();
}


    requestToken = ++CLBI_CATLINKS_FETCH_TOKEN;
var CLBI_CATLINKS_FETCH_TOKEN = 0;
    markCatlinksPending(cat, pageTitle);


    fetchCatlinksForPage(pageTitle, function (categories, requestedPage) {
function getCurrentPageTitleForCatlinks() {
        if (requestToken !== CLBI_CATLINKS_FETCH_TOKEN) return;
    return String(
         if (requestedPage !== getCurrentPageTitleForCatlinks()) return;
         mw.config.get('wgPageName') ||
         if (!cat || !cat.isConnected) return;
         mw.config.get('wgRelevantPageName') ||
         if (cat.getAttribute('data-clbi-catlinks-page') !== requestedPage) return;
         ''
    ).trim();
}


        if (!renderFetchedCatlinks(cat, categories, requestedPage)) {
function shouldFetchCatlinks() {
            finalizeEmptyCatlinks(cat);
    var pageName = getCurrentPageTitleForCatlinks();
        }
     var specialPage = mw.config.get('wgCanonicalSpecialPageName');
     });
}


function normalizeCatlinksPanel(cat) {
    if (!pageName) return false;
     if (!cat) return;
     if (specialPage) return false;


     cat.classList.add('catlinks');
     return true;
    clearCatlinksInlineHiding(cat);
}
    exposeHiddenCatlinks(cat);


     if (hasRenderedCatlinkItems(cat)) {
function clearCatlinksInlineHiding(cat) {
        markCatlinksReady(cat, getCurrentPageTitleForCatlinks());
     if (!cat || !cat.style) return;
        return;
 
     }
    cat.style.removeProperty('display');
    cat.style.removeProperty('visibility');
    cat.style.removeProperty('height');
    cat.style.removeProperty('max-height');
     cat.style.removeProperty('overflow');


     fetchCatlinksIfNeeded(cat);
     $(cat).find('.mw-normal-catlinks, #mw-normal-catlinks, .mw-hidden-catlinks, #mw-hidden-catlinks, .mw-hidden-cats-hidden, .mw-hidden-cats-user-shown').each(function () {
        if (!this.style) return;
        this.style.removeProperty('display');
        this.style.removeProperty('visibility');
        this.style.removeProperty('height');
        this.style.removeProperty('max-height');
        this.style.removeProperty('overflow');
    });
}
}


function createCatlinksPanel(target, className) {
function exposeHiddenCatlinks(cat) {
     var cat;
     if (!cat) return;


     if (!target || !target.length) return null;
     $(cat).find('.mw-hidden-catlinks, #mw-hidden-catlinks, .mw-hidden-cats-hidden, .mw-hidden-cats-user-shown').each(function () {
        this.classList.remove('mw-hidden-cats-hidden');
        this.classList.add('mw-hidden-cats-user-shown');


    cat = document.createElement('div');
        if (this.style) {
    cat.id = 'catlinks';
            this.style.removeProperty('display');
    cat.className = className || 'catlinks clbi-catlinks-created clbi-catlinks-pending';
            this.style.removeProperty('visibility');
    target.append(cat);
            this.style.removeProperty('height');
     return cat;
            this.style.removeProperty('max-height');
            this.style.removeProperty('overflow');
        }
     });
}
}


function prepareSpaCatlinksBeforeInsert(root) {
function getCatlinkTextContent(cat) {
     var nodes;
     var clone;
     var target;
     var text;
    var configCategories;
    var pageTitle;


     if (!root) return;
     if (!cat) return '';


     pageTitle = getCurrentPageTitleForCatlinks();
     clone = cat.cloneNode(true);
     configCategories = getConfigCatlinksCategories();
     $(clone).find('script, style').remove();
    nodes = getCatlinkNodes(root);


     nodes.forEach(function (node) {
     text = String(clone.textContent || '')
         node.classList.add('catlinks');
        .replace(/\s+/g, ' ')
         clearCatlinksInlineHiding(node);
         .replace(/^(분류|숨은 분류|Category|Hidden categories)\s*:\s*/i, '')
         exposeHiddenCatlinks(node);
         .replace(/^(분류|숨은 분류|Category|Hidden categories)\s*$/i, '')
         .trim();


        if (hasRenderedCatlinkItems(node)) {
    return text;
            markCatlinksReady(node, pageTitle);
}
        } else if (configCategories.length) {
            renderFetchedCatlinks(node, configCategories, pageTitle);
        } else {
            markCatlinksEmpty(node);
        }
    });


    if (nodes.length || !configCategories.length) return;
function hasRenderedCatlinkItems(cat) {
    var hasLink;
    var hasListText;


    target = getCatlinksTarget(root);
     if (!cat) return false;
     if (!target.length) target = $(root);


     renderFetchedCatlinks(createCatlinksPanel(target, 'catlinks catlinks-allhidden clbi-catlinks-created clbi-catlinks-pending'), configCategories, pageTitle);
     hasLink = false;
}
    $(cat).find('a').each(function () {
        var text = String($(this).text() || '').trim();
        var href = String(this.getAttribute('href') || '').trim();
        if (text || href) hasLink = true;
    });
    if (hasLink) return true;


function moveCatlinksToBottom() {
    hasListText = false;
    var main = $('.liberty-content-main').first();
    $(cat).find('li').each(function () {
     var target = getCatlinksTarget();
        if (String($(this).text() || '').trim()) hasListText = true;
     var catlinks = getCatlinkNodes();
     });
    var configCategories;
     if (hasListText) return true;
    var pageTitle;
    var requestToken;


     if (!main.length || !target.length) return;
     return !!getCatlinkTextContent(cat);
}


     pageTitle = getCurrentPageTitleForCatlinks();
function normalizeCategoryTitle(rawTitle) {
     var title = String(rawTitle == null ? '' : rawTitle).trim();


     catlinks.forEach(function (node) {
     if (!title) return '';
        var catNode = $(node);


        if (node.parentNode !== target[0]) {
    title = title.replace(/_/g, ' ');
            catNode.appendTo(target);
        }


        normalizeCatlinksPanel(node);
     if (/^(Category|분류):/i.test(title)) {
    });
         return title;
 
     if (catlinks.length) return;
 
    configCategories = getConfigCatlinksCategories();
    if (configCategories.length) {
        renderFetchedCatlinks(createCatlinksPanel(target, 'catlinks catlinks-allhidden clbi-catlinks-created clbi-catlinks-pending'), configCategories, pageTitle);
         return;
     }
     }


     if (!shouldFetchCatlinks()) return;
     return '분류:' + title;
}


     requestToken = ++CLBI_CATLINKS_FETCH_TOKEN;
function makeCategoryLinkTitle(rawTitle) {
     return String(rawTitle || '')
        .replace(/^Category:/i, '')
        .replace(/^분류:/, '')
        .replace(/_/g, ' ')
        .trim();
}
 
function dedupeCatlinkCategories(categories) {
    var seen = {};
    var result = [];
 
    (categories || []).forEach(function (item) {
        var title = '';
        var hidden = false;


    fetchCatlinksForPage(pageTitle, function (categories, requestedPage) {
        if (typeof item === 'string') {
         var cat;
            title = normalizeCategoryTitle(item);
        } else if (item && typeof item === 'object') {
            title = normalizeCategoryTitle(item.title || item.name || item.category || '');
            hidden = item.hidden !== undefined || item.isHidden === true;
         }


         if (requestToken !== CLBI_CATLINKS_FETCH_TOKEN) return;
         if (!title) return;
         if (requestedPage !== getCurrentPageTitleForCatlinks()) return;
         if (seen[title]) return;
        if (getCatlinkNodes().length) return;
        if (!categories || !categories.length) return;


         cat = createCatlinksPanel(target, 'catlinks catlinks-allhidden clbi-catlinks-created clbi-catlinks-pending');
         seen[title] = true;
         renderFetchedCatlinks(cat, categories, requestedPage);
         result.push({ title: title, hidden: hidden });
     });
     });
    return result;
}
}


// 대문 스타일
function getConfigCatlinksCategories() {
function initCategoryNavIfAvailable(root) {
     var normal = mw.config.get('wgCategories') || [];
     /*
     var hidden = mw.config.get('wgHiddenCategories') || [];
     CategoryNav.js는 대문 카테고리 네비를 SVG로 생성한다.
    var categories = [];


     Common.js가 SPA로 본문을 갈아끼운 뒤에는 MediaWiki 원래 페이지 로드와 달리
     if (!Array.isArray(normal)) normal = [];
     CategoryNav.js의 초기 DOMContentLoaded만으로는 새 mount를 다시 잡지 못할 수 있다.
     if (!Array.isArray(hidden)) hidden = [];
    CategoryNav.js 자체도 mw.hook('wikipage.content')를 듣지만, 로드 순서와 SPA 타이밍이
    엇갈릴 수 있으므로 Common.js 쪽에서도 존재 여부를 확인한 뒤 한 번 더 호출한다.


     이 함수는 CategoryNav.js가 아직 로드되지 않았으면 아무 것도 하지 않는다.
     normal.forEach(function (name) {
    */
         categories.push({ title: normalizeCategoryTitle(name), hidden: false });
    if (
     });
        window.CLBI &&
        window.CLBI.categoryNav &&
        typeof window.CLBI.categoryNav.init === 'function'
    ) {
         window.CLBI.categoryNav.init(root || document);
     }
}


function removeLegacyMainPageHero() {
    hidden.forEach(function (name) {
    /*
        categories.push({ title: normalizeCategoryTitle(name), hidden: true });
    기존 대문 전용 레거시 요소 정리
     });
    -----------------------------------------
    이전 대문 구조에서는 Common.js가 본문 바깥에 #clbi-main-logo를 직접 삽입하고,
     본문 안의 #clbi-main-crt-hero를 #clbi-main-crt-hero-wrap으로 감싸서
    .liberty-content-main 위쪽으로 재배치했다.


     새 대문은 본문 내부의 .main-portal이 로고, 알림, 카테고리 네비, 이미지 피드,
     return dedupeCatlinkCategories(categories);
    방명록, 상태 패널을 모두 담당한다. 따라서 Common.js가 별도 로고나 CRT 래퍼를
}
     삽입하면 새 로고/콘텐츠와 중복된다.
 
function markCatlinksReady(cat, pageTitle) {
     if (!cat) return;


     여기서는 JS가 만들던 바깥 로고와 CRT 래퍼를 제거하고, 예전 대문 원본이나
     cat.classList.add('catlinks');
     캐시된 렌더 결과에 남아 있을 수 있는 #clbi-main-crt-hero도 제거한다.
     cat.classList.add('clbi-catlinks-ready');
     */
     cat.classList.remove('clbi-catlinks-empty');
    $('#clbi-main-logo').remove();
    cat.classList.remove('clbi-catlinks-pending');
     $('#clbi-main-crt-hero-wrap').remove();
     cat.classList.remove('clbi-catlinks-loading');
     $('#clbi-main-crt-hero').remove();
    cat.removeAttribute('data-clbi-catlinks-fetching');
     cat.setAttribute('data-clbi-catlinks-page', pageTitle || getCurrentPageTitleForCatlinks());
    clearCatlinksInlineHiding(cat);
    exposeHiddenCatlinks(cat);
}
}


function markCatlinksEmpty(cat) {
    if (!cat) return;


function setNativePageTitleHiddenHard(hidden) {
    cat.classList.add('catlinks');
     var selectors = [
     cat.classList.add('clbi-catlinks-empty');
        '.liberty-content-header',
    cat.classList.remove('clbi-catlinks-ready');
        '.liberty-content-header .title',
    cat.classList.remove('clbi-catlinks-pending');
        '.liberty-content-header .title h1',
    cat.classList.remove('clbi-catlinks-loading');
        '.liberty-content-header h1',
    cat.removeAttribute('data-clbi-catlinks-fetching');
        '#firstHeading',
    cat.removeAttribute('data-clbi-catlinks-page');
        '.firstHeading',
}
        '.mw-first-heading',
 
        '.page-heading',
function markCatlinksPending(cat, pageTitle) {
        '.page-header',
     if (!cat) return;
        '.mw-page-title-main',
        '.mw-page-title-namespace',
        '.mw-page-title-separator'
     ];


     document.querySelectorAll(selectors.join(',')).forEach(function(node) {
     cat.classList.add('catlinks');
        if (!node || !node.style) return;
    cat.classList.remove('clbi-catlinks-ready');
    cat.classList.remove('clbi-catlinks-empty');
    cat.classList.add('clbi-catlinks-pending');
    cat.classList.add('clbi-catlinks-loading');
    cat.setAttribute('data-clbi-catlinks-fetching', '1');
    cat.setAttribute('data-clbi-catlinks-page', pageTitle || getCurrentPageTitleForCatlinks());
}


        if (hidden) {
function renderFetchedCatlinks(cat, categories, pageTitle) {
            node.setAttribute('data-clbi-title-hidden', 'true');
    var container;
            node.style.setProperty('display', 'none', 'important');
    var ul;
            node.style.setProperty('visibility', 'hidden', 'important');
     var normalized;
            node.style.setProperty('height', '0', 'important');
            node.style.setProperty('min-height', '0', 'important');
            node.style.setProperty('margin', '0', 'important');
            node.style.setProperty('padding', '0', 'important');
            node.style.setProperty('overflow', 'hidden', 'important');
        } else if (node.getAttribute('data-clbi-title-hidden') === 'true') {
            node.removeAttribute('data-clbi-title-hidden');
            node.style.removeProperty('display');
            node.style.removeProperty('visibility');
            node.style.removeProperty('height');
            node.style.removeProperty('min-height');
            node.style.removeProperty('margin');
            node.style.removeProperty('padding');
            node.style.removeProperty('overflow');
        }
     });
}


function applyDefaultPageTitleVisibility() {
    if (!cat) return false;
    var hideTitle = true;
    var isSystemAssetPage = false;


     if (window.CLBI_PAGE_SHELL && typeof window.CLBI_PAGE_SHELL.isSystemAssetPage === 'function') {
     normalized = dedupeCatlinkCategories(categories);
        isSystemAssetPage = window.CLBI_PAGE_SHELL.isSystemAssetPage();
    }


     if (isSystemAssetPage) {
     if (!normalized.length) {
         hideTitle = true;
         markCatlinksEmpty(cat);
    } else if (window.CLBI_PAGE_SHELL && typeof window.CLBI_PAGE_SHELL.isBackendOrSystemPage === 'function') {
         return false;
         hideTitle = !window.CLBI_PAGE_SHELL.isBackendOrSystemPage();
     }
     }


     $('body')
     cat.innerHTML = '';
        .toggleClass('page-title-hidden', hideTitle)
    cat.classList.add('catlinks');
        .toggleClass('page-title-visible', !hideTitle)
    cat.classList.add('clbi-catlinks-api-populated');
        .toggleClass('clbi-system-doc-page', isSystemAssetPage);


     $('.content-tools').css('display', 'none');
     container = document.createElement('div');
    container.className = 'mw-normal-catlinks';
    container.appendChild(document.createTextNode('분류: '));


     if (isSystemAssetPage && window.CLBI_PAGE_SHELL && typeof window.CLBI_PAGE_SHELL.renderSystemDocIndicator === 'function') {
     ul = document.createElement('ul');
        window.CLBI_PAGE_SHELL.renderSystemDocIndicator();
    } else if (!isSystemAssetPage && window.CLBI_PAGE_SHELL && typeof window.CLBI_PAGE_SHELL.removeSystemDocIndicator === 'function') {
        window.CLBI_PAGE_SHELL.removeSystemDocIndicator();
    }


     if (hideTitle) {
     normalized.forEach(function (item) {
        $('.liberty-content-header').css('display', 'none');
         var title = String(item && item.title ? item.title : '').trim();
        $('.mw-page-title-main, .mw-page-title-namespace, .mw-page-title-separator').addClass('clbi-hide');
         var li;
        $('#firstHeading, .firstHeading, .mw-first-heading, .page-heading, .page-header').css('display', 'none');
         var a;
        setNativePageTitleHiddenHard(true);
    } else {
         $('.liberty-content-header').css('display', '');
        $('.mw-page-title-main, .mw-page-title-namespace, .mw-page-title-separator').removeClass('clbi-hide');
         $('#firstHeading, .firstHeading, .mw-first-heading, .page-heading, .page-header').css('display', '');
         setNativePageTitleHiddenHard(false);
    }
}


function applyMainPageStyle() {
        if (!title) return;
    var specialPage = mw.config.get('wgCanonicalSpecialPageName');
    if (specialPage === 'Preferences') return;


    var pageName = normalizePageName(mw.config.get('wgPageName'));
        li = document.createElement('li');
    var namespaceNumber = mw.config.get('wgNamespaceNumber');
        a = document.createElement('a');
    var isMainPage = (pageName === '대문');
        a.href = mw.util.getUrl(title);
    var isUserProfilePage = (namespaceNumber === 2);
        a.title = title;
    var isScreenDoc = ($('.screen-header').length > 0);
        a.textContent = makeCategoryLinkTitle(title);
    var hideTools = (isMainPage || isUserProfilePage || !canShowContentTools());


    $('body').toggleClass('user-profile-page', isUserProfilePage);
        if (item.hidden) {
    $('body').toggleClass('clbi-main-page', isMainPage);
            li.className = 'clbi-hidden-category-item';
        }


    // 모든 문서에서 분류 바를 본문 컨테이너 아래로 이동
        li.appendChild(a);
     moveCatlinksToBottom();
        ul.appendChild(li);
     });


     if (isMainPage) {
     if (!ul.children.length) {
        $('.liberty-content-header').css('display', 'none');
         markCatlinksEmpty(cat);
        $('.mw-page-title-main').addClass('clbi-hide');
         return false;
         setNativePageTitleHiddenHard(true);
    }
         $('.catlinks').css('display', 'none');
        $('.liberty-content-main').css('border-radius', '0');


        // 새 대문은 .main-portal 본문 구조가 로고/히어로를 담당한다.
    container.appendChild(ul);
        // Common.js의 구식 바깥 로고/CRT 재배치 루틴은 사용하지 않는다.
    cat.appendChild(container);
        removeLegacyMainPageHero();
    markCatlinksReady(cat, pageTitle);
        $('#clbi-tools-box').remove();
    return true;
}


        $('.content-tools').css('display', 'none');
function fetchCatlinksForPage(pageTitle, callback) {
    var api;


         initCategoryNavIfAvailable(document);
    if (typeof pageTitle === 'function') {
        callback = pageTitle;
         pageTitle = getCurrentPageTitleForCatlinks();
    }


     } else if (isUserProfilePage) {
     pageTitle = String(pageTitle || '').trim();
        $('.liberty-content-header').css('display', 'none');
        $('.mw-page-title-main, .mw-page-title-namespace, .mw-page-title-separator').addClass('clbi-hide');
        $('.catlinks').css('display', 'none');
        $('.liberty-content-main').css('border-radius', '0');


        $('#clbi-main-logo').remove();
    if (!pageTitle || !shouldFetchCatlinks()) {
         $('#clbi-main-crt-hero-wrap').remove();
         if (typeof callback === 'function') callback([], pageTitle);
         $('#clbi-main-crt-hero').remove();
         return;
        $('#clbi-tools-box').remove();
    }


         $('.content-tools').css('display', 'none');
    if (!mw.Api) {
         if (typeof callback === 'function') callback([], pageTitle);
        return;
    }


     } else if (isScreenDoc) {
     api = new mw.Api();
         $('.liberty-content-header').css('display', 'none');
    api.get({
         $('.mw-page-title-main').addClass('clbi-hide');
         action: 'query',
         $('.catlinks').css('display', '');
        prop: 'categories',
         $('.liberty-content-main').css('border-radius', '0');
        titles: pageTitle,
        cllimit: 'max',
         clprop: 'hidden',
        formatversion: 2
    }).done(function (data) {
        var pages = data && data.query && data.query.pages ? data.query.pages : [];
         var page = pages && pages.length ? pages[0] : null;
         var categories = page && page.categories ? page.categories : [];


         $('#clbi-main-logo').remove();
         if (typeof callback === 'function') callback(categories || [], pageTitle);
         $('#clbi-main-crt-hero-wrap').remove();
    }).fail(function () {
         if (typeof callback === 'function') callback([], pageTitle);
    });
}


        if ($('#clbi-tools-box').length === 0 && canShowContentTools()) {
function finalizeEmptyCatlinks(cat) {
            var $toolsBox = $('<div id="clbi-tools-box" class="clbi-left-box"></div>');
    if (!cat) return;
            var $toolsTitle = $('<div class="clbi-left-title">관리</div>');
    if (!cat.isConnected) return;
            var $toolsContent = $('<div class="clbi-left-content"></div>');


            $toolsContent.append($('.content-tools .btn-group').clone(true));
    clearCatlinksInlineHiding(cat);
            $toolsBox.append($toolsTitle).append($toolsContent);
    exposeHiddenCatlinks(cat);
            $('#clbi-left-sidebar').append($toolsBox);
        }


        $('.content-tools').css('display', 'none');
    if (hasRenderedCatlinkItems(cat)) {
        markCatlinksReady(cat, getCurrentPageTitleForCatlinks());
        return;
    }


     } else {
     markCatlinksEmpty(cat);
        $('.liberty-content-header').css('display', '');
}
        $('.mw-page-title-main, .mw-page-title-namespace, .mw-page-title-separator').removeClass('clbi-hide');
        $('.catlinks').css('display', '');
        $('.liberty-content-main').css('border-radius', '0');


        $('#clbi-main-logo').remove();
function fetchCatlinksIfNeeded(cat) {
        $('#clbi-main-crt-hero-wrap').remove();
    var configCategories;
        $('#clbi-tools-box').remove();
    var pageTitle;
     }
     var requestToken;


     if (!isUserProfilePage) {
     if (!cat) return;
        $('.profile-card').remove();
    if (!cat.isConnected) return;
        $('.user-profile-portal').removeClass('user-profile-portal');
    }


     $('.content-tools').css('display', 'none');
     pageTitle = getCurrentPageTitleForCatlinks();


     applyDefaultPageTitleVisibility();
     clearCatlinksInlineHiding(cat);
     updateSidebar();
     exposeHiddenCatlinks(cat);
}


// 본문 기본 목차 제거
    if (hasRenderedCatlinkItems(cat)) {
function removeNativeTocFromContent() {
        markCatlinksReady(cat, pageTitle);
    $('.liberty-content-main #toc, .liberty-content-main .toc').remove();
        return;
}
    }


// 왼쪽 목차: MediaWiki 문단 ID 가져오기
    configCategories = getConfigCatlinksCategories();
function getHeadingId(heading) {
     if (configCategories.length) {
     if (heading.id) {
        renderFetchedCatlinks(cat, configCategories, pageTitle);
         return heading.id;
         return;
     }
     }


     var headline = heading.querySelector('.mw-headline[id]');
     if (!shouldFetchCatlinks()) {
    if (headline && headline.id) {
        finalizeEmptyCatlinks(cat);
         return headline.id;
         return;
     }
     }


     return '';
     if (cat.getAttribute('data-clbi-catlinks-fetching') === '1' && cat.getAttribute('data-clbi-catlinks-page') === pageTitle) return;
}


// 왼쪽 목차: MediaWiki 문단 제목 텍스트 가져오기
     requestToken = ++CLBI_CATLINKS_FETCH_TOKEN;
function getHeadingText(heading) {
     markCatlinksPending(cat, pageTitle);
     var headline = heading.querySelector('.mw-headline');
     var source = headline || heading;
    var clone = source.cloneNode(true);


     $(clone).find('.mw-editsection, .mw-editsection-bracket, .mw-editsection-divider').remove();
     fetchCatlinksForPage(pageTitle, function (categories, requestedPage) {
        if (requestToken !== CLBI_CATLINKS_FETCH_TOKEN) return;
        if (requestedPage !== getCurrentPageTitleForCatlinks()) return;
        if (!cat || !cat.isConnected) return;
        if (cat.getAttribute('data-clbi-catlinks-page') !== requestedPage) return;


    return (clone.textContent || '')
        if (!renderFetchedCatlinks(cat, categories, requestedPage)) {
        .replace(/\s+/g, ' ')
            finalizeEmptyCatlinks(cat);
         .trim();
         }
    });
}
}


// 왼쪽 목차: 긴 제목에 자동 스크롤 적용
function normalizeCatlinksPanel(cat) {
function initTocTitleScroll(root) {
     if (!cat) return;
     var $items = root
        ? $(root).find('.toc-scroll-text')
        : $('#side-toc-box .toc-scroll-text');


     $items.each(function () {
     cat.classList.add('catlinks');
        var $text = $(this);
    clearCatlinksInlineHiding(cat);
        var $wrap = $text.closest('.toc-scroll-wrap');
    exposeHiddenCatlinks(cat);


         if (!$wrap.length) return;
    if (hasRenderedCatlinkItems(cat)) {
         markCatlinksReady(cat, getCurrentPageTitleForCatlinks());
        return;
    }


        var wrapW = Math.floor($wrap.width());
    fetchCatlinksIfNeeded(cat);
        var textW = Math.ceil(this.scrollWidth);
}


        // 왼쪽 목차: 레이아웃 계산이 끝나지 않았으면 이번 실행에서는 건드리지 않는다.
function createCatlinksPanel(target, className) {
        if (!wrapW || !textW) return;
    var cat;
 
    if (!target || !target.length) return null;


        if (textW <= wrapW + 12) {
    cat = document.createElement('div');
            // 왼쪽 목차: 칸을 넘지 않는 제목은 전체 텍스트를 그대로 보여준다.
    cat.id = 'catlinks';
            $wrap.removeClass('is-scrolling');
    cat.className = className || 'catlinks clbi-catlinks-created clbi-catlinks-pending';
    target.append(cat);
    return cat;
}


            if ($text.data('toc-scroll-enabled')) {
function prepareSpaCatlinksBeforeInsert(root) {
                $text.css({
    var nodes;
                    animation: '',
    var target;
                    'animation-delay': '',
    var configCategories;
                    '--scroll-dist': ''
    var pageTitle;
                });
                $text.removeData('toc-scroll-enabled');
                $text.removeData('toc-scroll-key');
            }


            return;
    if (!root) return;
        }


        var scrollDist = '-' + (textW - wrapW + 10) + 'px';
    pageTitle = getCurrentPageTitleForCatlinks();
        var duration = Math.max(7, textW / 38) * 1.25;
    configCategories = getConfigCatlinksCategories();
        var scrollKey = scrollDist + '|' + duration;
    nodes = getCatlinkNodes(root);


        // 왼쪽 목차: 긴 제목에는 오른쪽 페이드와 스크롤을 적용한다.
    nodes.forEach(function (node) {
         $wrap.addClass('is-scrolling');
         node.classList.add('catlinks');
        clearCatlinksInlineHiding(node);
        exposeHiddenCatlinks(node);


         // 왼쪽 목차: 같은 값으로 이미 적용된 애니메이션은 다시 초기화하지 않는다.
         if (hasRenderedCatlinkItems(node)) {
         if ($text.data('toc-scroll-key') === scrollKey) {
            markCatlinksReady(node, pageTitle);
             return;
         } else if (configCategories.length) {
            renderFetchedCatlinks(node, configCategories, pageTitle);
        } else {
             markCatlinksEmpty(node);
         }
         }
    });


        $text.data('toc-scroll-enabled', true);
    if (nodes.length || !configCategories.length) return;
        $text.data('toc-scroll-key', scrollKey);
 
    target = getCatlinksTarget(root);
    if (!target.length) target = $(root);


        $text.css({
    renderFetchedCatlinks(createCatlinksPanel(target, 'catlinks catlinks-allhidden clbi-catlinks-created clbi-catlinks-pending'), configCategories, pageTitle);
            // 왼쪽 목차: 페이지 진입 직후에는 잠시 읽을 시간을 준 뒤 흐르게 한다.
            animation: 'toc-scroll-blink-reset ' + duration + 's linear infinite',
            'animation-delay': '1s',
            '--scroll-dist': scrollDist
        });
    });
}
}


// 목차를 왼쪽 사이드바에 새로 생성
function moveCatlinksToBottom() {
function moveTocToLeftSidebar() {
     var main = $('.liberty-content-main').first();
     removeNativeTocFromContent();
    var target = getCatlinksTarget();
    $('#side-toc-box').remove();
     var catlinks = getCatlinkNodes();
     return;
    var configCategories;
    var pageTitle;
    var requestToken;


     // 왼쪽 목차: MediaWiki가 만든 원래 목차는 본문에서 제거한다.
     if (!main.length || !target.length) return;
    removeNativeTocFromContent();


     var leftSidebar = document.getElementById('clbi-left-sidebar');
     pageTitle = getCurrentPageTitleForCatlinks();
    if (!leftSidebar) return;


     var content =
     catlinks.forEach(function (node) {
        document.querySelector('.liberty-content-main .mw-parser-output') ||
         var catNode = $(node);
         document.querySelector('.liberty-content-main');


    if (!content) return;
        if (node.parentNode !== target[0]) {
            catNode.appendTo(target);
        }


    var headings = Array.prototype.slice.call(
         normalizeCatlinksPanel(node);
        content.querySelectorAll('h2, h3')
    ).filter(function (heading) {
        if (heading.closest('#toc, .toc, #side-toc-box')) return false;
 
        var id = getHeadingId(heading);
         var text = getHeadingText(heading);
 
        if (!id || !text) return false;
 
        return true;
     });
     });


     var tocKey = headings.map(function (heading) {
     if (catlinks.length) return;
        return getHeadingId(heading) + '|' + getHeadingText(heading);
    }).join('||');


     var existingBox = document.getElementById('side-toc-box');
     configCategories = getConfigCatlinksCategories();
 
     if (configCategories.length) {
     // 왼쪽 목차: 같은 문서에서 같은 목차를 이미 만들었다면 다시 지우고 만들지 않는다.
        renderFetchedCatlinks(createCatlinksPanel(target, 'catlinks catlinks-allhidden clbi-catlinks-created clbi-catlinks-pending'), configCategories, pageTitle);
    if (existingBox && existingBox.getAttribute('data-toc-key') === tocKey) {
        initTocTitleScroll(existingBox);
         return;
         return;
     }
     }


     if (existingBox) {
     if (!shouldFetchCatlinks()) return;
        existingBox.remove();
    }


     if (!headings.length) return;
     requestToken = ++CLBI_CATLINKS_FETCH_TOKEN;


     var tocBox = document.createElement('div');
     fetchCatlinksForPage(pageTitle, function (categories, requestedPage) {
    tocBox.className = 'clbi-left-box';
        var cat;
    tocBox.id = 'side-toc-box';
    tocBox.setAttribute('data-toc-key', tocKey);


    var title = document.createElement('div');
        if (requestToken !== CLBI_CATLINKS_FETCH_TOKEN) return;
    title.className = 'clbi-left-title';
        if (requestedPage !== getCurrentPageTitleForCatlinks()) return;
        if (getCatlinkNodes().length) return;
        if (!categories || !categories.length) return;


    // 왼쪽 목차: 박스 제목은 Lang.js의 현재 UI 언어를 따른다.
        cat = createCatlinksPanel(target, 'catlinks catlinks-allhidden clbi-catlinks-created clbi-catlinks-pending');
    var currentLang = getCurrentLang();
        renderFetchedCatlinks(cat, categories, requestedPage);
    var t = (window.LANG && window.LANG[currentLang]) ? window.LANG[currentLang] : window.LANG.ko;
     });
     var tocTitleText = (t && t.toc) ? t.toc : '목차';
}


     title.textContent = tocTitleText;
// 대문 스타일
function initCategoryNavIfAvailable(root) {
     /*
    CategoryNav.js는 대문 카테고리 네비를 SVG로 생성한다.


     var body = document.createElement('div');
     Common.js가 SPA로 본문을 갈아끼운 뒤에는 MediaWiki 원래 페이지 로드와 달리
     body.className = 'clbi-left-content toc-sidebar-content';
    CategoryNav.js의 초기 DOMContentLoaded만으로는 새 mount를 다시 잡지 못할 수 있다.
    CategoryNav.js 자체도 mw.hook('wikipage.content')를 듣지만, 로드 순서와 SPA 타이밍이
     엇갈릴 수 있으므로 Common.js 쪽에서도 존재 여부를 확인한 뒤 한 번 더 호출한다.


     var list = document.createElement('ul');
     이 함수는 CategoryNav.js가 아직 로드되지 않았으면 아무 것도 하지 않는다.
     list.className = 'generated-toc';
    */
    if (window.CategoryNav && typeof window.CategoryNav.init === 'function') {
        window.CategoryNav.init(root || document);
        return;
     }


     headings.forEach(function (heading) {
     if (
         var id = getHeadingId(heading);
         window.CLBI &&
         var text = getHeadingText(heading);
         window.CLBI.categoryNav &&
         var level = heading.tagName.toLowerCase() === 'h3' ? 3 : 2;
         typeof window.CLBI.categoryNav.init === 'function'
    ) {
        window.CLBI.categoryNav.init(root || document);
    }
}


        var item = document.createElement('li');
function removeLegacyMainPageHero() {
        item.className = 'toc-level-' + level;
    /*
    기존 대문 전용 레거시 요소 정리
    -----------------------------------------
    이전 대문 구조에서는 Common.js가 본문 바깥에 #clbi-main-logo를 직접 삽입하고,
    본문 안의 #clbi-main-crt-hero를 #clbi-main-crt-hero-wrap으로 감싸서
    .liberty-content-main 위쪽으로 재배치했다.


        var link = document.createElement('a');
    새 대문은 본문 내부의 .main-portal이 로고, 알림, 카테고리 네비, 이미지 피드,
        link.setAttribute('href', '#' + id);
    방명록, 상태 패널을 모두 담당한다. 따라서 Common.js가 별도 로고나 CRT 래퍼를
    삽입하면 새 로고/콘텐츠와 중복된다.


        // 왼쪽 목차: 긴 제목 스크롤을 위해 텍스트를 별도 span으로 감싼다.
    여기서는 JS가 만들던 바깥 로고와 CRT 래퍼를 제거하고, 예전 대문 원본이나
        var textWrap = document.createElement('span');
    캐시된 렌더 결과에 남아 있을 수 있는 #clbi-main-crt-hero도 제거한다.
        textWrap.className = 'toc-scroll-wrap';
    */
    $('#clbi-main-logo').remove();
    $('#clbi-main-crt-hero-wrap').remove();
    $('#clbi-main-crt-hero').remove();
}


        var textSpan = document.createElement('span');
        textSpan.className = 'toc-scroll-text';
        textSpan.textContent = text;


         textWrap.appendChild(textSpan);
function setNativePageTitleHiddenHard(hidden) {
         link.appendChild(textWrap);
    var selectors = [
        '.liberty-content-header',
        '.liberty-content-header .title',
         '.liberty-content-header .title h1',
        '.liberty-content-header h1',
        '#firstHeading',
        '.firstHeading',
        '.mw-first-heading',
        '.page-heading',
        '.page-header',
        '.mw-page-title-main',
        '.mw-page-title-namespace',
        '.mw-page-title-separator'
    ];
 
    document.querySelectorAll(selectors.join(',')).forEach(function(node) {
         if (!node || !node.style) return;


         item.appendChild(link);
         if (hidden) {
         list.appendChild(item);
            node.setAttribute('data-clbi-title-hidden', 'true');
            node.style.setProperty('display', 'none', 'important');
            node.style.setProperty('visibility', 'hidden', 'important');
            node.style.setProperty('height', '0', 'important');
            node.style.setProperty('min-height', '0', 'important');
            node.style.setProperty('margin', '0', 'important');
            node.style.setProperty('padding', '0', 'important');
            node.style.setProperty('overflow', 'hidden', 'important');
         } else if (node.getAttribute('data-clbi-title-hidden') === 'true') {
            node.removeAttribute('data-clbi-title-hidden');
            node.style.removeProperty('display');
            node.style.removeProperty('visibility');
            node.style.removeProperty('height');
            node.style.removeProperty('min-height');
            node.style.removeProperty('margin');
            node.style.removeProperty('padding');
            node.style.removeProperty('overflow');
        }
     });
     });
}


    body.appendChild(list);
function applyDefaultPageTitleVisibility() {
     tocBox.appendChild(title);
     var hideTitle = true;
     tocBox.appendChild(body);
     var isSystemAssetPage = false;
    leftSidebar.appendChild(tocBox);


     // 왼쪽 목차: DOM 배치가 끝난 뒤 긴 제목 스크롤 여부를 계산한다.
     if (window.CLBI_PAGE_SHELL && typeof window.CLBI_PAGE_SHELL.isSystemAssetPage === 'function') {
    requestAnimationFrame(function () {
         isSystemAssetPage = window.CLBI_PAGE_SHELL.isSystemAssetPage();
         initTocTitleScroll(tocBox);
    }


        setTimeout(function () {
    if (isSystemAssetPage) {
            initTocTitleScroll(tocBox);
        hideTitle = true;
         }, 120);
    } else if (window.CLBI_PAGE_SHELL && typeof window.CLBI_PAGE_SHELL.isBackendOrSystemPage === 'function') {
     });
         hideTitle = !window.CLBI_PAGE_SHELL.isBackendOrSystemPage();
}
     }


    $('body')
        .toggleClass('page-title-hidden', hideTitle)
        .toggleClass('page-title-visible', !hideTitle)
        .toggleClass('clbi-system-doc-page', isSystemAssetPage);


// 우측 광고판: 이미지/번역 캡션 목록
     $('.content-tools').css('display', 'none');
var RIGHT_BILLBOARD_ITEMS = [
 
     {
    if (isSystemAssetPage && window.CLBI_PAGE_SHELL && typeof window.CLBI_PAGE_SHELL.renderSystemDocIndicator === 'function') {
        file: 'Side-visual-001.png',
         window.CLBI_PAGE_SHELL.renderSystemDocIndicator();
        alt: 'PROOF TO THE WORLD / YOU ONCE PART OF IT',
     } else if (!isSystemAssetPage && window.CLBI_PAGE_SHELL && typeof window.CLBI_PAGE_SHELL.removeSystemDocIndicator === 'function') {
        duration: 3000,
         window.CLBI_PAGE_SHELL.removeSystemDocIndicator();
        caption: [
            '"당신이 한때 이 세계의',
            '',
            '일부였다는 것을 증명하십시오"'
        ]
    },
    {
         file: 'Side-visual-002.png',
        alt: 'APPLY NOW',
        duration: 1000,
        caption: [
            '"지금 지원하세요!"'
        ]
     },
    {
        file: 'Side-visual-003.png',
        alt: 'APPLY NOW',
        duration: 1000,
        caption: [
            '"지금 지원하세요!"'
        ]
    },
    {
         file: 'Side-visual-002.png',
        alt: 'APPLY NOW',
        duration: 1000,
        caption: [
            '"지금 지원하세요!"'
        ]
     }
     }
];


function getRightBillboardItem(index) {
    if (hideTitle) {
    var items = RIGHT_BILLBOARD_ITEMS;
        $('.liberty-content-header').css('display', 'none');
 
        $('.mw-page-title-main, .mw-page-title-namespace, .mw-page-title-separator').addClass('clbi-hide');
    if (!items || !items.length) {
        $('#firstHeading, .firstHeading, .mw-first-heading, .page-heading, .page-header').css('display', 'none');
         return {
         setNativePageTitleHiddenHard(true);
            file: 'Side-visual-001.png',
    } else {
            alt: '',
        $('.liberty-content-header').css('display', '');
            caption: []
        $('.mw-page-title-main, .mw-page-title-namespace, .mw-page-title-separator').removeClass('clbi-hide');
         };
        $('#firstHeading, .firstHeading, .mw-first-heading, .page-heading, .page-header').css('display', '');
         setNativePageTitleHiddenHard(false);
     }
     }
}


     var normalized = index % items.length;
function applyMainPageStyle() {
     if (normalized < 0) normalized += items.length;
     var specialPage = mw.config.get('wgCanonicalSpecialPageName');
 
     if (specialPage === 'Preferences') return;
    return items[normalized];
}


function getRightBillboardImageUrl(fileName) {
    var pageName = normalizePageName(mw.config.get('wgPageName'));
     return '/index.php?title=특수:Redirect/file/' + encodeURIComponent(fileName || 'Side-visual-001.png');
     var namespaceNumber = mw.config.get('wgNamespaceNumber');
}
    var isMainPage = (pageName === '대문');
    var isUserProfilePage = (namespaceNumber === 2);
    var isScreenDoc = ($('.screen-header').length > 0);
    var hideTools = (isMainPage || isUserProfilePage || !canShowContentTools());


function getRightBillboardCaptionHtml(item) {
    $('body').toggleClass('user-profile-page', isUserProfilePage);
    var lines = item && item.caption ? item.caption : [];
     $('body').toggleClass('clbi-main-page', isMainPage);
     var html = '';


     function escapeCaptionText(value) {
     // 모든 문서에서 분류 바를 본문 컨테이너 아래로 이동
        return String(value == null ? '' : value)
    moveCatlinksToBottom();
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/\"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }


     lines.forEach(function(line) {
     if (isMainPage) {
         var text = String(line == null ? '' : line);
         $('.liberty-content-header').css('display', 'none');
        var isGap = !text.trim();
         $('.mw-page-title-main').addClass('clbi-hide');
         var className = 'right-billboard-caption-line' + (isGap ? ' is-gap' : '');
         setNativePageTitleHiddenHard(true);
         html += '<span class="' + className + '">' + (isGap ? '&nbsp;' : escapeCaptionText(text)) + '</span>';
        $('.catlinks').css('display', 'none');
    });
        $('.liberty-content-main').css('border-radius', '0');


    return html;
        // 새 대문은 .main-portal 본문 구조가 로고/히어로를 담당한다.
}
        // Common.js의 구식 바깥 로고/CRT 재배치 루틴은 사용하지 않는다.
        removeLegacyMainPageHero();
        $('#clbi-tools-box').remove();


function setRightBillboardItem(index) {
        $('.content-tools').css('display', 'none');
    var box = document.querySelector('.right-billboard-box');
    if (!box) return;


    var item = getRightBillboardItem(index);
        initCategoryNavIfAvailable(document);
    var src = getRightBillboardImageUrl(item.file);
    var images = box.querySelectorAll('.right-billboard-image');
    var caption = box.querySelector('#right-billboard-caption');
    var emptySub = box.querySelector('.right-billboard-empty-sub');


     box.setAttribute('data-billboard-index', String(index));
     } else if (isUserProfilePage) {
    box.classList.remove('is-empty');
        $('.liberty-content-header').css('display', 'none');
        $('.mw-page-title-main, .mw-page-title-namespace, .mw-page-title-separator').addClass('clbi-hide');
        $('.catlinks').css('display', 'none');
        $('.liberty-content-main').css('border-radius', '0');


    Array.prototype.forEach.call(images, function(img) {
        $('#clbi-main-logo').remove();
         img.style.display = '';
         $('#clbi-main-crt-hero-wrap').remove();
        img.setAttribute('src', src);
         $('#clbi-main-crt-hero').remove();
         img.setAttribute('alt', img.classList.contains('right-billboard-image-base') ? (item.alt || '') : '');
        $('#clbi-tools-box').remove();
    });


    if (caption) {
        $('.content-tools').css('display', 'none');
        caption.innerHTML = getRightBillboardCaptionHtml(item);
    }


     if (emptySub) {
     } else if (isScreenDoc) {
         emptySub.textContent = item.file || 'Side-visual-001.png';
         $('.liberty-content-header').css('display', 'none');
    }
        $('.mw-page-title-main').addClass('clbi-hide');
}
        $('.catlinks').css('display', '');
        $('.liberty-content-main').css('border-radius', '0');


function getRightBillboardItemDuration(item) {
        $('#clbi-main-logo').remove();
    var duration = item && item.duration ? parseInt(item.duration, 10) : 3000;
        $('#clbi-main-crt-hero-wrap').remove();


    if (Number.isNaN(duration) || duration < 500) {
        if ($('#clbi-tools-box').length === 0 && canShowContentTools()) {
        duration = 3000;
            var $toolsBox = $('<div id="clbi-tools-box" class="clbi-left-box"></div>');
    }
            var $toolsTitle = $('<div class="clbi-left-title">관리</div>');
            var $toolsContent = $('<div class="clbi-left-content"></div>');


    return duration;
            $toolsContent.append($('.content-tools .btn-group').clone(true));
}
            $toolsBox.append($toolsTitle).append($toolsContent);
            $('#clbi-left-sidebar').append($toolsBox);
        }


function initRightBillboardCarousel() {
        $('.content-tools').css('display', 'none');
    var box = document.querySelector('.right-billboard-box');
    if (!box || box.getAttribute('data-billboard-ready') === '1') return;


     box.setAttribute('data-billboard-ready', '1');
     } else {
    box.setAttribute('data-billboard-index', '0');
        $('.liberty-content-header').css('display', '');
        $('.mw-page-title-main, .mw-page-title-namespace, .mw-page-title-separator').removeClass('clbi-hide');
        $('.catlinks').css('display', '');
        $('.liberty-content-main').css('border-radius', '0');


    setRightBillboardItem(0);
        $('#clbi-main-logo').remove();
        $('#clbi-main-crt-hero-wrap').remove();
        $('#clbi-tools-box').remove();
    }


     if (!RIGHT_BILLBOARD_ITEMS || RIGHT_BILLBOARD_ITEMS.length <= 1) return;
     if (!isUserProfilePage) {
        $('.profile-card').remove();
        $('.user-profile-portal').removeClass('user-profile-portal');
    }


     function scheduleNext() {
     $('.content-tools').css('display', 'none');
        var current = parseInt(box.getAttribute('data-billboard-index') || '0', 10);
        if (Number.isNaN(current)) current = 0;


        var currentItem = getRightBillboardItem(current);
    applyDefaultPageTitleVisibility();
        var delay = getRightBillboardItemDuration(currentItem);
    updateSidebar();
}


        window.setTimeout(function() {
// 본문 기본 목차 제거
            if (!document.body.contains(box)) return;
function removeNativeTocFromContent() {
    $('.liberty-content-main #toc, .liberty-content-main .toc').remove();
}


            if (!document.hidden) {
// 왼쪽 목차: MediaWiki 문단 ID 가져오기
                setRightBillboardItem(current + 1);
function getHeadingId(heading) {
            }
    if (heading.id) {
        return heading.id;
    }


            scheduleNext();
    var headline = heading.querySelector('.mw-headline[id]');
         }, delay);
    if (headline && headline.id) {
         return headline.id;
     }
     }


     scheduleNext();
     return '';
}
}


// 왼쪽 목차: MediaWiki 문단 제목 텍스트 가져오기
function getHeadingText(heading) {
    var headline = heading.querySelector('.mw-headline');
    var source = headline || heading;
    var clone = source.cloneNode(true);


function escapeRightBillboardAttr(value) {
     $(clone).find('.mw-editsection, .mw-editsection-bracket, .mw-editsection-divider').remove();
     return String(value == null ? '' : value)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}


function buildRightBillboardBox() {
     return (clone.textContent || '')
    var billboardInitial = getRightBillboardItem(0);
        .replace(/\s+/g, ' ')
    var billboardSrc = getRightBillboardImageUrl(billboardInitial.file);
        .trim();
 
     return '' +
        '<div class="clbi-left-box right-billboard-box left-billboard-box left-ad-box" data-billboard-index="0">' +
            '<div class="clbi-left-title right-billboard-title left-ad-title left-ad-title-iconless">' +
                '<span id="clbi-title-left-ad" class="left-ad-title-label">Looking for a job?</span>' +
            '</div>' +
            '<div class="clbi-left-content left-ad-content-shell">' +
                '<div class="right-billboard-body">' +
                    '<div class="right-billboard-recess">' +
                        '<div class="right-billboard-screen">' +
                            '<img id="right-billboard-image" class="right-billboard-image right-billboard-image-base" src="' + escapeRightBillboardAttr(billboardSrc) + '" alt="' + escapeRightBillboardAttr(billboardInitial.alt || '') + '" onload="var b=this.closest(\'.right-billboard-box\'); if(b){b.classList.remove(\'is-empty\');}" onerror="this.onerror=null;this.style.display=\'none\';var b=this.closest(\'.right-billboard-box\'); if(b){b.classList.add(\'is-empty\');}">' +
                            '<img class="right-billboard-image right-billboard-image-bloom" src="' + escapeRightBillboardAttr(billboardSrc) + '" alt="" aria-hidden="true" onerror="this.onerror=null;this.style.display=\'none\';">' +
                            '<img class="right-billboard-image right-billboard-slice right-billboard-slice-a" src="' + escapeRightBillboardAttr(billboardSrc) + '" alt="" aria-hidden="true" onerror="this.onerror=null;this.style.display=\'none\';">' +
                            '<img class="right-billboard-image right-billboard-slice right-billboard-slice-b" src="' + escapeRightBillboardAttr(billboardSrc) + '" alt="" aria-hidden="true" onerror="this.onerror=null;this.style.display=\'none\';">' +
                            '<img class="right-billboard-image right-billboard-slice right-billboard-slice-c" src="' + escapeRightBillboardAttr(billboardSrc) + '" alt="" aria-hidden="true" onerror="this.onerror=null;this.style.display=\'none\';">' +
                            '<div class="right-billboard-glitch" aria-hidden="true"></div>' +
                            '<div class="right-billboard-tear" aria-hidden="true"></div>' +
                            '<div class="right-billboard-empty" aria-hidden="true">' +
                                '<span class="right-billboard-empty-main">SIGNAL EMPTY</span>' +
                                '<span class="right-billboard-empty-sub">' + escapeRightBillboardAttr(billboardInitial.file || 'Side-visual-001.png') + '</span>' +
                            '</div>' +
                        '</div>' +
                    '</div>' +
                    '<div id="right-billboard-caption" class="right-billboard-caption" aria-hidden="true">' + getRightBillboardCaptionHtml(billboardInitial) + '</div>' +
                    '<div class="right-billboard-bottom-finish left-ad-bottom-finish" aria-hidden="true"></div>' +
                '</div>' +
            '</div>' +
        '</div>';
}
}


// 왼쪽 목차: 긴 제목에 자동 스크롤 적용
function initTocTitleScroll(root) {
    var $items = root
        ? $(root).find('.toc-scroll-text')
        : $('#side-toc-box .toc-scroll-text');


var GREAT_WALL_DATA_TITLE = '프로젝트:The_Great_Wall/Data.json';
    $items.each(function () {
var GREAT_WALL_LIST_LIMIT = 0;
        var $text = $(this);
var greatWallState = {
        var $wrap = $text.closest('.toc-scroll-wrap');
    data: { entries: {} },
    loaded: false,
    loading: false,
    saving: false,
    selectedOwnEntry: false,
    statusText: ''
};


function normalizeGreatWallData(data) {
        if (!$wrap.length) return;
    var normalized = { entries: {} };
    var entries = data && data.entries && typeof data.entries === 'object' ? data.entries : {};


    Object.keys(entries).forEach(function(key) {
         var wrapW = Math.floor($wrap.width());
        var item = entries[key];
         var textW = Math.ceil(this.scrollWidth);
         var user = item && item.user ? String(item.user) : String(key || '');
        var text = item && item.text ? String(item.text) : '';
         var timestamp = item && item.timestamp ? String(item.timestamp) : '';


         if (!user || !text) return;
        // 왼쪽 목차: 레이아웃 계산이 끝나지 않았으면 이번 실행에서는 건드리지 않는다.
         if (!wrapW || !textW) return;


         normalized.entries[user] = {
         if (textW <= wrapW + 12) {
             user: user,
             // 왼쪽 목차: 칸을 넘지 않는 제목은 전체 텍스트를 그대로 보여준다.
            text: text.slice(0, 140),
             $wrap.removeClass('is-scrolling');
             timestamp: timestamp || new Date(0).toISOString()
        };
    });


    return normalized;
            if ($text.data('toc-scroll-enabled')) {
}
                $text.css({
                    animation: '',
                    'animation-delay': '',
                    '--scroll-dist': ''
                });
                $text.removeData('toc-scroll-enabled');
                $text.removeData('toc-scroll-key');
            }


function parseGreatWallData(text) {
            return;
    var parsed;
        }


    try {
         var scrollDist = '-' + (textW - wrapW + 10) + 'px';
         parsed = text ? JSON.parse(text) : {};
         var duration = Math.max(7, textW / 38) * 1.25;
    } catch (err) {
         var scrollKey = scrollDist + '|' + duration;
         console.error('The Great Wall data parse failed:', err);
         parsed = {};
    }


    return normalizeGreatWallData(parsed);
        // 왼쪽 목차: 긴 제목에는 오른쪽 페이드와 스크롤을 적용한다.
}
        $wrap.addClass('is-scrolling');


function stringifyGreatWallData(data) {
        // 왼쪽 목차: 같은 값으로 이미 적용된 애니메이션은 다시 초기화하지 않는다.
    return JSON.stringify(normalizeGreatWallData(data), null, 2) + '\n';
        if ($text.data('toc-scroll-key') === scrollKey) {
}
            return;
        }


function getGreatWallRevisionText(page) {
        $text.data('toc-scroll-enabled', true);
     var rev;
        $text.data('toc-scroll-key', scrollKey);
     var slot;
 
        $text.css({
            // 왼쪽 목차: 페이지 진입 직후에는 잠시 읽을 시간을 준 뒤 흐르게 한다.
            animation: 'toc-scroll-blink-reset ' + duration + 's linear infinite',
            'animation-delay': '1s',
            '--scroll-dist': scrollDist
        });
    });
}
 
// 목차를 왼쪽 사이드바에 새로 생성
function moveTocToLeftSidebar() {
     removeNativeTocFromContent();
    $('#side-toc-box').remove();
     return;


     if (!page || !page.revisions || !page.revisions.length) return '';
     // 왼쪽 목차: MediaWiki가 만든 원래 목차는 본문에서 제거한다.
    removeNativeTocFromContent();


     rev = page.revisions[0];
     var leftSidebar = document.getElementById('clbi-left-sidebar');
    if (!leftSidebar) return;


     if (rev.slots && rev.slots.main) {
     var content =
         slot = rev.slots.main;
         document.querySelector('.liberty-content-main .mw-parser-output') ||
        return slot.content || slot['*'] || '';
        document.querySelector('.liberty-content-main');
    }


     return rev.content || rev['*'] || '';
     if (!content) return;
}


function fetchGreatWallData() {
    var headings = Array.prototype.slice.call(
    var api = new mw.Api();
        content.querySelectorAll('h2, h3')
    ).filter(function (heading) {
        if (heading.closest('#toc, .toc, #side-toc-box')) return false;


    return api.get({
         var id = getHeadingId(heading);
         action: 'query',
         var text = getHeadingText(heading);
        prop: 'revisions',
        titles: GREAT_WALL_DATA_TITLE,
        rvprop: 'content|timestamp',
        rvslots: 'main',
        formatversion: 2
    }).then(function(data) {
        var pages = data && data.query && data.query.pages ? data.query.pages : [];
         var page = pages[0] || null;


         if (!page || page.missing) {
         if (!id || !text) return false;
            return { entries: {} };
        }


         return parseGreatWallData(getGreatWallRevisionText(page));
         return true;
    }, function(err) {
        console.error('The Great Wall load failed:', err);
        return { entries: {} };
     });
     });
}
function getGreatWallEntries(data) {
    var entries = data && data.entries && typeof data.entries === 'object' ? data.entries : {};


     return Object.keys(entries).map(function(key) {
     var tocKey = headings.map(function (heading) {
         return entries[key];
         return getHeadingId(heading) + '|' + getHeadingText(heading);
    }).filter(function(item) {
     }).join('||');
        return item && item.user && item.text;
     }).sort(function(a, b) {
        return String(a.timestamp || '').localeCompare(String(b.timestamp || ''));
    });
}


function getGreatWallMessageTime(timestamp) {
     var existingBox = document.getElementById('side-toc-box');
     var date = timestamp ? new Date(timestamp) : null;
    var month;
    var day;
    var hour;
    var minute;


     if (!date || isNaN(date.getTime())) return '—';
    // 왼쪽 목차: 같은 문서에서 같은 목차를 이미 만들었다면 다시 지우고 만들지 않는다.
     if (existingBox && existingBox.getAttribute('data-toc-key') === tocKey) {
        initTocTitleScroll(existingBox);
        return;
    }


     month = String(date.getMonth() + 1).padStart(2, '0');
     if (existingBox) {
    day = String(date.getDate()).padStart(2, '0');
        existingBox.remove();
     hour = String(date.getHours()).padStart(2, '0');
     }
    minute = String(date.getMinutes()).padStart(2, '0');


     return month + '.' + day + ' ' + hour + ':' + minute;
     if (!headings.length) return;
}


function getGreatWallAvatarSrc(user) {
    var tocBox = document.createElement('div');
     return '/index.php?title=특수:Redirect/file/Pfp-' + encodeURIComponent(String(user || '')) + '.png';
     tocBox.className = 'clbi-left-box';
}
    tocBox.id = 'side-toc-box';
    tocBox.setAttribute('data-toc-key', tocKey);


function buildGreatWallEntryHtml(item, currentUser, selectedOwnEntry) {
     var title = document.createElement('div');
     var isOwn = currentUser && item.user === currentUser;
     title.className = 'clbi-left-title';
    var tag = isOwn ? 'button' : 'div';
     var attrs = isOwn ? ' type="button" data-great-wall-own-entry="1" aria-label="Edit your wall message"' : '';
    var className = 'great-wall-entry' + (isOwn ? ' is-own' : '') + (isOwn && selectedOwnEntry ? ' is-selected' : '');
    var avatarSrc = getGreatWallAvatarSrc(item.user);
    var messageTime = getGreatWallMessageTime(item.timestamp);
    var isoTime = item.timestamp || '';


     return '' +
     // 왼쪽 목차: 박스 제목은 Lang.js의 현재 UI 언어를 따른다.
        '<' + tag + attrs + ' class="' + className + '">' +
    var currentLang = getCurrentLang();
            '<img class="great-wall-avatar" src="' + escapeClbiHtml(avatarSrc) + '" alt="" onerror="this.onerror=null;this.src=&quot;/index.php?title=특수:Redirect/file/Pfp-default.png&quot;;">' +
    var t = (window.LANG && window.LANG[currentLang]) ? window.LANG[currentLang] : window.LANG.ko;
            '<div class="great-wall-bubble">' +
    var tocTitleText = (t && t.toc) ? t.toc : '목차';
                '<div class="great-wall-entry-head">' +
                    '<span class="great-wall-user">@' + escapeClbiHtml(item.user) + '</span>' +
                    '<span class="great-wall-time" title="' + escapeClbiHtml(isoTime) + '">' + escapeClbiHtml(messageTime) + '</span>' +
                '</div>' +
                '<div class="great-wall-text">' + escapeClbiHtml(item.text) + '</div>' +
            '</div>' +
        '</' + tag + '>';
}


function renderGreatWallBox() {
     title.textContent = tocTitleText;
     var box = document.getElementById('great-wall-sidebar');
 
    var list = document.getElementById('great-wall-list');
     var body = document.createElement('div');
     var input = document.getElementById('great-wall-input');
     body.className = 'clbi-left-content toc-sidebar-content';
     var submit = document.getElementById('great-wall-submit');
    var deleteButton = document.getElementById('great-wall-delete');
    var status = document.getElementById('great-wall-status');
    var currentUser = mw.config.get('wgUserName') || '';
    var entries = getGreatWallEntries(greatWallState.data);
    var ownEntry = currentUser && greatWallState.data.entries ? greatWallState.data.entries[currentUser] : null;
    var visibleEntries = [];
    var seen = {};


     if (!box || !list) return;
     var list = document.createElement('ul');
    list.className = 'generated-toc';


     box.classList.toggle('is-guest', !currentUser);
     headings.forEach(function (heading) {
    box.classList.toggle('is-loading', !!greatWallState.loading);
        var id = getHeadingId(heading);
    box.classList.toggle('is-saving', !!greatWallState.saving);
        var text = getHeadingText(heading);
    box.classList.toggle('has-own-entry', !!ownEntry);
        var level = heading.tagName.toLowerCase() === 'h3' ? 3 : 2;
    box.classList.toggle('is-own-selected', !!greatWallState.selectedOwnEntry);


    entries.forEach(function(item) {
         var item = document.createElement('li');
         if (seen[item.user]) return;
         item.className = 'toc-level-' + level;
        visibleEntries.push(item);
         seen[item.user] = true;
    });


    if (greatWallState.loading && !greatWallState.loaded) {
         var link = document.createElement('a');
         list.innerHTML = '<div class="great-wall-empty">SYNCING WALL</div>';
         link.setAttribute('href', '#' + id);
    } else if (!visibleEntries.length) {
         list.innerHTML = '<div class="great-wall-empty">NO MARKS</div>';
    } else {
        list.innerHTML = visibleEntries.map(function(item) {
            return buildGreatWallEntryHtml(item, currentUser, greatWallState.selectedOwnEntry);
        }).join('');
    }


    if (list && list.scrollHeight > list.clientHeight) {
        // 왼쪽 목차: 긴 제목 스크롤을 위해 텍스트를 별도 span으로 감싼다.
         list.scrollTop = list.scrollHeight;
        var textWrap = document.createElement('span');
    }
         textWrap.className = 'toc-scroll-wrap';


    if (status) {
         var textSpan = document.createElement('span');
         status.textContent = greatWallState.statusText || (currentUser ? (ownEntry ? 'SELECT YOUR MARK TO UPDATE' : 'LEAVE ONE MARK') : 'ACCOUNT REQUIRED');
        textSpan.className = 'toc-scroll-text';
    }
        textSpan.textContent = text;


    if (!input || !submit) return;
        textWrap.appendChild(textSpan);
        link.appendChild(textWrap);


    input.disabled = false;
        item.appendChild(link);
    input.readOnly = false;
        list.appendChild(item);
     input.removeAttribute('aria-readonly');
     });


     if (!currentUser) {
     body.appendChild(list);
        input.disabled = true;
    tocBox.appendChild(title);
        input.readOnly = false;
    tocBox.appendChild(body);
        input.value = '';
    leftSidebar.appendChild(tocBox);
        input.placeholder = 'Login required';
        submit.textContent = 'LOGIN';
        submit.disabled = false;
        if (deleteButton) {
            deleteButton.disabled = true;
            deleteButton.title = 'Login required';
        }
        return;
    }


     if (greatWallState.saving || greatWallState.loading) {
     // 왼쪽 목차: DOM 배치가 끝난 뒤 긴 제목 스크롤 여부를 계산한다.
         input.disabled = true;
    requestAnimationFrame(function () {
        input.readOnly = false;
         initTocTitleScroll(tocBox);
        submit.disabled = true;
        submit.textContent = greatWallState.saving ? 'SAVE' : 'SYNC';
        if (deleteButton) {
            deleteButton.disabled = true;
            deleteButton.title = greatWallState.saving ? 'Saving' : 'Syncing';
        }
        return;
    }


    if (deleteButton) {
        setTimeout(function () {
        deleteButton.disabled = !ownEntry;
            initTocTitleScroll(tocBox);
        deleteButton.title = ownEntry ? 'Delete your mark' : 'No mark to delete';
         }, 120);
    }
     });
 
    if (ownEntry && !greatWallState.selectedOwnEntry) {
        input.disabled = false;
         input.readOnly = true;
        input.setAttribute('aria-readonly', 'true');
        input.value = '';
        input.placeholder = 'Select your existing mark';
        submit.disabled = true;
        submit.textContent = 'UPDATE';
        return;
     }
 
    input.disabled = false;
    input.readOnly = false;
    input.removeAttribute('aria-readonly');
    input.placeholder = ownEntry ? 'Update your mark' : 'Leave your mark';
    if (ownEntry && greatWallState.selectedOwnEntry && !input.value) {
        input.value = ownEntry.text || '';
    }
    submit.disabled = false;
    submit.textContent = ownEntry ? 'UPDATE' : 'POST';
}
}


function saveGreatWallEntry() {
    var input = document.getElementById('great-wall-input');
    var currentUser = mw.config.get('wgUserName') || '';
    var ownEntry = currentUser && greatWallState.data.entries ? greatWallState.data.entries[currentUser] : null;
    var text = input ? String(input.value || '').trim() : '';
    var api;


     if (!currentUser) {
// 우측 광고판: 이미지/번역 캡션 목록
         window.location.href = '/index.php?title=특수:로그인&returnto=' + encodeURIComponent(mw.config.get('wgPageName') || '대문');
var RIGHT_BILLBOARD_ITEMS = [
         return;
     {
     }
         file: 'Side-visual-001.png',
 
        alt: 'PROOF TO THE WORLD / YOU ONCE PART OF IT',
     if (ownEntry && !greatWallState.selectedOwnEntry) {
        duration: 3000,
         greatWallState.statusText = 'SELECT YOUR MARK FIRST';
        caption: [
         renderGreatWallBox();
            '"당신이 한때 이 세계의',
         return;
            '',
            '일부였다는 것을 증명하십시오"'
        ]
    },
    {
        file: 'Side-visual-002.png',
        alt: 'APPLY NOW',
        duration: 1000,
        caption: [
            '"지금 지원하세요!"'
        ]
    },
    {
        file: 'Side-visual-003.png',
        alt: 'APPLY NOW',
        duration: 1000,
        caption: [
            '"지금 지원하세요!"'
         ]
     },
     {
         file: 'Side-visual-002.png',
        alt: 'APPLY NOW',
        duration: 1000,
         caption: [
            '"지금 지원하세요!"'
         ]
     }
     }
];


    if (!text) {
function getRightBillboardItem(index) {
        greatWallState.statusText = 'EMPTY MARK';
    var items = RIGHT_BILLBOARD_ITEMS;
        renderGreatWallBox();
        return;
    }


     if (text.length > 140) {
     if (!items || !items.length) {
         text = text.slice(0, 140);
         return {
            file: 'Side-visual-001.png',
            alt: '',
            caption: []
        };
     }
     }


     greatWallState.saving = true;
     var normalized = index % items.length;
    greatWallState.statusText = 'SAVING';
     if (normalized < 0) normalized += items.length;
     renderGreatWallBox();


     fetchGreatWallData().then(function(data) {
     return items[normalized];
        data = normalizeGreatWallData(data);
}
        data.entries[currentUser] = {
            user: currentUser,
            text: text,
            timestamp: new Date().toISOString()
        };


        api = new mw.Api();
function getRightBillboardImageUrl(fileName) {
        return api.postWithToken('csrf', {
    return '/index.php?title=특수:Redirect/file/' + encodeURIComponent(fileName || 'Side-visual-001.png');
            action: 'edit',
            title: GREAT_WALL_DATA_TITLE,
            text: stringifyGreatWallData(data),
            summary: 'Update The Great Wall entry',
            format: 'json'
        }).then(function() {
            greatWallState.data = data;
            greatWallState.loaded = true;
            greatWallState.selectedOwnEntry = false;
            greatWallState.statusText = 'MARK UPDATED';
            if (input) input.value = '';
        });
    }).then(function() {
        greatWallState.saving = false;
        renderGreatWallBox();
    }, function(err) {
        console.error('The Great Wall save failed:', err);
        greatWallState.saving = false;
        greatWallState.statusText = 'SAVE FAILED';
        renderGreatWallBox();
    });
}
}


function getRightBillboardCaptionHtml(item) {
    var lines = item && item.caption ? item.caption : [];
    var html = '';


function deleteGreatWallEntry() {
    function escapeCaptionText(value) {
    var input = document.getElementById('great-wall-input');
        return String(value == null ? '' : value)
    var currentUser = mw.config.get('wgUserName') || '';
            .replace(/&/g, '&amp;')
    var ownEntry = currentUser && greatWallState.data.entries ? greatWallState.data.entries[currentUser] : null;
            .replace(/</g, '&lt;')
    var api;
            .replace(/>/g, '&gt;')
 
            .replace(/\"/g, '&quot;')
    if (!currentUser) {
            .replace(/'/g, '&#039;');
        window.location.href = '/index.php?title=특수:로그인&returnto=' + encodeURIComponent(mw.config.get('wgPageName') || '대문');
        return;
     }
     }


     if (!ownEntry) {
     lines.forEach(function(line) {
         greatWallState.statusText = 'NO MARK TO DELETE';
         var text = String(line == null ? '' : line);
         renderGreatWallBox();
        var isGap = !text.trim();
         return;
         var className = 'right-billboard-caption-line' + (isGap ? ' is-gap' : '');
     }
         html += '<span class="' + className + '">' + (isGap ? '&nbsp;' : escapeCaptionText(text)) + '</span>';
     });


     greatWallState.saving = true;
     return html;
    greatWallState.statusText = 'DELETING';
}
    renderGreatWallBox();


    fetchGreatWallData().then(function(data) {
function setRightBillboardItem(index) {
        data = normalizeGreatWallData(data);
    var box = document.querySelector('.right-billboard-box');
        if (data.entries && data.entries[currentUser]) {
    if (!box) return;
            delete data.entries[currentUser];
        }


        api = new mw.Api();
    var item = getRightBillboardItem(index);
        return api.postWithToken('csrf', {
    var src = getRightBillboardImageUrl(item.file);
            action: 'edit',
    var images = box.querySelectorAll('.right-billboard-image');
            title: GREAT_WALL_DATA_TITLE,
    var caption = box.querySelector('#right-billboard-caption');
            text: stringifyGreatWallData(data),
    var emptySub = box.querySelector('.right-billboard-empty-sub');
            summary: 'Delete The Great Wall entry',
 
            format: 'json'
    box.setAttribute('data-billboard-index', String(index));
        }).then(function() {
    box.classList.remove('is-empty');
            greatWallState.data = data;
 
            greatWallState.loaded = true;
     Array.prototype.forEach.call(images, function(img) {
            greatWallState.selectedOwnEntry = false;
         img.style.display = '';
            greatWallState.statusText = 'MARK DELETED';
         img.setAttribute('src', src);
            if (input) input.value = '';
         img.setAttribute('alt', img.classList.contains('right-billboard-image-base') ? (item.alt || '') : '');
        });
     }).then(function() {
         greatWallState.saving = false;
         renderGreatWallBox();
    }, function(err) {
         console.error('The Great Wall delete failed:', err);
        greatWallState.saving = false;
        greatWallState.statusText = 'DELETE FAILED';
        renderGreatWallBox();
     });
     });
}


function initGreatWallBoxWhenReady() {
     if (caption) {
     if (!document.getElementById('great-wall-sidebar')) return;
         caption.innerHTML = getRightBillboardCaptionHtml(item);
 
    if (mw.Api) {
         initGreatWallBox();
        return;
     }
     }


     if (mw.loader && mw.loader.using) {
     if (emptySub) {
         mw.loader.using(['mediawiki.api']).then(function() {
         emptySub.textContent = item.file || 'Side-visual-001.png';
            initGreatWallBox();
        });
     }
     }
}
}


function initGreatWallBox() {
function getRightBillboardItemDuration(item) {
     var box = document.getElementById('great-wall-sidebar');
     var duration = item && item.duration ? parseInt(item.duration, 10) : 3000;
    var input = document.getElementById('great-wall-input');
    var submit = document.getElementById('great-wall-submit');
    var deleteButton = document.getElementById('great-wall-delete');


     if (!box || box.getAttribute('data-great-wall-ready') === '1') return;
     if (Number.isNaN(duration) || duration < 500) {
 
         duration = 3000;
    if (!mw.Api) {
         initGreatWallBoxWhenReady();
        return;
     }
     }


     box.setAttribute('data-great-wall-ready', '1');
     return duration;
}


    box.addEventListener('click', function(e) {
function initRightBillboardCarousel() {
        var ownButton = e.target.closest ? e.target.closest('[data-great-wall-own-entry="1"]') : null;
    var box = document.querySelector('.right-billboard-box');
        var currentUser = mw.config.get('wgUserName') || '';
    if (!box || box.getAttribute('data-billboard-ready') === '1') return;
        var ownEntry = currentUser && greatWallState.data.entries ? greatWallState.data.entries[currentUser] : null;


        if (!ownButton || !ownEntry) return;
    box.setAttribute('data-billboard-ready', '1');
    box.setAttribute('data-billboard-index', '0');


        greatWallState.selectedOwnEntry = true;
    setRightBillboardItem(0);
        greatWallState.statusText = 'YOUR MARK SELECTED';
        renderGreatWallBox();


        if (input) {
    if (!RIGHT_BILLBOARD_ITEMS || RIGHT_BILLBOARD_ITEMS.length <= 1) return;
            input.focus();
            input.setSelectionRange(input.value.length, input.value.length);
        }
    });


     document.addEventListener('click', function(e) {
     function scheduleNext() {
         var target = e.target;
         var current = parseInt(box.getAttribute('data-billboard-index') || '0', 10);
         var keepSelection;
         if (Number.isNaN(current)) current = 0;


         if (!greatWallState.selectedOwnEntry || !target || !target.closest) return;
         var currentItem = getRightBillboardItem(current);
        var delay = getRightBillboardItemDuration(currentItem);


         keepSelection = target.closest('[data-great-wall-own-entry="1"], .great-wall-editor, .great-wall-compose-sector');
         window.setTimeout(function() {
            if (!document.body.contains(box)) return;


        if (keepSelection) return;
             if (!document.hidden) {
 
                 setRightBillboardItem(current + 1);
        greatWallState.selectedOwnEntry = false;
        greatWallState.statusText = '';
        if (input) input.value = '';
        renderGreatWallBox();
    });
 
    if (submit) {
        submit.addEventListener('click', function(e) {
            e.preventDefault();
             if (!mw.config.get('wgUserName')) {
                 window.location.href = '/index.php?title=특수:로그인&returnto=' + encodeURIComponent(mw.config.get('wgPageName') || '대문');
                return;
             }
             }
            saveGreatWallEntry();
        });
    }


    if (deleteButton) {
             scheduleNext();
        deleteButton.addEventListener('click', function(e) {
         }, delay);
             e.preventDefault();
            deleteGreatWallEntry();
         });
     }
     }


     if (input) {
     scheduleNext();
        input.addEventListener('keydown', function(e) {
}
            if (e.key === 'Enter') {
                e.preventDefault();
                saveGreatWallEntry();
            }
        });


        input.addEventListener('input', function() {
            if (input.value.length > 140) {
                input.value = input.value.slice(0, 140);
            }
        });
    }


     greatWallState.loading = true;
function escapeRightBillboardAttr(value) {
    greatWallState.statusText = 'SYNCING WALL';
     return String(value == null ? '' : value)
    renderGreatWallBox();
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}


    fetchGreatWallData().then(function(data) {
function buildRightBillboardBox() {
        greatWallState.data = normalizeGreatWallData(data);
    var billboardInitial = getRightBillboardItem(0);
        greatWallState.loaded = true;
    var billboardSrc = getRightBillboardImageUrl(billboardInitial.file);
        greatWallState.loading = false;
        greatWallState.selectedOwnEntry = false;
        greatWallState.statusText = '';
        renderGreatWallBox();
    });
}


function buildGreatWallBox() {
     return '' +
     return '' +
         '<div id="great-wall-sidebar" class="clbi-right-box great-wall-sidebar">' +
         '<div class="clbi-left-box right-billboard-box left-billboard-box left-ad-box" data-billboard-index="0">' +
             '<div class="clbi-right-title great-wall-title">' +
             '<div class="clbi-left-title right-billboard-title left-ad-title left-ad-title-iconless">' +
                 '<span id="clbi-title-great-wall">The Great Wall</span>' +
                 '<span id="clbi-title-left-ad" class="left-ad-title-label">Looking for a job?</span>' +
             '</div>' +
             '</div>' +
             '<div class="clbi-right-content great-wall-content">' +
             '<div class="clbi-left-content left-ad-content-shell">' +
                 '<div id="great-wall-list" class="great-wall-list"><div class="great-wall-empty">SYNCING WALL</div></div>' +
                 '<div class="right-billboard-body">' +
            '</div>' +
                    '<div class="right-billboard-recess">' +
            '<div class="great-wall-compose-sector" aria-label="The Great Wall editor">' +
                        '<div class="right-billboard-screen">' +
                '<div class="great-wall-editor">' +
                            '<img id="right-billboard-image" class="right-billboard-image right-billboard-image-base" src="' + escapeRightBillboardAttr(billboardSrc) + '" alt="' + escapeRightBillboardAttr(billboardInitial.alt || '') + '" onload="var b=this.closest(\'.right-billboard-box\'); if(b){b.classList.remove(\'is-empty\');}" onerror="this.onerror=null;this.style.display=\'none\';var b=this.closest(\'.right-billboard-box\'); if(b){b.classList.add(\'is-empty\');}">' +
                    '<input id="great-wall-input" class="great-wall-input" type="text" maxlength="140" autocomplete="off" placeholder="Leave your mark">' +
                            '<img class="right-billboard-image right-billboard-image-bloom" src="' + escapeRightBillboardAttr(billboardSrc) + '" alt="" aria-hidden="true" onerror="this.onerror=null;this.style.display=\'none\';">' +
                     '<button id="great-wall-submit" class="great-wall-submit" type="button">POST</button>' +
                            '<img class="right-billboard-image right-billboard-slice right-billboard-slice-a" src="' + escapeRightBillboardAttr(billboardSrc) + '" alt="" aria-hidden="true" onerror="this.onerror=null;this.style.display=\'none\';">' +
                     '<button id="great-wall-delete" class="great-wall-delete" type="button" disabled>DEL</button>' +
                            '<img class="right-billboard-image right-billboard-slice right-billboard-slice-b" src="' + escapeRightBillboardAttr(billboardSrc) + '" alt="" aria-hidden="true" onerror="this.onerror=null;this.style.display=\'none\';">' +
                            '<img class="right-billboard-image right-billboard-slice right-billboard-slice-c" src="' + escapeRightBillboardAttr(billboardSrc) + '" alt="" aria-hidden="true" onerror="this.onerror=null;this.style.display=\'none\';">' +
                            '<div class="right-billboard-glitch" aria-hidden="true"></div>' +
                            '<div class="right-billboard-tear" aria-hidden="true"></div>' +
                            '<div class="right-billboard-empty" aria-hidden="true">' +
                                '<span class="right-billboard-empty-main">SIGNAL EMPTY</span>' +
                                '<span class="right-billboard-empty-sub">' + escapeRightBillboardAttr(billboardInitial.file || 'Side-visual-001.png') + '</span>' +
                            '</div>' +
                        '</div>' +
                     '</div>' +
                    '<div id="right-billboard-caption" class="right-billboard-caption" aria-hidden="true">' + getRightBillboardCaptionHtml(billboardInitial) + '</div>' +
                     '<div class="right-billboard-bottom-finish left-ad-bottom-finish" aria-hidden="true"></div>' +
                 '</div>' +
                 '</div>' +
                '<div id="great-wall-status" class="great-wall-status">SYNCING WALL</div>' +
             '</div>' +
             '</div>' +
         '</div>';
         '</div>';
}
}


function removeMainPortalGuestbookPreview() {
    var portal = document.querySelector('.main-portal');
    var guestbook = portal ? portal.querySelector('.guestbook-device') : null;
    var sideScreen;
    var grid;


     if (!portal || !guestbook) return;
var GREAT_WALL_DATA_TITLE = '프로젝트:The_Great_Wall/Data.json';
 
var GREAT_WALL_LIST_LIMIT = 0;
     sideScreen = guestbook.closest ? guestbook.closest('.side-screen') : null;
var greatWallState = {
     grid = sideScreen && sideScreen.closest ? sideScreen.closest('.console-grid') : null;
     data: { entries: {} },
    loaded: false,
    loading: false,
    saving: false,
     selectedOwnEntry: false,
     statusText: ''
};


    if (guestbook.parentNode) {
function normalizeGreatWallData(data) {
        guestbook.parentNode.removeChild(guestbook);
    var normalized = { entries: {} };
     }
     var entries = data && data.entries && typeof data.entries === 'object' ? data.entries : {};


     if (sideScreen && !(sideScreen.textContent || '').trim() && !sideScreen.querySelector('img,svg,video,canvas,form,input,button,a')) {
     Object.keys(entries).forEach(function(key) {
         if (sideScreen.parentNode) {
        var item = entries[key];
            sideScreen.parentNode.removeChild(sideScreen);
        var user = item && item.user ? String(item.user) : String(key || '');
        }
        var text = item && item.text ? String(item.text) : '';
         var timestamp = item && item.timestamp ? String(item.timestamp) : '';


         if (grid) {
         if (!user || !text) return;
            grid.style.gridTemplateColumns = 'minmax(0,1fr)';
        }
    }


    portal.classList.add('is-great-wall-relocated');
        normalized.entries[user] = {
}
            user: user,
            text: text.slice(0, 140),
            timestamp: timestamp || new Date(0).toISOString()
        };
    });


function buildSiteInformationBox() {
     return normalized;
     return '' +
        '<div class="clbi-right-box site-info-sidebar">' +
            '<div class="clbi-right-title site-info-title">' +
                '<span>정보</span>' +
            '</div>' +
            '<div class="clbi-right-content site-info-content">' +
                '<div class="policy-list">' +
                    '<div class="policy-row"><a href="/index.php/개인정보처리방침" class="site-info-policy-button"><span class="site-info-policy-title">개인정보처리방침</span><span class="site-info-policy-arrow" aria-hidden="true">›</span></a></div>' +
                    '<div class="policy-row"><a href="/index.php/면책_조항" class="site-info-policy-button"><span class="site-info-policy-title">면책 조항</span><span class="site-info-policy-arrow" aria-hidden="true">›</span></a></div>' +
                    '<div class="policy-row"><a href="/index.php/라이선스" class="site-info-policy-button"><span class="site-info-policy-title">라이선스</span><span class="site-info-policy-arrow" aria-hidden="true">›</span></a></div>' +
                    '<div class="policy-row"><a href="/index.php/크레딧" class="site-info-policy-button"><span class="site-info-policy-title">크레딧</span><span class="site-info-policy-arrow" aria-hidden="true">›</span></a></div>' +
                '</div>' +
                '<div class="social-strip">' +
                    '<span class="social-icon"><a href="https://discord.gg/ctaeJ9d3Q5" target="_blank" rel="noopener noreferrer">DC</a></span>' +
                    '<span class="social-icon"><a href="https://www.youtube.com/@nxdsxn" target="_blank" rel="noopener noreferrer">YT</a></span>' +
                    '<span class="social-icon"><a href="https://x.com/nxd_sxn" target="_blank" rel="noopener noreferrer">X</a></span>' +
                    '<span class="social-icon"><a href="/index.php/프로젝트:소개">WIP:</a></span>' +
                '</div>' +
            '</div>' +
        '</div>';
}
}


function parseGreatWallData(text) {
    var parsed;


// 초기화 함수
    try {
function initSidebars() {
        parsed = text ? JSON.parse(text) : {};
     var header = $('.liberty-content-header');
    } catch (err) {
     var content = $('.liberty-content');
        console.error('The Great Wall data parse failed:', err);
        parsed = {};
    }
 
    return normalizeGreatWallData(parsed);
}
 
function stringifyGreatWallData(data) {
     return JSON.stringify(normalizeGreatWallData(data), null, 2) + '\n';
}
 
function getGreatWallRevisionText(page) {
    var rev;
     var slot;
 
    if (!page || !page.revisions || !page.revisions.length) return '';
 
    rev = page.revisions[0];


     if (header.length && content.length) {
     if (rev.slots && rev.slots.main) {
         header.prependTo(content);
         slot = rev.slots.main;
        return slot.content || slot['*'] || '';
     }
     }


     if ($('#clbi-right-sidebar').length === 0) {
     return rev.content || rev['*'] || '';
        var username = mw.config.get('wgUserName');
}
        var isLoggedIn = username !== null;
 
        var avatarSrc = isLoggedIn
function fetchGreatWallData() {
            ? '/index.php?title=특수:Redirect/file/Pfp-' + username + '.png'
    var api = new mw.Api();
            : '/index.php?title=특수:Redirect/file/Pfp-default.png';


         var userBox;
    return api.get({
        action: 'query',
        prop: 'revisions',
        titles: GREAT_WALL_DATA_TITLE,
        rvprop: 'content|timestamp',
        rvslots: 'main',
        formatversion: 2
    }).then(function(data) {
        var pages = data && data.query && data.query.pages ? data.query.pages : [];
         var page = pages[0] || null;


         if (isLoggedIn) {
         if (!page || page.missing) {
             userBox =
             return { entries: {} };
                '<div class="clbi-right-box profile-card-box">' +
         }
                    '<div id="clbi-user-avatar-wrap" class="profile-identity-panel">' +
                        '<div class="profile-avatar-stage">' +
                            '<img id="clbi-user-avatar" src="' + avatarSrc + '" onerror="this.onerror=null;this.src=\'/index.php?title=특수:Redirect/file/Pfp-default.png\';">' +
                        '</div>' +
                        '<div id="clbi-user-name-row" class="profile-name-row">' +
                            '<a href="/index.php/사용자:' + username + '" id="clbi-user-name">' + username + '</a>' +
                        '</div>' +
                    '</div>' +
                    '<div class="clbi-right-content profile-action-box">' +
                        '<div class="profile-quick-actions" aria-label="프로필 빠른 메뉴">' +
                            '<button type="button" class="profile-quick-btn" id="profile-quick-inventory" aria-label="인벤토리"><span class="profile-quick-icon" aria-hidden="true">' + CLBI_SVG_PACKAGE + '</span><span class="profile-quick-tip" aria-hidden="true">인벤토리</span></button>' +
                            '<button type="button" class="profile-quick-btn" id="profile-quick-achievements" aria-label="업적"><span class="profile-quick-icon" aria-hidden="true">' + CLBI_SVG_TROPHY + '</span><span class="profile-quick-tip" aria-hidden="true">업적</span></button>' +
                            '<button type="button" class="profile-quick-btn" id="profile-quick-notifications" aria-label="알림"><span id="profile-quick-notification-icon" class="profile-quick-icon" aria-hidden="true">' + CLBI_SVG_BELL + '</span><span class="profile-quick-tip" aria-hidden="true">알림</span></button>' +
                        '</div>' +
                        '<a href="/index.php/특수:기여/' + username + '" class="clbi-user-btn" id="clbi-btn-contribution"><span class="profile-action-icon" aria-hidden="true">' + CLBI_SVG_SCAN_TEXT + '</span><span class="profile-action-label">기여</span><i class="hn hn-angle-right-solid profile-action-arrow" aria-hidden="true"></i></a>' +
                        '<a href="/index.php/특수:주시문서목록" class="clbi-user-btn" id="clbi-btn-watchlist"><span class="profile-action-icon" aria-hidden="true">' + CLBI_SVG_SCAN_EYE + '</span><span class="profile-action-label">주시문서 목록</span><i class="hn hn-angle-right-solid profile-action-arrow" aria-hidden="true"></i></a>' +
                        '<a href="/index.php/특수:설정" class="clbi-user-btn" id="clbi-btn-preferences"><span class="profile-action-icon" aria-hidden="true">' + CLBI_SVG_SETTINGS + '</span><span class="profile-action-label">설정</span><i class="hn hn-angle-right-solid profile-action-arrow" aria-hidden="true"></i></a>' +
                        '<a href="/index.php?title=특수:로그아웃&returnto=대문" class="clbi-user-btn clbi-user-btn-logout" id="clbi-btn-logout"><span class="profile-action-icon" aria-hidden="true">' + CLBI_SVG_POWER + '</span><span class="profile-action-label">로그아웃</span><i class="hn hn-angle-right-solid profile-action-arrow" aria-hidden="true"></i></a>' +
                    '</div>' +
                '</div>';
        } else {
            userBox =
                '<div class="clbi-right-box profile-card-box">' +
                    '<div id="clbi-user-avatar-wrap" class="profile-identity-panel">' +
                        '<div class="profile-avatar-stage">' +
                            '<img id="clbi-user-avatar" src="/index.php?title=특수:Redirect/file/Pfp-default.png">' +
                        '</div>' +
                        '<div id="clbi-user-name-row" class="profile-name-row profile-name-row-guest">' +
                            '<span id="clbi-user-name">Guest</span>' +
                        '</div>' +
                    '</div>' +
                    '<div class="clbi-right-content profile-action-box">' +
                        '<a href="/index.php?title=특수:로그인&returnto=대문" class="clbi-user-btn" id="clbi-btn-login"><span class="profile-action-icon" aria-hidden="true">' + CLBI_SVG_POWER + '</span><span class="profile-action-label">로그인</span><i class="hn hn-angle-right-solid profile-action-arrow" aria-hidden="true"></i></a>' +
                    '</div>' +
                '</div>';
         }
        var greatWallBox = '';
        var siteInformationBox = '';


         try {
         return parseGreatWallData(getGreatWallRevisionText(page));
            greatWallBox = buildGreatWallBox();
    }, function(err) {
        } catch (err) {
        console.error('The Great Wall load failed:', err);
            console.error('The Great Wall build failed:', err);
        return { entries: {} };
            greatWallBox = '';
    });
        }
}


        try {
function getGreatWallEntries(data) {
            siteInformationBox = buildSiteInformationBox();
    var entries = data && data.entries && typeof data.entries === 'object' ? data.entries : {};
        } catch (err) {
            console.error('Site information build failed:', err);
            siteInformationBox = '';
        }


    return Object.keys(entries).map(function(key) {
        return entries[key];
    }).filter(function(item) {
        return item && item.user && item.text;
    }).sort(function(a, b) {
        return String(a.timestamp || '').localeCompare(String(b.timestamp || ''));
    });
}


        var sidebar = userBox + greatWallBox + siteInformationBox;
function getGreatWallMessageTime(timestamp) {
    var date = timestamp ? new Date(timestamp) : null;
    var month;
    var day;
    var hour;
    var minute;


        $('.content-wrapper').append('<div id="clbi-right-sidebar">' + sidebar + '</div>');
    if (!date || isNaN(date.getTime())) return '—';
        initGreatWallBoxWhenReady();
        removeMainPortalGuestbookPreview();
    }


     initGreatWallBoxWhenReady();
     month = String(date.getMonth() + 1).padStart(2, '0');
     removeMainPortalGuestbookPreview();
    day = String(date.getDate()).padStart(2, '0');
     hour = String(date.getHours()).padStart(2, '0');
    minute = String(date.getMinutes()).padStart(2, '0');


    return month + '.' + day + ' ' + hour + ':' + minute;
}


     if ($('#clbi-left-sidebar').length === 0) {
function getGreatWallAvatarSrc(user) {
var leftBillboardBox = '';
     return '/index.php?title=특수:Redirect/file/Pfp-' + encodeURIComponent(String(user || '')) + '.png';
}


        try {
function buildGreatWallEntryHtml(item, currentUser, selectedOwnEntry) {
            leftBillboardBox = buildRightBillboardBox();
    var isOwn = currentUser && item.user === currentUser;
        } catch (err) {
    var tag = isOwn ? 'button' : 'div';
            console.error('Left billboard build failed:', err);
    var attrs = isOwn ? ' type="button" data-great-wall-own-entry="1" aria-label="Edit your wall message"' : '';
            leftBillboardBox = '';
    var className = 'great-wall-entry' + (isOwn ? ' is-own' : '') + (isOwn && selectedOwnEntry ? ' is-selected' : '');
        }
    var avatarSrc = getGreatWallAvatarSrc(item.user);
    var messageTime = getGreatWallMessageTime(item.timestamp);
    var isoTime = item.timestamp || '';


var leftSidebar =
     return '' +
     '<div id="clbi-left-sidebar">' +
         '<' + tag + attrs + ' class="' + className + '">' +
         '<div class="clbi-left-box clbi-left-lang-box">' +
             '<img class="great-wall-avatar" src="' + escapeClbiHtml(avatarSrc) + '" alt="" onerror="this.onerror=null;this.src=&quot;/index.php?title=특수:Redirect/file/Pfp-default.png&quot;;">' +
            '<div class="clbi-left-title">' +
            '<div class="great-wall-bubble">' +
                '<span id="clbi-title-left-language">언어</span>' +
                '<div class="great-wall-entry-head">' +
            '</div>' +
                    '<span class="great-wall-user">@' + escapeClbiHtml(item.user) + '</span>' +
             '<div class="clbi-left-content sidebar-lang-box">' +
                    '<span class="great-wall-time" title="' + escapeClbiHtml(isoTime) + '">' + escapeClbiHtml(messageTime) + '</span>' +
                '<div id="clbi-sidebar-lang-selector" class="sidebar-lang-selector sidebar-lang-dial" tabindex="0" role="group" aria-label="언어 선택">' +
                    '<div id="clbi-sidebar-lang-dial-stage" class="sidebar-lang-dial-stage">' +
                        '<div id="clbi-sidebar-lang-fan" class="sidebar-lang-fan" aria-hidden="true"></div>' +
                        '<div id="clbi-sidebar-lang-selected-panel" class="sidebar-lang-status-panel sidebar-lang-status-left" aria-hidden="true">' +
                            '<span id="clbi-sidebar-lang-selected-value" class="sidebar-lang-status-value">한국어</span>' +
                        '</div>' +
                        '<div id="clbi-sidebar-lang-availability-panel" class="sidebar-lang-status-panel sidebar-lang-status-right is-current" aria-hidden="true">' +
                            '<span id="clbi-sidebar-lang-availability-value" class="sidebar-lang-status-value">CURRENT</span>' +
                        '</div>' +
                        '<button type="button" id="clbi-sidebar-lang-apply" class="sidebar-lang-apply" aria-label="언어 적용">' +
                            '<span class="sidebar-lang-apply-mark" aria-hidden="true">✓</span>' +
                        '</button>' +
                    '</div>' +
                 '</div>' +
                 '</div>' +
                '<div class="great-wall-text">' + escapeClbiHtml(item.text) + '</div>' +
             '</div>' +
             '</div>' +
         '</div>' +
         '</' + tag + '>';
        '<div class="clbi-left-box clbi-left-news-box">' +
}
            '<div class="clbi-left-title">' +
                '<span id="clbi-title-left-news">뉴스</span>' +
            '</div>' +
            '<div class="clbi-left-content clbi-news-box">' +


                '<div class="news-feed-title" id="clbi-left-news-changelog-title">CHANGELOG</div>' +
function renderGreatWallBox() {
                '<div class="news-left-changelog-feed">' +
    var box = document.getElementById('great-wall-sidebar');
                    '<a href="/index.php/체인지로그" class="news-post-item">' +
    var list = document.getElementById('great-wall-list');
                        '<div class="news-post-title-wrap">' +
    var input = document.getElementById('great-wall-input');
                            '<span class="news-post-title" id="clbi-left-news-changelog-main">체인지로그</span>' +
    var submit = document.getElementById('great-wall-submit');
                        '</div>' +
    var deleteButton = document.getElementById('great-wall-delete');
                        '<span class="news-post-jump" aria-hidden="true">›</span>' +
    var status = document.getElementById('great-wall-status');
                    '</a>' +
    var currentUser = mw.config.get('wgUserName') || '';
                '</div>' +
    var entries = getGreatWallEntries(greatWallState.data);
    var ownEntry = currentUser && greatWallState.data.entries ? greatWallState.data.entries[currentUser] : null;
    var visibleEntries = [];
    var seen = {};


                '<div class="news-divider"></div>' +
    if (!box || !list) return;


                '<div class="news-feed-title" id="clbi-left-news-recent-title">RECENT CHANGES</div>' +
    box.classList.toggle('is-guest', !currentUser);
                '<div class="news-left-recent-feed" id="clbi-left-recent-list">불러오는 중...</div>' +
    box.classList.toggle('is-loading', !!greatWallState.loading);
    box.classList.toggle('is-saving', !!greatWallState.saving);
    box.classList.toggle('has-own-entry', !!ownEntry);
    box.classList.toggle('is-own-selected', !!greatWallState.selectedOwnEntry);


                '<a class="news-fill-image-slot" id="clbi-left-news-fill-image" href="/index.php/특수:최근바뀜" aria-label="최근 바뀜으로 이동">' +
    entries.forEach(function(item) {
                    '<div class="news-fill-image-frame">' +
        if (seen[item.user]) return;
                        '<span class="news-fill-image" style="--news-fill-image-url:url(\'/index.php?title=특수:Redirect/file/Side-news-fill-001.png\');" aria-hidden="true"></span><img class="news-fill-image-probe" src="/index.php?title=특수:Redirect/file/Side-news-fill-001.png" alt="" aria-hidden="true" onerror="this.onerror=null;this.closest(\'.news-fill-image-slot\').classList.add(\'is-empty\');this.remove();">' +
        visibleEntries.push(item);
                    '</div>' +
        seen[item.user] = true;
                '</a>' +
    });


            '</div>' +
    if (greatWallState.loading && !greatWallState.loaded) {
         '</div>' +
        list.innerHTML = '<div class="great-wall-empty">SYNCING WALL</div>';
        leftBillboardBox +
    } else if (!visibleEntries.length) {
    '</div>';
         list.innerHTML = '<div class="great-wall-empty">NO MARKS</div>';
 
    } else {
         $('.content-wrapper').prepend(leftSidebar);
         list.innerHTML = visibleEntries.map(function(item) {
 
            return buildGreatWallEntryHtml(item, currentUser, greatWallState.selectedOwnEntry);
        renderSidebarLanguageBox();
         }).join('');
        loadRecentChangesList('#clbi-left-recent-list', 10);
         scheduleAdaptiveLeftRecentItems();
        scheduleLeftBillboardAdaptive();
        scheduleClbiContentBottomGap();
        updateLeftSidebarNationsImage();
     }
     }


     try {
     if (list && list.scrollHeight > list.clientHeight) {
        initRightBillboardCarousel();
         list.scrollTop = list.scrollHeight;
    } catch (err) {
         console.error('Right billboard carousel failed:', err);
     }
     }


     if (typeof window.normalizeClbiShellDomOrder === 'function') window.normalizeClbiShellDomOrder();
     if (status) {
    applyMainPageStyle();
        // Status text is intentionally suppressed in the composer strip; the area is spacing-only UI.
    initClbiCustomDocumentScrollbars();
         status.textContent = '';
    initCategoryNavIfAvailable(document);
 
    if (window.ProgressSystemWebUi && typeof window.ProgressSystemWebUi.boot === 'function') {
         window.ProgressSystemWebUi.boot('initSidebars');
     }
     }


     $('#side-toc-box').remove();
     if (!input || !submit) return;


     mw.loader.using(['mediawiki.api']).then(function() {
     input.disabled = false;
        setTimeout(function() {
    input.readOnly = false;
            initNotifications();
    input.removeAttribute('aria-readonly');
            initProfile();
            moveTocToLeftSidebar();
        }, 300);


        setTimeout(moveTocToLeftSidebar, 800);
    if (!currentUser) {
         setTimeout(moveTocToLeftSidebar, 1500);
        input.disabled = true;
    });
        input.readOnly = false;
}
        input.value = '';
        input.placeholder = '담벼락';
        submit.textContent = 'LOGIN';
         submit.disabled = false;
        if (deleteButton) {
            deleteButton.disabled = true;
            deleteButton.title = 'Login required';
        }
        return;
    }


$(function() {
    if (greatWallState.saving || greatWallState.loading) {
    loadLangScript(function() {
        input.disabled = true;
         setTimeout(function() {
        input.readOnly = false;
             initSidebars();
        submit.disabled = true;
         }, 100);
        submit.textContent = greatWallState.saving ? 'SAVE' : 'SYNC';
     });
         if (deleteButton) {
});
             deleteButton.disabled = true;
            deleteButton.title = greatWallState.saving ? 'Saving' : 'Syncing';
         }
        return;
     }


$(document).on('click.profileQuickPlaceholder', '#profile-quick-inventory, #profile-quick-achievements', function(e) {
    if (deleteButton) {
    e.preventDefault();
        deleteButton.disabled = !ownEntry;
     e.stopPropagation();
        deleteButton.title = ownEntry ? 'Delete your mark' : 'No mark to delete';
});
     }


function extractJsonArrayAfterMwConfigKey(text, key) {
    if (ownEntry && !greatWallState.selectedOwnEntry) {
    var needle = '"' + key + '"';
        input.disabled = false;
    var keyIndex = String(text || '').indexOf(needle);
        input.readOnly = true;
    var start;
        input.setAttribute('aria-readonly', 'true');
    var i;
        input.value = '';
    var depth = 0;
        input.placeholder = '담벼락';
    var inString = false;
        submit.disabled = true;
     var escaped = false;
        submit.textContent = 'UPDATE';
        return;
     }


     if (keyIndex === -1) return null;
     input.disabled = false;
 
    input.readOnly = false;
     start = String(text || '').indexOf('[', keyIndex + needle.length);
    input.removeAttribute('aria-readonly');
     if (start === -1) return null;
    input.placeholder = '담벼락';
     if (ownEntry && greatWallState.selectedOwnEntry && !input.value) {
        input.value = ownEntry.text || '';
    }
    submit.disabled = false;
    submit.textContent = ownEntry ? 'UPDATE' : 'POST';
}
 
function saveGreatWallEntry() {
    var input = document.getElementById('great-wall-input');
    var currentUser = mw.config.get('wgUserName') || '';
     var ownEntry = currentUser && greatWallState.data.entries ? greatWallState.data.entries[currentUser] : null;
    var text = input ? String(input.value || '').trim() : '';
    var api;


     for (i = start; i < text.length; i += 1) {
     if (!currentUser) {
         var ch = text.charAt(i);
         window.location.href = '/index.php?title=특수:로그인&returnto=' + encodeURIComponent(mw.config.get('wgPageName') || '대문');
        return;
    }


        if (inString) {
    if (ownEntry && !greatWallState.selectedOwnEntry) {
            if (escaped) {
        greatWallState.statusText = '';
                escaped = false;
        renderGreatWallBox();
            } else if (ch === '\\') {
        return;
                escaped = true;
    }
            } else if (ch === '"') {
                inString = false;
            }
            continue;
        }


        if (ch === '"') {
    if (!text) {
            inString = true;
        greatWallState.statusText = 'EMPTY MARK';
            continue;
        renderGreatWallBox();
         }
         return;
    }


        if (ch === '[') depth += 1;
    if (text.length > 140) {
         if (ch === ']') {
         text = text.slice(0, 140);
            depth -= 1;
            if (depth === 0) {
                try {
                    return JSON.parse(text.slice(start, i + 1));
                } catch (err) {
                    return null;
                }
            }
        }
     }
     }


     return null;
     greatWallState.saving = true;
}
    greatWallState.statusText = 'SAVING';
    renderGreatWallBox();


function extractJsonStringAfterMwConfigKey(text, key) {
    fetchGreatWallData().then(function(data) {
    var needle = '"' + key + '"';
        data = normalizeGreatWallData(data);
    var keyIndex = String(text || '').indexOf(needle);
        data.entries[currentUser] = {
    var colon;
            user: currentUser,
    var start;
            text: text,
    var i;
            timestamp: new Date().toISOString()
    var escaped = false;
        };


     if (keyIndex === -1) return null;
        api = new mw.Api();
        return api.postWithToken('csrf', {
            action: 'edit',
            title: GREAT_WALL_DATA_TITLE,
            text: stringifyGreatWallData(data),
            summary: 'Update The Great Wall entry',
            format: 'json'
        }).then(function() {
            greatWallState.data = data;
            greatWallState.loaded = true;
            greatWallState.selectedOwnEntry = false;
            greatWallState.statusText = 'MARK UPDATED';
            if (input) input.value = '';
        });
     }).then(function() {
        greatWallState.saving = false;
        renderGreatWallBox();
    }, function(err) {
        console.error('The Great Wall save failed:', err);
        greatWallState.saving = false;
        greatWallState.statusText = 'SAVE FAILED';
        renderGreatWallBox();
    });
}


    colon = text.indexOf(':', keyIndex + needle.length);
    if (colon === -1) return null;


     start = text.indexOf('"', colon + 1);
function deleteGreatWallEntry() {
     if (start === -1) return null;
     var input = document.getElementById('great-wall-input');
     var currentUser = mw.config.get('wgUserName') || '';
    var ownEntry = currentUser && greatWallState.data.entries ? greatWallState.data.entries[currentUser] : null;
    var api;


     for (i = start + 1; i < text.length; i += 1) {
     if (!currentUser) {
         var ch = text.charAt(i);
         window.location.href = '/index.php?title=특수:로그인&returnto=' + encodeURIComponent(mw.config.get('wgPageName') || '대문');
        return;
    }


        if (escaped) {
    if (!ownEntry) {
            escaped = false;
        greatWallState.statusText = 'NO MARK TO DELETE';
            continue;
        renderGreatWallBox();
         }
         return;
    }


        if (ch === '\\') {
    greatWallState.saving = true;
            escaped = true;
    greatWallState.statusText = 'DELETING';
            continue;
    renderGreatWallBox();
        }


        if (ch === '"') {
    fetchGreatWallData().then(function(data) {
            try {
        data = normalizeGreatWallData(data);
                return JSON.parse(text.slice(start, i + 1));
        if (data.entries && data.entries[currentUser]) {
            } catch (err) {
            delete data.entries[currentUser];
                return text.slice(start + 1, i);
            }
         }
         }
    }


     return null;
        api = new mw.Api();
        return api.postWithToken('csrf', {
            action: 'edit',
            title: GREAT_WALL_DATA_TITLE,
            text: stringifyGreatWallData(data),
            summary: 'Delete The Great Wall entry',
            format: 'json'
        }).then(function() {
            greatWallState.data = data;
            greatWallState.loaded = true;
            greatWallState.selectedOwnEntry = false;
            greatWallState.statusText = 'MARK DELETED';
            if (input) input.value = '';
        });
    }).then(function() {
        greatWallState.saving = false;
        renderGreatWallBox();
    }, function(err) {
        console.error('The Great Wall delete failed:', err);
        greatWallState.saving = false;
        greatWallState.statusText = 'DELETE FAILED';
        renderGreatWallBox();
     });
}
}


function syncCatlinksConfigFromSpaDocument(doc) {
function initGreatWallBoxWhenReady() {
     var scripts = doc ? doc.querySelectorAll('script') : [];
     if (!document.getElementById('great-wall-sidebar')) return;
    var categories = null;
 
     var hiddenCategories = null;
     if (mw.Api) {
    var relevantPageName = null;
        initGreatWallBox();
    var pageName = null;
        return;
    var i;
     }
     var text;
    var value;


     for (i = 0; i < scripts.length; i += 1) {
     if (mw.loader && mw.loader.using) {
         text = scripts[i].textContent || '';
         mw.loader.using(['mediawiki.api']).then(function() {
            initGreatWallBox();
        });
    }
}


        if (categories === null) {
function initGreatWallBox() {
            value = extractJsonArrayAfterMwConfigKey(text, 'wgCategories');
    var box = document.getElementById('great-wall-sidebar');
            if (Array.isArray(value)) categories = value;
    var input = document.getElementById('great-wall-input');
        }
    var submit = document.getElementById('great-wall-submit');
    var deleteButton = document.getElementById('great-wall-delete');


        if (hiddenCategories === null) {
    if (!box || box.getAttribute('data-great-wall-ready') === '1') return;
            value = extractJsonArrayAfterMwConfigKey(text, 'wgHiddenCategories');
            if (Array.isArray(value)) hiddenCategories = value;
        }


        if (relevantPageName === null) {
    if (!mw.Api) {
            value = extractJsonStringAfterMwConfigKey(text, 'wgRelevantPageName');
        initGreatWallBoxWhenReady();
            if (value !== null) relevantPageName = value;
         return;
         }
 
        if (pageName === null) {
            value = extractJsonStringAfterMwConfigKey(text, 'wgPageName');
            if (value !== null) pageName = value;
        }
     }
     }


     mw.config.set('wgCategories', Array.isArray(categories) ? categories : []);
     box.setAttribute('data-great-wall-ready', '1');
    mw.config.set('wgHiddenCategories', Array.isArray(hiddenCategories) ? hiddenCategories : []);


     if (relevantPageName !== null) {
     box.addEventListener('click', function(e) {
         mw.config.set('wgRelevantPageName', relevantPageName);
         var ownButton = e.target.closest ? e.target.closest('[data-great-wall-own-entry="1"]') : null;
    } else if (pageName !== null) {
        var currentUser = mw.config.get('wgUserName') || '';
        mw.config.set('wgRelevantPageName', pageName);
        var ownEntry = currentUser && greatWallState.data.entries ? greatWallState.data.entries[currentUser] : null;
    }


    CLBI_CATLINKS_FETCH_TOKEN += 1;
        if (!ownButton || !ownEntry) return;
}


// SPA 네비게이션
        greatWallState.selectedOwnEntry = true;
function shouldSkip(url) {
        greatWallState.statusText = '';
    return url.match(/action=edit|action=submit|action=history|action=delete|action=protect|action=purge|특수:로그인|특수:로그아웃|Special:UserLogin|Special:UserLogout|특수:사용자정보|특수:비밀번호바꾸기|uselang=/);
        renderGreatWallBox();
}


$(function() {
        if (input) {
    if (window._spaInitialized) return;
            input.focus();
     window._spaInitialized = true;
            input.setSelectionRange(input.value.length, input.value.length);
        }
     });


     function isInternal(url) {
     document.addEventListener('click', function(e) {
         var a = document.createElement('a');
         var target = e.target;
         a.href = url;
         var keepSelection;
        return a.hostname === window.location.hostname;
    }


    function getCachedSpaPageHtml(url) {
         if (!greatWallState.selectedOwnEntry || !target || !target.closest) return;
         if (!window.EntryStore || typeof window.EntryStore.getTextSync !== 'function') return '';
        return window.EntryStore.getTextSync(url) || window.EntryStore.getTextSync(String(url || '').replace(/^https?:\/\/[^/]+/i, '')) || '';
    }


    function fetchSpaPageHtml(url) {
         keepSelection = target.closest('[data-great-wall-own-entry="1"], .great-wall-editor, .great-wall-compose-sector');
         var cached = getCachedSpaPageHtml(url);
        if (cached) return Promise.resolve(cached);
        return fetch(url, { credentials: 'same-origin', cache: 'force-cache' }).then(function(res) {
            return res.text();
        });
    }


    function prepareDetachedEntryContent(newContent) {
        if (keepSelection) return;
        /*
 
         Initial boot prepares entry artifacts; SPA is only allowed to consume them.
         greatWallState.selectedOwnEntry = false;
         This hook runs while the fetched page is still detached, before the user sees it.
         greatWallState.statusText = '';
         It must stay synchronous or already-resolved: if a subsystem cannot prepare from
         if (input) input.value = '';
         EntryStore immediately, it should leave the old fallback path in place instead of
         renderGreatWallBox();
        opening BootGate during SPA.
    });
        */
 
         try {
    if (submit) {
             if (window.NationsPanel && typeof window.NationsPanel.prepareContentForEntry === 'function') {
         submit.addEventListener('click', function(e) {
                 window.NationsPanel.prepareContentForEntry(newContent);
            e.preventDefault();
             if (!mw.config.get('wgUserName')) {
                 window.location.href = '/index.php?title=특수:로그인&returnto=' + encodeURIComponent(mw.config.get('wgPageName') || '대문');
                return;
             }
             }
        } catch (err) {
             saveGreatWallEntry();
             console.warn('entry content preparation failed:', err);
         });
         }
     }
     }


     function loadPage(url) {
     if (deleteButton) {
         invalidateProfileRender();
        deleteButton.addEventListener('click', function(e) {
            e.preventDefault();
            deleteGreatWallEntry();
         });
    }


        return fetchSpaPageHtml(url)
    if (input) {
            .then(function(html) {
        input.addEventListener('keydown', function(e) {
                 var parser = new DOMParser();
            if (e.key === 'Enter') {
                 var doc = parser.parseFromString(html, 'text/html');
                 e.preventDefault();
                 saveGreatWallEntry();
            }
        });


                var scripts = doc.querySelectorAll('script');
        input.addEventListener('input', function() {
                for (var i = 0; i < scripts.length; i++) {
            if (input.value.length > 140) {
                    var src = scripts[i].textContent;
                input.value = input.value.slice(0, 140);
            }
        });
    }


                    if (src.indexOf('wgNamespaceNumber') !== -1) {
    greatWallState.loading = true;
                        var match = src.match(/"wgNamespaceNumber":(-?\d+)/);
    greatWallState.statusText = 'SYNCING WALL';
                        if (match) mw.config.set('wgNamespaceNumber', parseInt(match[1], 10));
    renderGreatWallBox();


                        var matchTitle = src.match(/"wgTitle":"([^"]+)"/);
    fetchGreatWallData().then(function(data) {
                        if (matchTitle) mw.config.set('wgTitle', matchTitle[1]);
        greatWallState.data = normalizeGreatWallData(data);
 
        greatWallState.loaded = true;
                        var matchPage = src.match(/"wgPageName":"([^"]+)"/);
        greatWallState.loading = false;
                        if (matchPage) mw.config.set('wgPageName', matchPage[1]);
        greatWallState.selectedOwnEntry = false;
        greatWallState.statusText = '';
        renderGreatWallBox();
    });
}


                        var matchArticle = src.match(/"wgArticleId":(\d+)/);
function buildGreatWallBox() {
                        if (matchArticle) {
    return '' +
                            mw.config.set('wgArticleId', parseInt(matchArticle[1], 10));
        '<div id="great-wall-sidebar" class="clbi-right-box great-wall-sidebar">' +
                        } else {
            '<div class="clbi-right-title great-wall-title">' +
                            mw.config.set('wgArticleId', 0);
                '<span id="clbi-title-great-wall">The Great Wall</span>' +
                        }
            '</div>' +
            '<div class="clbi-right-content great-wall-content">' +
                '<div id="great-wall-list" class="great-wall-list"><div class="great-wall-empty">SYNCING WALL</div></div>' +
            '</div>' +
            '<div class="great-wall-compose-sector" aria-label="The Great Wall editor">' +
                '<div class="great-wall-editor">' +
                    '<input id="great-wall-input" class="great-wall-input" type="text" maxlength="140" autocomplete="off" placeholder="담벼락">' +
                    '<button id="great-wall-submit" class="great-wall-submit" type="button">POST</button>' +
                    '<button id="great-wall-delete" class="great-wall-delete" type="button" disabled>DEL</button>' +
                '</div>' +
                '<div id="great-wall-status" class="great-wall-status">SYNCING WALL</div>' +
            '</div>' +
        '</div>';
}


                        var matchIsMainPage = src.match(/"wgIsMainPage":(true|false)/);
function removeMainPortalGuestbookPreview() {
                        if (matchIsMainPage) {
    var portal = document.querySelector('.main-portal');
                            mw.config.set('wgIsMainPage', matchIsMainPage[1] === 'true');
    var guestbook = portal ? portal.querySelector('.guestbook-device') : null;
                        } else {
    var sideScreen;
                            mw.config.set('wgIsMainPage', false);
    var grid;
                        }


                        var matchSpecial = src.match(/"wgCanonicalSpecialPageName":"([^"]+)"/);
    if (!portal || !guestbook) return;
                        if (matchSpecial) {
                            mw.config.set('wgCanonicalSpecialPageName', matchSpecial[1]);
                        } else {
                            mw.config.set('wgCanonicalSpecialPageName', false);
                        }
                        break;
                    }
                }


                syncCatlinksConfigFromSpaDocument(doc);
    sideScreen = guestbook.closest ? guestbook.closest('.side-screen') : null;
    grid = sideScreen && sideScreen.closest ? sideScreen.closest('.console-grid') : null;


                var newContent = doc.querySelector('.liberty-content-main');
    if (guestbook.parentNode) {
                var newTitle = doc.querySelector('.mw-page-title-main');
        guestbook.parentNode.removeChild(guestbook);
                var newHead = doc.querySelector('title');
    }
                var newHeader = doc.querySelector('.liberty-content-header');


                if (newContent) {
    if (sideScreen && !(sideScreen.textContent || '').trim() && !sideScreen.querySelector('img,svg,video,canvas,form,input,button,a')) {
                    prepareDetachedEntryContent(newContent);
        if (sideScreen.parentNode) {
                    prepareSpaCatlinksBeforeInsert(newContent);
            sideScreen.parentNode.removeChild(sideScreen);
                    $('#side-toc-box').remove();
        }
                    $('.profile-card').remove();
                    $('.user-profile-portal').removeClass('user-profile-portal');
                    $('.liberty-content-main').html(newContent.innerHTML);
                    $('.profile-card').remove();
                    try {
                        if (window.Decorations && typeof window.Decorations.renderPrepared === 'function') window.Decorations.renderPrepared();
                        else if (window.CLBI_DECORATIONS && typeof window.CLBI_DECORATIONS.renderPrepared === 'function') window.CLBI_DECORATIONS.renderPrepared();
                    } catch (err) {}
                    $('body').removeClass('page-loading');
                }


                if (newTitle) {
        if (grid) {
                    $('.mw-page-title-main').html(newTitle.innerHTML);
            grid.style.gridTemplateColumns = 'minmax(0,1fr)';
                }
        }
    }


                if (newHead) {
    portal.classList.add('is-great-wall-relocated');
                    document.title = newHead.textContent;
}
                }


                if (newHeader) {
function buildSiteInformationBox() {
                     $('.liberty-content-header').html(newHeader.innerHTML);
    return '' +
                }
        '<div class="clbi-right-box site-info-sidebar">' +
            '<div class="clbi-right-title site-info-title">' +
                '<span>정보</span>' +
            '</div>' +
            '<div class="clbi-right-content site-info-content">' +
                '<div class="policy-list">' +
                    '<div class="policy-row"><a href="/index.php/개인정보처리방침" class="site-info-policy-button"><span class="site-info-policy-title">개인정보처리방침</span><span class="site-info-policy-arrow" aria-hidden="true">›</span></a></div>' +
                    '<div class="policy-row"><a href="/index.php/면책_조항" class="site-info-policy-button"><span class="site-info-policy-title">면책 조항</span><span class="site-info-policy-arrow" aria-hidden="true">›</span></a></div>' +
                    '<div class="policy-row"><a href="/index.php/라이선스" class="site-info-policy-button"><span class="site-info-policy-title">라이선스</span><span class="site-info-policy-arrow" aria-hidden="true">›</span></a></div>' +
                     '<div class="policy-row"><a href="/index.php/크레딧" class="site-info-policy-button"><span class="site-info-policy-title">크레딧</span><span class="site-info-policy-arrow" aria-hidden="true">›</span></a></div>' +
                '</div>' +
                '<div class="social-strip">' +
                    '<span class="social-icon"><a href="https://discord.gg/ctaeJ9d3Q5" target="_blank" rel="noopener noreferrer">DC</a></span>' +
                    '<span class="social-icon"><a href="https://www.youtube.com/@nxdsxn" target="_blank" rel="noopener noreferrer">YT</a></span>' +
                    '<span class="social-icon"><a href="https://x.com/nxd_sxn" target="_blank" rel="noopener noreferrer">X</a></span>' +
                    '<span class="social-icon"><a href="/index.php/프로젝트:소개">WIP:</a></span>' +
                '</div>' +
            '</div>' +
        '</div>';
}


                if (typeof window.normalizeClbiShellDomOrder === 'function') window.normalizeClbiShellDomOrder();
                window.scrollTo(0, 0);
                mw.hook('wikipage.content').fire($('.liberty-content-main'));
                applyMainPageStyle();
                initClbiCustomDocumentScrollbars();
                initCategoryNavIfAvailable(document);


                if (window.ProgressSystemWebUi && typeof window.ProgressSystemWebUi.handleSpaPageView === 'function') {
// 초기화 함수
                    window.ProgressSystemWebUi.handleSpaPageView();
function initSidebars() {
                } else if (window.ProgressSystemWebUi && typeof window.ProgressSystemWebUi.boot === 'function') {
    var header = $('.liberty-content-header');
                    window.ProgressSystemWebUi.boot('spa');
    var content = $('.liberty-content');
                }


                $('#side-toc-box').remove();
    if (header.length && content.length) {
                setTimeout(moveTocToLeftSidebar, 100);
        header.prependTo(content);
                setTimeout(moveTocToLeftSidebar, 500);
                setTimeout(moveTocToLeftSidebar, 1200);
 
                mw.loader.using(['mediawiki.api']).then(function() {
                    initProfile();
                    moveTocToLeftSidebar();
                });
            })
            .catch(function (err) {
                console.error('SPA page load failed:', err);
                $('body').removeClass('page-loading');
            });
     }
     }


// 목차 링크는 전용 처리
    if ($('#clbi-right-sidebar').length === 0) {
$(document).on('click', '#side-toc-box a, #toc a, .toc a', function(e) {
        var username = mw.config.get('wgUserName');
    var href = $(this).attr('href');
        var isLoggedIn = username !== null;
    if (!href || href.charAt(0) !== '#') return;
        var avatarSrc = isLoggedIn
            ? '/index.php?title=특수:Redirect/file/Pfp-' + username + '.png'
            : '/index.php?title=특수:Redirect/file/Pfp-default.png';


    var rawId = href.slice(1);
        var userBox;
    if (!rawId) return;


    var decodedId = rawId;
        if (isLoggedIn) {
            userBox =
                '<div class="clbi-right-box profile-card-box">' +
                    '<div id="clbi-user-avatar-wrap" class="profile-identity-panel">' +
                        '<div class="profile-avatar-stage">' +
                            '<img id="clbi-user-avatar" src="' + avatarSrc + '" onerror="this.onerror=null;this.src=\'/index.php?title=특수:Redirect/file/Pfp-default.png\';">' +
                        '</div>' +
                        '<div id="clbi-user-name-row" class="profile-name-row">' +
                            '<a href="/index.php/사용자:' + username + '" id="clbi-user-name">' + username + '</a>' +
                        '</div>' +
                    '</div>' +
                    '<div class="clbi-right-content profile-action-box">' +
                        '<div class="profile-quick-actions" aria-label="프로필 빠른 메뉴">' +
                            '<button type="button" class="profile-quick-btn" id="profile-quick-inventory" aria-label="인벤토리"><span class="profile-quick-icon" aria-hidden="true">' + CLBI_SVG_PACKAGE + '</span><span class="profile-quick-tip" aria-hidden="true">인벤토리</span></button>' +
                            '<button type="button" class="profile-quick-btn" id="profile-quick-achievements" aria-label="업적"><span class="profile-quick-icon" aria-hidden="true">' + CLBI_SVG_TROPHY + '</span><span class="profile-quick-tip" aria-hidden="true">업적</span></button>' +
                            '<button type="button" class="profile-quick-btn" id="profile-quick-notifications" aria-label="알림"><span id="profile-quick-notification-icon" class="profile-quick-icon" aria-hidden="true">' + CLBI_SVG_BELL + '</span><span class="profile-quick-tip" aria-hidden="true">알림</span></button>' +
                        '</div>' +
                        '<a href="/index.php/특수:기여/' + username + '" class="clbi-user-btn" id="clbi-btn-contribution"><span class="profile-action-icon" aria-hidden="true">' + CLBI_SVG_SCAN_TEXT + '</span><span class="profile-action-label">기여</span><i class="hn hn-angle-right-solid profile-action-arrow" aria-hidden="true"></i></a>' +
                        '<a href="/index.php/특수:주시문서목록" class="clbi-user-btn" id="clbi-btn-watchlist"><span class="profile-action-icon" aria-hidden="true">' + CLBI_SVG_SCAN_EYE + '</span><span class="profile-action-label">주시문서 목록</span><i class="hn hn-angle-right-solid profile-action-arrow" aria-hidden="true"></i></a>' +
                        '<a href="/index.php/특수:설정" class="clbi-user-btn" id="clbi-btn-preferences"><span class="profile-action-icon" aria-hidden="true">' + CLBI_SVG_SETTINGS + '</span><span class="profile-action-label">설정</span><i class="hn hn-angle-right-solid profile-action-arrow" aria-hidden="true"></i></a>' +
                        '<a href="/index.php?title=특수:로그아웃&returnto=대문" class="clbi-user-btn clbi-user-btn-logout" id="clbi-btn-logout"><span class="profile-action-icon" aria-hidden="true">' + CLBI_SVG_POWER + '</span><span class="profile-action-label">로그아웃</span><i class="hn hn-angle-right-solid profile-action-arrow" aria-hidden="true"></i></a>' +
                    '</div>' +
                '</div>';
        } else {
            userBox =
                '<div class="clbi-right-box profile-card-box">' +
                    '<div id="clbi-user-avatar-wrap" class="profile-identity-panel">' +
                        '<div class="profile-avatar-stage">' +
                            '<img id="clbi-user-avatar" src="/index.php?title=특수:Redirect/file/Pfp-default.png">' +
                        '</div>' +
                        '<div id="clbi-user-name-row" class="profile-name-row profile-name-row-guest">' +
                            '<span id="clbi-user-name">Guest</span>' +
                        '</div>' +
                    '</div>' +
                    '<div class="clbi-right-content profile-action-box">' +
                        '<a href="/index.php?title=특수:로그인&returnto=대문" class="clbi-user-btn" id="clbi-btn-login"><span class="profile-action-icon" aria-hidden="true">' + CLBI_SVG_POWER + '</span><span class="profile-action-label">로그인</span><i class="hn hn-angle-right-solid profile-action-arrow" aria-hidden="true"></i></a>' +
                    '</div>' +
                '</div>';
        }
        var greatWallBox = '';
        var siteInformationBox = '';


    try {
        try {
        decodedId = decodeURIComponent(rawId);
            greatWallBox = buildGreatWallBox();
    } catch (err) {
        } catch (err) {
        decodedId = rawId;
            console.error('The Great Wall build failed:', err);
    }
            greatWallBox = '';
        }


    var target = document.getElementById(decodedId);
        try {
            siteInformationBox = buildSiteInformationBox();
        } catch (err) {
            console.error('Site information build failed:', err);
            siteInformationBox = '';
        }


    if (!target && window.CSS && CSS.escape) {
        target = document.querySelector('#' + CSS.escape(decodedId));
    }


    if (!target) return;
        var sidebar = userBox + greatWallBox + siteInformationBox;


    e.preventDefault();
        $('.content-wrapper').append('<div id="clbi-right-sidebar">' + sidebar + '</div>');
    e.stopPropagation();
        initGreatWallBoxWhenReady();
        removeMainPortalGuestbookPreview();
    }


     var scrollTarget = target.closest('h2, h3') || target;
     initGreatWallBoxWhenReady();
 
     removeMainPortalGuestbookPreview();
     scrollTarget.scrollIntoView({
        behavior: 'auto',
        block: 'start'
    });


    history.replaceState(null, '', '#' + rawId);
});


     $(document).on('click', 'a', function(e) {
     if ($('#clbi-left-sidebar').length === 0) {
        // 휠 클릭, 새 탭 열기, 보조키 이동은 브라우저 기본 동작을 유지한다.
var leftBillboardBox = '';
        if (e.which && e.which !== 1) return;
        if (e.button && e.button !== 0) return;
        if (e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) return;


         var href = $(this).attr('href');
         try {
         if (!href) return;
            leftBillboardBox = buildRightBillboardBox();
        } catch (err) {
            console.error('Left billboard build failed:', err);
            leftBillboardBox = '';
         }


         // 목차 링크는 별도 핸들러에서 처리
var leftSidebar =
         if ($(this).closest('#side-toc-box, #toc, .toc').length) return;
    '<div id="clbi-left-sidebar">' +
 
         '<div class="clbi-left-box clbi-left-lang-box">' +
        // 단순 해시 링크는 SPA 가로채기 제외
            '<div class="clbi-left-title">' +
        if (href.startsWith('#')) return;
                '<span id="clbi-title-left-language">언어</span>' +
            '</div>' +
            '<div class="clbi-left-content sidebar-lang-box">' +
                '<div id="clbi-sidebar-lang-selector" class="sidebar-lang-selector sidebar-lang-dial" tabindex="0" role="group" aria-label="언어 선택">' +
                    '<div id="clbi-sidebar-lang-dial-stage" class="sidebar-lang-dial-stage">' +
                        '<div id="clbi-sidebar-lang-fan" class="sidebar-lang-fan" aria-hidden="true"></div>' +
                        '<div id="clbi-sidebar-lang-selected-panel" class="sidebar-lang-status-panel sidebar-lang-status-left" aria-hidden="true">' +
                            '<span id="clbi-sidebar-lang-selected-value" class="sidebar-lang-status-value">한국어</span>' +
                        '</div>' +
                        '<div id="clbi-sidebar-lang-availability-panel" class="sidebar-lang-status-panel sidebar-lang-status-right is-current" aria-hidden="true">' +
                            '<span id="clbi-sidebar-lang-availability-value" class="sidebar-lang-status-value">CURRENT</span>' +
                        '</div>' +
                        '<button type="button" id="clbi-sidebar-lang-apply" class="sidebar-lang-apply" aria-label="언어 적용">' +
                            '<span class="sidebar-lang-apply-mark" aria-hidden="true">✓</span>' +
                        '</button>' +
                    '</div>' +
                '</div>' +
            '</div>' +
        '</div>' +
         '<div class="clbi-left-box clbi-left-news-box">' +
            '<div class="clbi-left-title">' +
                '<span id="clbi-title-left-news">뉴스</span>' +
            '</div>' +
            '<div class="clbi-left-content clbi-news-box">' +


        var link = document.createElement('a');
                '<div class="news-feed-title" id="clbi-left-news-changelog-title">CHANGELOG</div>' +
        link.href = href;
                '<div class="news-left-changelog-feed">' +
                    '<a href="/index.php/체인지로그" class="news-post-item">' +
                        '<div class="news-post-title-wrap">' +
                            '<span class="news-post-title" id="clbi-left-news-changelog-main">체인지로그</span>' +
                        '</div>' +
                        '<span class="news-post-jump" aria-hidden="true">›</span>' +
                    '</a>' +
                '</div>' +
 
                '<div class="news-divider"></div>' +


        var samePath = decodeURIComponent(link.pathname) === decodeURIComponent(window.location.pathname);
                '<div class="news-feed-title" id="clbi-left-news-recent-title">RECENT CHANGES</div>' +
        var sameSearch = (link.search || '') === (window.location.search || '');
                '<div class="news-left-recent-feed" id="clbi-left-recent-list">불러오는 중...</div>' +


        if (link.hash && samePath && sameSearch) return;
                '<a class="news-fill-image-slot" id="clbi-left-news-fill-image" href="/index.php/특수:최근바뀜" aria-label="최근 바뀜으로 이동">' +
                    '<div class="news-fill-image-frame">' +
                        '<span class="news-fill-image" style="--news-fill-image-url:url(\'/index.php?title=특수:Redirect/file/Side-news-fill-001.png\');" aria-hidden="true"></span><img class="news-fill-image-probe" src="/index.php?title=특수:Redirect/file/Side-news-fill-001.png" alt="" aria-hidden="true" onerror="this.onerror=null;this.closest(\'.news-fill-image-slot\').classList.add(\'is-empty\');this.remove();">' +
                    '</div>' +
                '</a>' +


         var currentBase = window.location.href.split('#')[0];
            '</div>' +
         var targetBase = link.href.split('#')[0];
         '</div>' +
         leftBillboardBox +
    '</div>';


         if (link.hash && currentBase === targetBase) return;
         $('.content-wrapper').prepend(leftSidebar);


         if (!isInternal(href)) return;
         renderSidebarLanguageBox();
         if (shouldSkip(href)) return;
        loadRecentChangesList('#clbi-left-recent-list', 10);
        scheduleAdaptiveLeftRecentItems();
         scheduleLeftBillboardAdaptive();
        scheduleClbiContentBottomGap();
        updateLeftSidebarNationsImage();
    }


        e.preventDefault();
    try {
         playStaticSound();
         initRightBillboardCarousel();
        /*
    } catch (err) {
        SPA must remain a consumer phase.  If the target page HTML was prepared by
         console.error('Right billboard carousel failed:', err);
        the first-load boot pack, do not show the legacy page-loading veil.  The
     }
        route will consume cached HTML and detached entry artifacts before insertion.
        */
        if (getCachedSpaPageHtml(href)) {
            $('body').removeClass('page-loading');
         } else {
            $('body').addClass('page-loading');
        }
        history.pushState(null, '', href);
        loadPage(href);
     });


     window.addEventListener('popstate', function() {
     if (typeof window.normalizeClbiShellDomOrder === 'function') window.normalizeClbiShellDomOrder();
        loadPage(window.location.href);
    applyMainPageStyle();
     });
     initClbiCustomDocumentScrollbars();
});
    initCategoryNavIfAvailable(document);


    if (window.ProgressSystemWebUi && typeof window.ProgressSystemWebUi.boot === 'function') {
        window.ProgressSystemWebUi.boot('initSidebars');
    }


    $('#side-toc-box').remove();


/* ========== CLBI Custom Document Scrollbar ========== */
    mw.loader.using(['mediawiki.api']).then(function() {
function isGeneralDocumentView() {
        setTimeout(function() {
    var body = document.body;
            initNotifications();
    if (!body) return false;
            initProfile();
            moveTocToLeftSidebar();
        }, 300);


    return body.classList.contains('action-view') &&
         setTimeout(moveTocToLeftSidebar, 800);
         !body.classList.contains('clbi-main-page') &&
         setTimeout(moveTocToLeftSidebar, 1500);
         !body.classList.contains('clbi-system-doc-page') &&
    });
        !body.classList.contains('backend-system-page') &&
        !body.classList.contains('user-profile-page') &&
        !body.classList.contains('user-profile-settings-page');
}
}


function getClbiDocumentScrollTargets() {
$(function() {
     if (!isGeneralDocumentView()) return [];
     loadLangScript(function() {
 
         setTimeout(function() {
    return Array.prototype.slice.call(document.querySelectorAll(
            initSidebars();
         '.liberty-content-main > #mw-content-text .mw-parser-output, ' +
         }, 100);
        '.liberty-content-main > .mw-body-content .mw-parser-output'
    )).filter(function (el, index, list) {
         return el && list.indexOf(el) === index;
     });
     });
}
});


function getClbiOuterWellForScroll(scrollEl) {
$(document).on('click.profileQuickPlaceholder', '#profile-quick-inventory, #profile-quick-achievements', function(e) {
    var main = scrollEl ? scrollEl.closest('.liberty-content-main') : null;
     e.preventDefault();
     var children;
     e.stopPropagation();
     var i;
});
    var child;


     if (!main) return null;
function extractJsonArrayAfterMwConfigKey(text, key) {
    var needle = '"' + key + '"';
    var keyIndex = String(text || '').indexOf(needle);
    var start;
    var i;
    var depth = 0;
    var inString = false;
    var escaped = false;
 
     if (keyIndex === -1) return null;
 
    start = String(text || '').indexOf('[', keyIndex + needle.length);
    if (start === -1) return null;
 
    for (i = start; i < text.length; i += 1) {
        var ch = text.charAt(i);
 
        if (inString) {
            if (escaped) {
                escaped = false;
            } else if (ch === '\\') {
                escaped = true;
            } else if (ch === '"') {
                inString = false;
            }
            continue;
        }


    children = Array.prototype.slice.call(main.children || []);
        if (ch === '"') {
    for (i = 0; i < children.length; i += 1) {
            inString = true;
         child = children[i];
            continue;
         if (
         }
             child &&
 
             (child.id === 'mw-content-text' || child.classList.contains('mw-body-content')) &&
        if (ch === '[') depth += 1;
            child.contains(scrollEl)
         if (ch === ']') {
        ) {
             depth -= 1;
            return child;
             if (depth === 0) {
                try {
                    return JSON.parse(text.slice(start, i + 1));
                } catch (err) {
                    return null;
                }
            }
         }
         }
     }
     }


     return scrollEl.parentElement || null;
     return null;
}
}


function buildClbiCustomScrollbar(well, scrollEl) {
function extractJsonStringAfterMwConfigKey(text, key) {
     var bar = well.querySelector(':scope > .clbi-custom-scrollbar');
     var needle = '"' + key + '"';
     var up;
    var keyIndex = String(text || '').indexOf(needle);
     var track;
     var colon;
     var thumb;
     var start;
     var down;
     var i;
     var escaped = false;
 
    if (keyIndex === -1) return null;


     if (!bar) {
     colon = text.indexOf(':', keyIndex + needle.length);
        bar = document.createElement('div');
    if (colon === -1) return null;
        bar.className = 'clbi-custom-scrollbar';
        bar.setAttribute('aria-hidden', 'true');
        bar.innerHTML =
            '<div class="clbi-custom-scroll-arrow clbi-custom-scroll-arrow-up" data-scroll-arrow="up"></div>' +
            '<div class="clbi-custom-scroll-track"><div class="clbi-custom-scroll-thumb"></div></div>' +
            '<div class="clbi-custom-scroll-arrow clbi-custom-scroll-arrow-down" data-scroll-arrow="down"></div>';
        well.appendChild(bar);
    }


     bar.__clbiScrollTarget = scrollEl;
     start = text.indexOf('"', colon + 1);
    up = bar.querySelector('.clbi-custom-scroll-arrow-up');
     if (start === -1) return null;
     track = bar.querySelector('.clbi-custom-scroll-track');
    thumb = bar.querySelector('.clbi-custom-scroll-thumb');
    down = bar.querySelector('.clbi-custom-scroll-arrow-down');


     if (up && !up.__clbiBound) {
     for (i = start + 1; i < text.length; i += 1) {
         up.__clbiBound = true;
         var ch = text.charAt(i);
        up.addEventListener('mousedown', function (e) {
            e.preventDefault();
            e.stopPropagation();
            if (bar.__clbiScrollTarget) bar.__clbiScrollTarget.scrollTop -= 48;
            updateClbiCustomScrollbar(bar);
        });
    }


    if (down && !down.__clbiBound) {
        if (escaped) {
        down.__clbiBound = true;
             escaped = false;
        down.addEventListener('mousedown', function (e) {
             continue;
             e.preventDefault();
         }
            e.stopPropagation();
            if (bar.__clbiScrollTarget) bar.__clbiScrollTarget.scrollTop += 48;
             updateClbiCustomScrollbar(bar);
         });
    }


    if (track && !track.__clbiBound) {
        if (ch === '\\') {
        track.__clbiBound = true;
             escaped = true;
        track.addEventListener('mousedown', function (e) {
             continue;
             var rect;
        }
             var thumbRect;
            var target;
            var direction;


            if (e.target === thumb) return;
        if (ch === '"') {
             e.preventDefault();
             try {
             e.stopPropagation();
                return JSON.parse(text.slice(start, i + 1));
             } catch (err) {
                return text.slice(start + 1, i);
            }
        }
    }


            target = bar.__clbiScrollTarget;
    return null;
            if (!target) return;
}


            rect = track.getBoundingClientRect();
function syncCatlinksConfigFromSpaDocument(doc) {
            thumbRect = thumb.getBoundingClientRect();
    var scripts = doc ? doc.querySelectorAll('script') : [];
            direction = e.clientY < thumbRect.top ? -1 : 1;
    var categories = null;
            target.scrollTop += direction * Math.max(60, Math.floor(target.clientHeight * 0.82));
    var hiddenCategories = null;
            updateClbiCustomScrollbar(bar);
    var relevantPageName = null;
        });
    var pageName = null;
     }
    var i;
    var text;
     var value;


     if (thumb && !thumb.__clbiBound) {
     for (i = 0; i < scripts.length; i += 1) {
         thumb.__clbiBound = true;
         text = scripts[i].textContent || '';
        thumb.addEventListener('mousedown', function (e) {
            var target = bar.__clbiScrollTarget;
            var startY;
            var startScroll;
            var maxScroll;
            var maxThumbTop;
            var trackHeight;
            var thumbHeight;


             if (!target) return;
        if (categories === null) {
            value = extractJsonArrayAfterMwConfigKey(text, 'wgCategories');
             if (Array.isArray(value)) categories = value;
        }


             e.preventDefault();
        if (hiddenCategories === null) {
             e.stopPropagation();
             value = extractJsonArrayAfterMwConfigKey(text, 'wgHiddenCategories');
             if (Array.isArray(value)) hiddenCategories = value;
        }


            startY = e.clientY;
        if (relevantPageName === null) {
            startScroll = target.scrollTop;
             value = extractJsonStringAfterMwConfigKey(text, 'wgRelevantPageName');
             maxScroll = Math.max(1, target.scrollHeight - target.clientHeight);
             if (value !== null) relevantPageName = value;
             trackHeight = track ? track.clientHeight : 0;
        }
            thumbHeight = thumb.offsetHeight || 0;
            maxThumbTop = Math.max(1, trackHeight - thumbHeight);


             bar.classList.add('is-dragging');
        if (pageName === null) {
             value = extractJsonStringAfterMwConfigKey(text, 'wgPageName');
            if (value !== null) pageName = value;
        }
    }


            function onMove(moveEvent) {
    mw.config.set('wgCategories', Array.isArray(categories) ? categories : []);
                var dy = moveEvent.clientY - startY;
    mw.config.set('wgHiddenCategories', Array.isArray(hiddenCategories) ? hiddenCategories : []);
                target.scrollTop = startScroll + (dy / maxThumbTop) * maxScroll;
                updateClbiCustomScrollbar(bar);
                moveEvent.preventDefault();
            }


            function onUp() {
    if (relevantPageName !== null) {
                bar.classList.remove('is-dragging');
        mw.config.set('wgRelevantPageName', relevantPageName);
                document.removeEventListener('mousemove', onMove);
    } else if (pageName !== null) {
                document.removeEventListener('mouseup', onUp);
        mw.config.set('wgRelevantPageName', pageName);
            }
 
            document.addEventListener('mousemove', onMove);
            document.addEventListener('mouseup', onUp);
        });
     }
     }


     if (!scrollEl.__clbiCustomScrollbarBound) {
     CLBI_CATLINKS_FETCH_TOKEN += 1;
        scrollEl.__clbiCustomScrollbarBound = true;
}
        scrollEl.addEventListener('scroll', function () {
            if (scrollEl.__clbiCustomScrollbar) {
                updateClbiCustomScrollbar(scrollEl.__clbiCustomScrollbar);
            }
        }, { passive: true });
    }


    scrollEl.__clbiCustomScrollbar = bar;
// SPA 네비게이션
    updateClbiCustomScrollbar(bar);
function shouldSkip(url) {
 
     return url.match(/action=edit|action=submit|action=history|action=delete|action=protect|action=purge|특수:로그인|특수:로그아웃|Special:UserLogin|Special:UserLogout|특수:사용자정보|특수:비밀번호바꾸기|uselang=/);
     return bar;
}
}


function updateClbiCustomScrollbar(bar) {
$(function() {
     var scrollEl = bar && bar.__clbiScrollTarget;
     if (window._spaInitialized) return;
    var track = bar ? bar.querySelector('.clbi-custom-scroll-track') : null;
     window._spaInitialized = true;
     var thumb = bar ? bar.querySelector('.clbi-custom-scroll-thumb') : null;
    var maxScroll;
    var trackHeight;
    var thumbHeight;
    var maxTop;
    var top;


     if (!bar || !scrollEl || !track || !thumb) return;
     function isInternal(url) {
        var a = document.createElement('a');
        a.href = url;
        return a.hostname === window.location.hostname;
    }


     maxScroll = scrollEl.scrollHeight - scrollEl.clientHeight;
     function getCachedSpaPageHtml(url) {
    if (maxScroll <= 1) {
         if (!window.EntryStore || typeof window.EntryStore.getTextSync !== 'function') return '';
         bar.classList.add('is-hidden');
         return window.EntryStore.getTextSync(url) || window.EntryStore.getTextSync(String(url || '').replace(/^https?:\/\/[^/]+/i, '')) || '';
         return;
     }
     }


     bar.classList.remove('is-hidden');
     function fetchSpaPageHtml(url) {
        var cached = getCachedSpaPageHtml(url);
        if (cached) return Promise.resolve(cached);
        return fetch(url, { credentials: 'same-origin', cache: 'force-cache' }).then(function(res) {
            return res.text();
        });
    }


     trackHeight = Math.max(1, track.clientHeight || 1);
     function prepareDetachedEntryContent(newContent) {
    thumbHeight = Math.max(12, Math.floor((scrollEl.clientHeight / Math.max(scrollEl.scrollHeight, 1)) * trackHeight));
        /*
    thumbHeight = Math.min(trackHeight, thumbHeight);
        Initial boot prepares entry artifacts; SPA is only allowed to consume them.
    maxTop = Math.max(0, trackHeight - thumbHeight);
        This hook runs while the fetched page is still detached, before the user sees it.
     top = maxScroll > 0 ? Math.round((scrollEl.scrollTop / maxScroll) * maxTop) : 0;
        It must stay synchronous or already-resolved: if a subsystem cannot prepare from
        EntryStore immediately, it should leave the old fallback path in place instead of
        opening BootGate during SPA.
        */
        try {
            if (window.NationsPanel && typeof window.NationsPanel.prepareContentForEntry === 'function') {
                window.NationsPanel.prepareContentForEntry(newContent);
            }
        } catch (err) {
            console.warn('entry content preparation failed:', err);
        }
     }


     thumb.style.height = thumbHeight + 'px';
     function loadPage(url) {
    thumb.style.transform = 'translateY(' + top + 'px)';
        invalidateProfileRender();
}


function initClbiCustomDocumentScrollbars() {
        return fetchSpaPageHtml(url)
    var existing = Array.prototype.slice.call(document.querySelectorAll('.clbi-custom-scrollbar'));
            .then(function(html) {
    var targets = getClbiDocumentScrollTargets();
                var parser = new DOMParser();
    var liveBars = [];
                var doc = parser.parseFromString(html, 'text/html');


    if (!targets.length) {
                var scripts = doc.querySelectorAll('script');
        existing.forEach(function (bar) { bar.remove(); });
                for (var i = 0; i < scripts.length; i++) {
        return;
                    var src = scripts[i].textContent;
    }


    targets.forEach(function (scrollEl) {
                    if (src.indexOf('wgNamespaceNumber') !== -1) {
        var well = getClbiOuterWellForScroll(scrollEl);
                        var match = src.match(/"wgNamespaceNumber":(-?\d+)/);
        var bar;
                        if (match) mw.config.set('wgNamespaceNumber', parseInt(match[1], 10));


        if (!well) return;
                        var matchTitle = src.match(/"wgTitle":"([^"]+)"/);
        bar = buildClbiCustomScrollbar(well, scrollEl);
                        if (matchTitle) mw.config.set('wgTitle', matchTitle[1]);
        liveBars.push(bar);
    });


    existing.forEach(function (bar) {
                        var matchPage = src.match(/"wgPageName":"([^"]+)"/);
        if (liveBars.indexOf(bar) === -1) bar.remove();
                        if (matchPage) mw.config.set('wgPageName', matchPage[1]);
    });


    window.requestAnimationFrame(function () {
                        var matchArticle = src.match(/"wgArticleId":(\d+)/);
        liveBars.forEach(updateClbiCustomScrollbar);
                        if (matchArticle) {
    });
                            mw.config.set('wgArticleId', parseInt(matchArticle[1], 10));
                        } else {
                            mw.config.set('wgArticleId', 0);
                        }


    setTimeout(function () {
                        var matchIsMainPage = src.match(/"wgIsMainPage":(true|false)/);
        liveBars.forEach(updateClbiCustomScrollbar);
                        if (matchIsMainPage) {
    }, 120);
                            mw.config.set('wgIsMainPage', matchIsMainPage[1] === 'true');
}
                        } else {
                            mw.config.set('wgIsMainPage', false);
                        }


if (!window.__clbiCustomScrollbarResizeBound) {
                        var matchSpecial = src.match(/"wgCanonicalSpecialPageName":"([^"]+)"/);
    window.__clbiCustomScrollbarResizeBound = true;
                        if (matchSpecial) {
    window.addEventListener('resize', function () {
                            mw.config.set('wgCanonicalSpecialPageName', matchSpecial[1]);
        setTimeout(initClbiCustomDocumentScrollbars, 60);
                        } else {
    });
                            mw.config.set('wgCanonicalSpecialPageName', false);
}
                        }
                        break;
                    }
                }


                syncCatlinksConfigFromSpaDocument(doc);


// 시간 계산 함수
                var newContent = doc.querySelector('.liberty-content-main');
function timeAgo(timestamp) {
                var newTitle = doc.querySelector('.mw-page-title-main');
    var now = new Date();
                var newHead = doc.querySelector('title');
    var date = new Date(timestamp);
                var newHeader = doc.querySelector('.liberty-content-header');
    var diff = Math.floor((now - date) / 1000);


    if (diff < 60) return diff + '초 전';
                if (newContent) {
    if (diff < 3600) return Math.floor(diff / 60) + '분 전';
                    prepareDetachedEntryContent(newContent);
    if (diff < 86400) return Math.floor(diff / 3600) + '시간 전';
                    prepareSpaCatlinksBeforeInsert(newContent);
    return Math.floor(diff / 86400) + '일 전';
                    $('#side-toc-box').remove();
}
                    $('.profile-card').remove();
                    $('.user-profile-portal').removeClass('user-profile-portal');
                    $('.liberty-content-main').html(newContent.innerHTML);
                    $('.profile-card').remove();
                    try {
                        if (window.Decorations && typeof window.Decorations.renderPrepared === 'function') window.Decorations.renderPrepared();
                        else if (window.CLBI_DECORATIONS && typeof window.CLBI_DECORATIONS.renderPrepared === 'function') window.CLBI_DECORATIONS.renderPrepared();
                    } catch (err) {}
                    $('body').removeClass('page-loading');
                }


// 펼접 토글
                if (newTitle) {
// 펼접 토글
                    $('.mw-page-title-main').html(newTitle.innerHTML);
function getFoldTexts() {
                }
    var lang = getCurrentLang();
    return (window.LANG && window.LANG[lang])
        ? window.LANG[lang]
        : (window.LANG ? window.LANG.ko : { expand: '펼치기', collapse: '접기' });
}


function refreshOpenAncestors($start) {
                if (newHead) {
    $start.parents('[id^="collapsible"]').each(function () {
                    document.title = newHead.textContent;
        var $parent = $(this);
                }
        if (!$parent.hasClass('folding-open')) return;


        // 이미 fully open 상태면 굳이 다시 잠그지 않음
                if (newHeader) {
        if ($parent.data('fold-state') === 'open') {
                    $('.liberty-content-header').html(newHeader.innerHTML);
            return;
                }
        }


        $parent.css('max-height', this.scrollHeight + 'px');
                if (typeof window.normalizeClbiShellDomOrder === 'function') window.normalizeClbiShellDomOrder();
    });
                window.scrollTo(0, 0);
}
                mw.hook('wikipage.content').fire($('.liberty-content-main'));
                applyMainPageStyle();
                initClbiCustomDocumentScrollbars();
                initCategoryNavIfAvailable(document);


function bindInnerResizeUpdates($target) {
                if (window.ProgressSystemWebUi && typeof window.ProgressSystemWebUi.handleSpaPageView === 'function') {
    // 이미지 늦게 로드될 때 높이 갱신
                    window.ProgressSystemWebUi.handleSpaPageView();
    $target.find('img').off('.foldimg').on('load.foldimg', function () {
                } else if (window.ProgressSystemWebUi && typeof window.ProgressSystemWebUi.boot === 'function') {
        if ($target.hasClass('folding-open')) {
                    window.ProgressSystemWebUi.boot('spa');
            if ($target.data('fold-state') !== 'open') {
                }
                $target.css('max-height', $target[0].scrollHeight + 'px');
            }
            refreshOpenAncestors($target);
        }
    });
}


function openFold($target, $btn) {
                $('#side-toc-box').remove();
    var t = getFoldTexts();
                setTimeout(moveTocToLeftSidebar, 100);
                setTimeout(moveTocToLeftSidebar, 500);
                setTimeout(moveTocToLeftSidebar, 1200);


    $target.data('fold-state', 'opening');
                mw.loader.using(['mediawiki.api']).then(function() {
    $target.addClass('folding-open');
                    initProfile();
                    moveTocToLeftSidebar();
                });
            })
            .catch(function (err) {
                console.error('SPA page load failed:', err);
                $('body').removeClass('page-loading');
            });
    }


    // 열린 뒤 자연 확장 가능하게 만들기 위해 먼저 px로 열기
// 목차 링크는 전용 처리
    $target.css('max-height', '0px');
$(document).on('click', '#side-toc-box a, #toc a, .toc a', function(e) {
     $target[0].offsetHeight;
     var href = $(this).attr('href');
     $target.css('max-height', $target[0].scrollHeight + 'px');
     if (!href || href.charAt(0) !== '#') return;


     $btn.text(t.collapse);
     var rawId = href.slice(1);
    if (!rawId) return;


     bindInnerResizeUpdates($target);
     var decodedId = rawId;


     // 바깥 펼접 즉시 갱신
     try {
     refreshOpenAncestors($target);
        decodedId = decodeURIComponent(rawId);
     } catch (err) {
        decodedId = rawId;
    }


     // 전환 끝나면 none으로 풀어서 중첩 펼접/동적 내용 증가를 자연스럽게 허용
     var target = document.getElementById(decodedId);
    $target.off('transitionend.foldopen').on('transitionend.foldopen', function (e) {
        if (e.target !== this) return;
        if (!$target.hasClass('folding-open')) return;


         $target.css('max-height', 'none');
    if (!target && window.CSS && CSS.escape) {
        $target.data('fold-state', 'open');
         target = document.querySelector('#' + CSS.escape(decodedId));
    }
 
    if (!target) return;
 
    e.preventDefault();
    e.stopPropagation();
 
    var scrollTarget = target.closest('h2, h3') || target;


         refreshOpenAncestors($target);
    scrollTarget.scrollIntoView({
         behavior: 'auto',
        block: 'start'
     });
     });


     // 늦게 렌더되는 콘텐츠 대응
     history.replaceState(null, '', '#' + rawId);
    requestAnimationFrame(function () {
});
        if ($target.hasClass('folding-open') && $target.data('fold-state') !== 'open') {
            $target.css('max-height', $target[0].scrollHeight + 'px');
            refreshOpenAncestors($target);
        }
    });


     setTimeout(function () {
     /* 길라잡이는 문서 링크가 아니라 대문 본문 화면 탭이다. */
         if ($target.hasClass('folding-open') && $target.data('fold-state') !== 'open') {
    $(document).on('click', '.portal-guide-anchor[data-category-key="guide"]', function(e) {
            $target.css('max-height', $target[0].scrollHeight + 'px');
         if (e.which && e.which !== 1) return;
            refreshOpenAncestors($target);
        if (e.button && e.button !== 0) return;
        }
        if (e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) return;
    }, 80);


    setTimeout(function () {
         if (window.BottomGuideNav && typeof window.BottomGuideNav.toggle === 'function') {
         if ($target.hasClass('folding-open') && $target.data('fold-state') !== 'open') {
             e.preventDefault();
             $target.css('max-height', $target[0].scrollHeight + 'px');
            e.stopImmediatePropagation();
             refreshOpenAncestors($target);
             window.BottomGuideNav.toggle();
         }
         }
     }, 220);
     });
}


function closeFold($target, $btn) {
    $(document).on('click', 'a', function(e) {
    var t = getFoldTexts();
        // 휠 클릭, 새 탭 열기, 보조키 이동은 브라우저 기본 동작을 유지한다.
        if (e.which && e.which !== 1) return;
        if (e.button && e.button !== 0) return;
        if (e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) return;


    // none 상태에서 닫으면 transition이 안 되므로 실제 높이로 고정
        /* 길라잡이 화면 탭은 위 전용 처리 외에는 SPA 문서 이동 대상으로 삼지 않는다. */
    if ($target.css('max-height') === 'none' || $target.data('fold-state') === 'open') {
        if ($(this).is('.portal-guide-anchor[data-category-key="guide"]')) return;
        $target.css('max-height', $target[0].scrollHeight + 'px');
    } else {
        $target.css('max-height', $target[0].scrollHeight + 'px');
    }


    $target.data('fold-state', 'closing');
        var href = $(this).attr('href');
    $target[0].offsetHeight;
        if (!href) return;
    $target.css('max-height', '0px');
    $target.removeClass('folding-open');


    $btn.text(t.expand);
        // 목차 링크는 별도 핸들러에서 처리
        if ($(this).closest('#side-toc-box, #toc, .toc').length) return;


    refreshOpenAncestors($target);
        // 단순 해시 링크는 SPA 가로채기 제외
        if (href.startsWith('#')) return;


    setTimeout(function () {
        var link = document.createElement('a');
         refreshOpenAncestors($target);
         link.href = href;
         $target.data('fold-state', 'closed');
 
    }, 250);
        var samePath = decodeURIComponent(link.pathname) === decodeURIComponent(window.location.pathname);
}
         var sameSearch = (link.search || '') === (window.location.search || '');


$(function () {
         if (link.hash && samePath && sameSearch) return;
    $(document)
        .off('click.clbiToggle')
         .on('click.clbiToggle', '.toggleBtn', function () {
            var $btn = $(this);
            var targetId = $btn.data('target');
            var $target = $('#' + targetId);
            if (!$target.length) return;


            var scrollY = window.scrollY;
        var currentBase = window.location.href.split('#')[0];
        var targetBase = link.href.split('#')[0];


            if ($target.hasClass('folding-open')) {
        if (link.hash && currentBase === targetBase) return;
                closeFold($target, $btn);
            } else {
                openFold($target, $btn);
            }


            window.scrollTo(0, scrollY);
        if (!isInternal(href)) return;
         });
         if (shouldSkip(href)) return;
});


// ========== 프로필 시스템 ==========
        e.preventDefault();
function initProfile() {
        playStaticSound();
    $('.profile-card').remove();
        /*
    $('.user-profile-portal').removeClass('user-profile-portal');
        SPA must remain a consumer phase.  If the target page HTML was prepared by
        the first-load boot pack, do not show the legacy page-loading veil.  The
        route will consume cached HTML and detached entry artifacts before insertion.
        */
        if (getCachedSpaPageHtml(href)) {
            $('body').removeClass('page-loading');
        } else {
            $('body').addClass('page-loading');
        }
        history.pushState(null, '', href);
        loadPage(href);
    });


     var token = ++PROFILE_RENDER_TOKEN;
     window.addEventListener('popstate', function() {
    var ns = mw.config.get('wgNamespaceNumber');
        loadPage(window.location.href);
    var title = mw.config.get('wgTitle');
     });
     var specialPage = mw.config.get('wgCanonicalSpecialPageName');
});
    var isProfileSettings = specialPage === '사용자정보';


    $('body').toggleClass('user-profile-page', ns === 2);
    $('body').toggleClass('user-profile-settings-page', isProfileSettings);


    if (ns === 2) {
        var profileUser = title.split('/')[0];
        renderProfile(profileUser, token);
    }


     if (isProfileSettings) {
/* ========== CLBI Custom Document Scrollbar ========== */
         initUserProfilePage();
function isGeneralDocumentView() {
    }
    var body = document.body;
     if (!body) return false;
 
    return body.classList.contains('action-view') &&
        !body.classList.contains('clbi-main-page') &&
        !body.classList.contains('clbi-system-doc-page') &&
        !body.classList.contains('backend-system-page') &&
        !body.classList.contains('user-profile-page') &&
         !body.classList.contains('user-profile-settings-page');
}
}


function renderProfile(username, token) {
function getClbiDocumentScrollTargets() {
     var api = new mw.Api();
     if (!isGeneralDocumentView()) return [];
    api.get({
        action: 'query',
        list: 'users',
        ususers: username,
        usprop: 'editcount'
    }).then(function(data) {
        if (token !== PROFILE_RENDER_TOKEN) return;
        if (mw.config.get('wgNamespaceNumber') !== 2) return;


        var currentTitle = String(mw.config.get('wgTitle') || '').split('/')[0];
    return Array.prototype.slice.call(document.querySelectorAll(
         if (currentTitle !== username) return;
         '.liberty-content-main > #mw-content-text .mw-parser-output, ' +
 
         '.liberty-content-main > .mw-body-content .mw-parser-output'
        var user = data.query.users[0];
    )).filter(function (el, index, list) {
        var contentEl = document.getElementById('mw-content-text');
         return el && list.indexOf(el) === index;
         if (!contentEl) return;
 
        var pageContent = contentEl.querySelector('.mw-parser-output') || contentEl;
         injectProfileCard(username, user, pageContent);
     });
     });
}
}


function injectProfileCard(username, userData, container) {
function getClbiOuterWellForScroll(scrollEl) {
     var isOwnPage = mw.config.get('wgUserName') === username;
     var main = scrollEl ? scrollEl.closest('.liberty-content-main') : null;
     var editCount = (userData && userData.editcount) ? userData.editcount : 0;
    var children;
    var i;
     var child;
 
    if (!main) return null;


     function escapeHtml(value) {
     children = Array.prototype.slice.call(main.children || []);
        return String(value == null ? '' : value)
    for (i = 0; i < children.length; i += 1) {
             .replace(/&/g, '&amp;')
        child = children[i];
             .replace(/</g, '&lt;')
        if (
            .replace(/>/g, '&gt;')
             child &&
             .replace(/"/g, '&quot;')
             (child.id === 'mw-content-text' || child.classList.contains('mw-body-content')) &&
             .replace(/'/g, '&#039;');
             child.contains(scrollEl)
        ) {
             return child;
        }
     }
     }


     container.classList.add('user-profile-portal');
     return scrollEl.parentElement || null;
}


    var safeUsername = escapeHtml(username);
function buildClbiCustomScrollbar(well, scrollEl) {
     var avatarSrc = '/index.php?title=특수:Redirect/file/Pfp-' + encodeURIComponent(username) + '.png&width=220';
     var bar = well.querySelector(':scope > .clbi-custom-scrollbar');
     var fallbackSrc = '/index.php?title=특수:Redirect/file/Pfp-default.png&width=220';
     var up;
    var editBtn = isOwnPage
    var track;
        ? '<a href="/index.php/특수:사용자정보" class="profile-edit-btn"><span class="profile-edit-label">프로필 수정</span><span class="profile-edit-arrow">›</span></a>'
    var thumb;
         : '';
    var down;
 
    if (!bar) {
        bar = document.createElement('div');
        bar.className = 'clbi-custom-scrollbar';
        bar.setAttribute('aria-hidden', 'true');
        bar.innerHTML =
            '<div class="clbi-custom-scroll-arrow clbi-custom-scroll-arrow-up" data-scroll-arrow="up"></div>' +
            '<div class="clbi-custom-scroll-track"><div class="clbi-custom-scroll-thumb"></div></div>' +
            '<div class="clbi-custom-scroll-arrow clbi-custom-scroll-arrow-down" data-scroll-arrow="down"></div>';
         well.appendChild(bar);
    }
 
    bar.__clbiScrollTarget = scrollEl;
    up = bar.querySelector('.clbi-custom-scroll-arrow-up');
    track = bar.querySelector('.clbi-custom-scroll-track');
    thumb = bar.querySelector('.clbi-custom-scroll-thumb');
    down = bar.querySelector('.clbi-custom-scroll-arrow-down');


     var progressHtml = isOwnPage
     if (up && !up.__clbiBound) {
         ? '<div class="profile-page-progress is-syncing" data-profile-progress>' +
        up.__clbiBound = true;
             '<div class="profile-section-title">LEVEL RECORD</div>' +
         up.addEventListener('mousedown', function (e) {
             '<div class="profile-page-progress-body">' +
             e.preventDefault();
                '<div class="profile-page-progress-row">' +
             e.stopPropagation();
                    '<span class="profile-page-level">SYNC</span>' +
            if (bar.__clbiScrollTarget) bar.__clbiScrollTarget.scrollTop -= 48;
                    '<span class="profile-page-total-xp">— XP</span>' +
             updateClbiCustomScrollbar(bar);
                '</div>' +
         });
                '<div class="profile-page-xp-bar" aria-hidden="true"><div class="profile-page-xp-fill"></div></div>' +
    }
                '<div class="profile-page-progress-sub">SYNCING</div>' +
                '<div class="profile-page-progress-meta">TODAY — · DISCOVERED —</div>' +
             '</div>' +
         '</div>'
        : '';


     var card = document.createElement('div');
     if (down && !down.__clbiBound) {
    card.className = 'profile-card profile-page-console';
        down.__clbiBound = true;
    card.innerHTML =
        down.addEventListener('mousedown', function (e) {
        '<div class="profile-card-titlebar">' +
             e.preventDefault();
             '<span>USER PROFILE</span>' +
             e.stopPropagation();
             '<span>OFFICIAL ARCHIVE</span>' +
             if (bar.__clbiScrollTarget) bar.__clbiScrollTarget.scrollTop += 48;
        '</div>' +
             updateClbiCustomScrollbar(bar);
        '<div class="profile-card-body">' +
         });
             '<div class="profile-identity-row">' +
    }
                '<div class="profile-avatar-bay">' +
                    '<img src="' + avatarSrc + '" onerror="this.onerror=null;this.src=\'' + fallbackSrc + '\';" alt="' + safeUsername + '">' +
                '</div>' +
                '<div class="profile-info-panel">' +
                    '<div class="profile-nameplate">' +
                        '<h2 class="profile-username">' + safeUsername + '</h2>' +
                        editBtn +
                    '</div>' +
                    '<div class="profile-name" data-field="name"></div>' +
                    '<div class="profile-role" data-field="role"></div>' +
                    '<div class="profile-discord" data-field="discord"></div>' +
                '</div>' +
             '</div>' +
            '<div class="profile-lower-grid">' +
                '<div class="profile-bio-panel">' +
                    '<div class="profile-section-title">BIOGRAPHY</div>' +
                    '<div class="profile-bio" data-field="bio"></div>' +
                '</div>' +
                '<div class="profile-stats-panel">' +
                    '<div class="profile-section-title">RECORD</div>' +
                    '<div class="profile-stats">' +
                        progressHtml +
                        '<div class="profile-stat-grid">' +
                            '<div class="profile-stat">' +
                                '<span class="clbi-stat-value">' + editCount + '</span>' +
                                '<span class="clbi-stat-label">수정 횟수</span>' +
                            '</div>' +
                            '<div class="profile-stat" data-contrib-pages-stat>' +
                                '<span class="clbi-stat-value" data-contrib-pages-value>SYNC</span>' +
                                '<span class="clbi-stat-label">기여 문서</span>' +
                            '</div>' +
                        '</div>' +
                        '<div class="profile-info-grid">' +
                            '<div class="profile-info-stat">' +
                                '<span class="profile-info-label">TIME</span>' +
                                '<span class="profile-info-value" data-profile-time>UTC --:--</span>' +
                            '</div>' +
                            '<div class="profile-info-stat">' +
                                '<span class="profile-info-label">LANGUAGE</span>' +
                                '<span class="profile-info-value" data-profile-language>—</span>' +
                            '</div>' +
                        '</div>' +
                    '</div>' +
                '</div>' +
            '</div>' +
         '</div>';


     $('.profile-card').remove();
     if (track && !track.__clbiBound) {
    container.insertBefore(card, container.firstChild);
        track.__clbiBound = true;
    loadProfileFields(username, card);
        track.addEventListener('mousedown', function (e) {
    loadProfileContributionPages(username, card);
            var rect;
    updateProfilePageEnvironment(card, null);
            var thumbRect;
            var target;
            var direction;


    if (isOwnPage) {
            if (e.target === thumb) return;
        loadProfileProgressForUserPage(card);
            e.preventDefault();
    }
            e.stopPropagation();
}


function getProfileLanguageLabel() {
            target = bar.__clbiScrollTarget;
    var lang = getCurrentLang();
            if (!target) return;
    return SIDEBAR_LANGUAGE_LABELS[lang] || (lang ? lang.toUpperCase() : '—');
}


function updateProfilePageEnvironment(card, summary) {
            rect = track.getBoundingClientRect();
    if (!card) return;
            thumbRect = thumb.getBoundingClientRect();
            direction = e.clientY < thumbRect.top ? -1 : 1;
            target.scrollTop += direction * Math.max(60, Math.floor(target.clientHeight * 0.82));
            updateClbiCustomScrollbar(bar);
        });
    }


     var timezone = summary && summary.timezone ? summary.timezone : 'UTC';
     if (thumb && !thumb.__clbiBound) {
    var timeEl = card.querySelector('[data-profile-time]');
        thumb.__clbiBound = true;
    var langEl = card.querySelector('[data-profile-language]');
        thumb.addEventListener('mousedown', function (e) {
            var target = bar.__clbiScrollTarget;
            var startY;
            var startScroll;
            var maxScroll;
            var maxThumbTop;
            var trackHeight;
            var thumbHeight;


    if (timeEl) {
            if (!target) return;
        try {
            timeEl.textContent = timezone + ' ' + new Intl.DateTimeFormat('ko-KR', {
                hour: '2-digit',
                minute: '2-digit',
                hour12: false,
                timeZone: timezone
            }).format(new Date());
        } catch (err) {
            timeEl.textContent = 'UTC ' + new Intl.DateTimeFormat('ko-KR', {
                hour: '2-digit',
                minute: '2-digit',
                hour12: false,
                timeZone: 'UTC'
            }).format(new Date());
        }
    }


    if (langEl) {
            e.preventDefault();
        langEl.textContent = getProfileLanguageLabel();
            e.stopPropagation();
    }
}


function loadProfileContributionPages(username, card) {
            startY = e.clientY;
    if (!username || !card) return;
            startScroll = target.scrollTop;
    if (!mw.loader || typeof mw.loader.using !== 'function') return;
            maxScroll = Math.max(1, target.scrollHeight - target.clientHeight);
            trackHeight = track ? track.clientHeight : 0;
            thumbHeight = thumb.offsetHeight || 0;
            maxThumbTop = Math.max(1, trackHeight - thumbHeight);


    var valueEl = card.querySelector('[data-contrib-pages-value]');
            bar.classList.add('is-dragging');
    if (valueEl) valueEl.textContent = 'SYNC';


    mw.loader.using(['mediawiki.api']).then(function () {
            function onMove(moveEvent) {
        var api = new mw.Api();
                var dy = moveEvent.clientY - startY;
        var pages = Object.create(null);
                target.scrollTop = startScroll + (dy / maxThumbTop) * maxScroll;
        var cont = {};
                updateClbiCustomScrollbar(bar);
        var guard = 0;
                moveEvent.preventDefault();
            }


        function requestNext() {
            function onUp() {
             guard++;
                bar.classList.remove('is-dragging');
                document.removeEventListener('mousemove', onMove);
                document.removeEventListener('mouseup', onUp);
             }


             var params = Object.assign({
             document.addEventListener('mousemove', onMove);
                action: 'query',
            document.addEventListener('mouseup', onUp);
                list: 'usercontribs',
        });
                ucuser: username,
    }
                ucnamespace: 0,
                ucprop: 'title',
                uclimit: 'max',
                format: 'json',
                formatversion: 2
            }, cont);


            return api.get(params).then(function (data) {
    if (!scrollEl.__clbiCustomScrollbarBound) {
                 var rows = data && data.query && data.query.usercontribs ? data.query.usercontribs : [];
        scrollEl.__clbiCustomScrollbarBound = true;
        scrollEl.addEventListener('scroll', function () {
            if (scrollEl.__clbiCustomScrollbar) {
                 updateClbiCustomScrollbar(scrollEl.__clbiCustomScrollbar);
            }
        }, { passive: true });
    }


                rows.forEach(function (row) {
    scrollEl.__clbiCustomScrollbar = bar;
                    if (row && row.title) pages[row.title] = true;
    updateClbiCustomScrollbar(bar);
                });


                if (data && data.continue && data.continue.uccontinue && guard < 40) {
    return bar;
                    cont = data.continue;
}
                    return requestNext();
                }


                if (valueEl) valueEl.textContent = Object.keys(pages).length;
function updateClbiCustomScrollbar(bar) {
            });
    var scrollEl = bar && bar.__clbiScrollTarget;
        }
    var track = bar ? bar.querySelector('.clbi-custom-scroll-track') : null;
    var thumb = bar ? bar.querySelector('.clbi-custom-scroll-thumb') : null;
    var maxScroll;
    var trackHeight;
    var thumbHeight;
    var maxTop;
    var top;


        requestNext().fail(function () {
    if (!bar || !scrollEl || !track || !thumb) return;
            if (valueEl) valueEl.textContent = '—';
        });
    });
}


function loadProfileProgressForUserPage(card) {
    maxScroll = scrollEl.scrollHeight - scrollEl.clientHeight;
     if (!mw.config.get('wgUserName')) return;
    if (maxScroll <= 1) {
     if (!mw.loader || typeof mw.loader.using !== 'function') return;
        bar.classList.add('is-hidden');
        return;
     }
 
    bar.classList.remove('is-hidden');
 
     trackHeight = Math.max(1, track.clientHeight || 1);
    thumbHeight = Math.max(12, Math.floor((scrollEl.clientHeight / Math.max(scrollEl.scrollHeight, 1)) * trackHeight));
    thumbHeight = Math.min(trackHeight, thumbHeight);
    maxTop = Math.max(0, trackHeight - thumbHeight);
    top = maxScroll > 0 ? Math.round((scrollEl.scrollTop / maxScroll) * maxTop) : 0;


     mw.loader.using(['mediawiki.api']).then(function () {
     thumb.style.height = thumbHeight + 'px';
        var api = new mw.Api();
    thumb.style.transform = 'translateY(' + top + 'px)';
        api.get({
            action: 'progress_summary',
            format: 'json',
            formatversion: 2
        }).then(function (data) {
            var payload = data && data.progress_summary;
            if (!payload || !payload.available || !payload.summary) return;
            updateUserPageProgress(card, payload.summary);
            updateProfilePageEnvironment(card, payload.summary);
        });
    });
}
}


function updateUserPageProgress(card, summary) {
function initClbiCustomDocumentScrollbars() {
     var panel = card.querySelector('[data-profile-progress]');
     var existing = Array.prototype.slice.call(document.querySelectorAll('.clbi-custom-scrollbar'));
     if (!panel || !summary) return;
     var targets = getClbiDocumentScrollTargets();
    var liveBars = [];


     var level = summary.level || 1;
     if (!targets.length) {
    var totalXp = summary.totalXp || 0;
        existing.forEach(function (bar) { bar.remove(); });
    var xpIntoLevel = summary.xpIntoLevel || 0;
        return;
    var xpForNext = summary.xpForNextLevel || 1;
     }
    var percent = Math.max(0, Math.min(100, summary.progressPercent || 0));
    var isMaxLevel = !!summary.isMaxLevel;
     var dailyXp = summary.dailyXp || 0;
    var discoveries = summary.discoveryCount || 0;


     panel.classList.remove('is-syncing');
     targets.forEach(function (scrollEl) {
    panel.classList.toggle('is-max-level', isMaxLevel);
        var well = getClbiOuterWellForScroll(scrollEl);
        var bar;


    var levelEl = panel.querySelector('.profile-page-level');
        if (!well) return;
    var totalEl = panel.querySelector('.profile-page-total-xp');
        bar = buildClbiCustomScrollbar(well, scrollEl);
    var fillEl = panel.querySelector('.profile-page-xp-fill');
        liveBars.push(bar);
    var subEl = panel.querySelector('.profile-page-progress-sub');
     });
     var metaEl = panel.querySelector('.profile-page-progress-meta');


     if (levelEl) levelEl.textContent = (isMaxLevel ? 'MAX ' : 'LVL ') + level;
     existing.forEach(function (bar) {
     if (totalEl) totalEl.textContent = totalXp + ' XP';
        if (liveBars.indexOf(bar) === -1) bar.remove();
     if (fillEl) fillEl.style.width = percent + '%';
     });
     if (subEl) subEl.textContent = isMaxLevel ? 'MAX LEVEL' : (xpIntoLevel + ' / ' + xpForNext + ' TO NEXT');
 
     if (metaEl) metaEl.textContent = 'TODAY ' + dailyXp + ' XP · DISCOVERED ' + discoveries;
    window.requestAnimationFrame(function () {
        liveBars.forEach(updateClbiCustomScrollbar);
     });
 
     setTimeout(function () {
        liveBars.forEach(updateClbiCustomScrollbar);
     }, 120);
}
}


function loadProfileFields(username, card) {
if (!window.__clbiCustomScrollbarResizeBound) {
     var api = new mw.Api();
     window.__clbiCustomScrollbarResizeBound = true;
     api.get({
     window.addEventListener('resize', function () {
        action: 'userprofile',
         setTimeout(initClbiCustomDocumentScrollbars, 60);
        user: username
    }).then(function(data) {
         var profile = data.userprofile;
        updateProfileFields(card, {
            name: profile.name || '',
            discord: profile.discord || '',
            role: profile.role || '',
            bio: profile.bio || ''
        });
    }).fail(function() {
        updateProfileFields(card, {
            name: '',
            discord: '',
            role: '',
            bio: ''
        });
     });
     });
}
}


function updateProfileFields(card, data) {
    var nameEl = card.querySelector('[data-field="name"]');
    var roleEl = card.querySelector('[data-field="role"]');
    var discordEl = card.querySelector('[data-field="discord"]');
    var bioEl = card.querySelector('[data-field="bio"]');
    if (nameEl) nameEl.textContent = data.name || '';
    if (roleEl) roleEl.textContent = data.role || '';
    if (discordEl) discordEl.textContent = data.discord ? ('디스코드: ' + data.discord) : '';
    if (bioEl) bioEl.textContent = data.bio || '';
}
// ========== 프로필 시스템 끝 ==========


// ========== 알림 시스템 ==========
// 시간 계산 함수
function ensureNotificationPopup() {
function timeAgo(timestamp) {
     if (document.getElementById('clbi-notification-popup')) return;
     var now = new Date();
    var date = new Date(timestamp);
    var diff = Math.floor((now - date) / 1000);


     var popup = document.createElement('div');
     if (diff < 60) return diff + '초 전';
     popup.id = 'clbi-notification-popup';
     if (diff < 3600) return Math.floor(diff / 60) + '분 전';
     popup.style.cssText =
     if (diff < 86400) return Math.floor(diff / 3600) + '시간 전';
        'display:none;position:fixed;z-index:99999;width:320px;max-height:420px;' +
    return Math.floor(diff / 86400) + '일 전';
        'background:#0a0909;border:2px solid #854369;border-radius:5px;' +
}
        'box-shadow:0 0 0 1px #1a1a1a, 0 8px 24px rgba(0,0,0,0.55);overflow:hidden;';


     popup.innerHTML =
// 펼접 토글
        '<div style="padding:10px 12px;border-bottom:2px solid #854369;background:linear-gradient(to bottom, #171114 0%, #0a0909 100%);color:#E2E2E2;font-size:13px;font-weight:700;display:flex;align-items:center;justify-content:space-between;gap:8px;">' +
// 펼접 토글
            '<span>알림</span>' +
function getFoldTexts() {
            '<button type="button" id="clbi-notification-readall" style="background:#171717;border:1px solid #854369;border-radius:6px;color:#E2E2E2;font-size:11px;font-weight:700;padding:4px 8px;cursor:pointer;">전체 읽음</button>' +
     var lang = getCurrentLang();
         '</div>' +
    return (window.LANG && window.LANG[lang])
         '<div id="clbi-notification-list" style="max-height:320px;overflow-y:auto;padding:8px 0;color:#E2E2E2;font-size:12px;">불러오는 중...</div>' +
         ? window.LANG[lang]
        '<div style="padding:8px;border-top:1px solid #2a2a2a;background:#111;">' +
         : (window.LANG ? window.LANG.ko : { expand: '펼치기', collapse: '접기' });
            '<a href="/index.php?title=Special:Notifications" id="clbi-notification-more" style="display:block;width:100%;text-align:center;padding:8px 10px;border-radius:6px;background:#171717;border:1px solid #854369;color:#E2E2E2 !important;text-decoration:none !important;font-size:12px;font-weight:700;">더보기</a>' +
        '</div>';
 
    document.body.appendChild(popup);
}
}


function positionNotificationPopup() {
function refreshOpenAncestors($start) {
     var btn = document.getElementById('profile-quick-notifications');
     $start.parents('[id^="collapsible"]').each(function () {
    var popup = document.getElementById('clbi-notification-popup');
        var $parent = $(this);
    if (!btn || !popup) return;
        if (!$parent.hasClass('folding-open')) return;


    var rect = btn.getBoundingClientRect();
        // 이미 fully open 상태면 굳이 다시 잠그지 않음
    var top = rect.bottom + 6;
        if ($parent.data('fold-state') === 'open') {
    var left = rect.left + (rect.width / 2) - (popup.offsetWidth / 2);
            return;
        }


    if (left < 8) left = 8;
         $parent.css('max-height', this.scrollHeight + 'px');
    if (left + popup.offsetWidth > window.innerWidth - 8) {
     });
         left = window.innerWidth - popup.offsetWidth - 8;
}
     }
    if (top + popup.offsetHeight > window.innerHeight - 8) {
        top = Math.max(8, rect.top - popup.offsetHeight - 6);
    }


     popup.style.top = top + 'px';
function bindInnerResizeUpdates($target) {
    popup.style.left = left + 'px';
     // 이미지 늦게 로드될 때 높이 갱신
    $target.find('img').off('.foldimg').on('load.foldimg', function () {
        if ($target.hasClass('folding-open')) {
            if ($target.data('fold-state') !== 'open') {
                $target.css('max-height', $target[0].scrollHeight + 'px');
            }
            refreshOpenAncestors($target);
        }
    });
}
}


function parseNotificationItemsFromHtml(html) {
function openFold($target, $btn) {
     var parser = new DOMParser();
     var t = getFoldTexts();
    var doc = parser.parseFromString(html, 'text/html');


     var selectors = [
     $target.data('fold-state', 'opening');
        '.mw-echo-ui-notificationItemWidget',
    $target.addClass('folding-open');
        '.mw-echo-ui-notificationsInboxWidgetRow',
        '.echo-ui-notificationItemWidget',
        'li[data-notification-id]',
        '.mw-echo-notifications-list li'
    ];


     var items = [];
     // 열린 뒤 자연 확장 가능하게 만들기 위해 먼저 px로 열기
     for (var i = 0; i < selectors.length; i++) {
    $target.css('max-height', '0px');
        items = Array.prototype.slice.call(doc.querySelectorAll(selectors[i]));
    $target[0].offsetHeight;
         if (items.length) break;
     $target.css('max-height', $target[0].scrollHeight + 'px');
    }
 
    $btn.text(t.collapse);
 
    bindInnerResizeUpdates($target);
 
    // 바깥 펼접 즉시 갱신
    refreshOpenAncestors($target);
 
    // 전환 끝나면 none으로 풀어서 중첩 펼접/동적 내용 증가를 자연스럽게 허용
    $target.off('transitionend.foldopen').on('transitionend.foldopen', function (e) {
        if (e.target !== this) return;
         if (!$target.hasClass('folding-open')) return;


    return items.slice(0, 5).map(function(item) {
         $target.css('max-height', 'none');
         var link = item.querySelector('a[href]');
         $target.data('fold-state', 'open');
        var href = link ? link.getAttribute('href') : '/index.php?title=Special:Notifications';
         var text = (item.textContent || '').replace(/\s+/g, ' ').trim();


         var notificationId =
         refreshOpenAncestors($target);
            item.getAttribute('data-notification-id') ||
    });
            item.getAttribute('data-id') ||
            item.getAttribute('data-notification') ||
            '';


        if (!notificationId) {
    // 늦게 렌더되는 콘텐츠 대응
            var anyWithId = item.querySelector('[data-notification-id], [data-id], [data-notification]');
    requestAnimationFrame(function () {
            if (anyWithId) {
        if ($target.hasClass('folding-open') && $target.data('fold-state') !== 'open') {
                notificationId =
            $target.css('max-height', $target[0].scrollHeight + 'px');
                    anyWithId.getAttribute('data-notification-id') ||
             refreshOpenAncestors($target);
                    anyWithId.getAttribute('data-id') ||
                    anyWithId.getAttribute('data-notification') ||
                    '';
             }
         }
         }
    });


         if (href && href.indexOf('http') !== 0) {
    setTimeout(function () {
             href = href.charAt(0) === '/'
         if ($target.hasClass('folding-open') && $target.data('fold-state') !== 'open') {
                ? href
             $target.css('max-height', $target[0].scrollHeight + 'px');
                : '/index.php' + (href.charAt(0) === '?' ? href : '/' + href);
            refreshOpenAncestors($target);
         }
         }
    }, 80);


         return {
    setTimeout(function () {
             id: notificationId,
         if ($target.hasClass('folding-open') && $target.data('fold-state') !== 'open') {
             href: href,
             $target.css('max-height', $target[0].scrollHeight + 'px');
            text: text || '알림'
             refreshOpenAncestors($target);
         };
         }
     });
     }, 220);
}
}


function setNotificationIcon(hasItems) {
function closeFold($target, $btn) {
     var quickIcon = document.getElementById('profile-quick-notification-icon');
     var t = getFoldTexts();
    var svg = hasItems ? CLBI_SVG_BELL_DOT : CLBI_SVG_BELL;


     if (quickIcon) {
    // none 상태에서 닫으면 transition이 안 되므로 실제 높이로 고정
         quickIcon.innerHTML = svg;
     if ($target.css('max-height') === 'none' || $target.data('fold-state') === 'open') {
         quickIcon.classList.toggle('has-notifications', !!hasItems);
         $target.css('max-height', $target[0].scrollHeight + 'px');
    } else {
         $target.css('max-height', $target[0].scrollHeight + 'px');
     }
     }
}


function renderNotificationPopup(items) {
     $target.data('fold-state', 'closing');
     var list = document.getElementById('clbi-notification-list');
     $target[0].offsetHeight;
     var badge = document.getElementById('clbi-notification-badge');
    $target.css('max-height', '0px');
     if (!list) return;
     $target.removeClass('folding-open');


     if (!items || !items.length) {
     $btn.text(t.expand);
        list.innerHTML = '<div style="padding:14px 12px;color:#999;">표시할 알림이 없습니다.</div>';
        if (badge) badge.style.display = 'none';
        setNotificationIcon(false);
        return;
    }


     var html = '';
     refreshOpenAncestors($target);
    for (var i = 0; i < items.length; i++) {
        html +=
            '<a href="' + items[i].href + '" class="clbi-notification-item" data-notification-id="' + (items[i].id || '') + '" style="display:block;padding:10px 12px;color:#E2E2E2 !important;text-decoration:none !important;border-bottom:1px solid #1f1f1f;line-height:1.5;">' +
                items[i].text +
            '</a>';
    }
    list.innerHTML = html;


     if (badge) {
     setTimeout(function () {
         badge.textContent = items.length;
         refreshOpenAncestors($target);
         badge.style.display = 'block';
         $target.data('fold-state', 'closed');
     }
     }, 250);
    setNotificationIcon(true);
}
}


function loadNotificationsIntoPopup() {
$(function () {
     var list = document.getElementById('clbi-notification-list');
     $(document)
    if (list) {
        .off('click.clbiToggle')
        list.innerHTML = '<div style="padding:14px 12px;color:#999;">불러오는 중...</div>';
        .on('click.clbiToggle', '.toggleBtn', function () {
    }
            var $btn = $(this);
            var targetId = $btn.data('target');
            var $target = $('#' + targetId);
            if (!$target.length) return;
 
            var scrollY = window.scrollY;


    fetch('/index.php?title=Special:Notifications', { credentials: 'same-origin' })
            if ($target.hasClass('folding-open')) {
        .then(function(res) {
                closeFold($target, $btn);
            return res.text();
             } else {
        })
                openFold($target, $btn);
        .then(function(html) {
             var items = parseNotificationItemsFromHtml(html);
            renderNotificationPopup(items);
        })
        .catch(function(err) {
            console.error(err);
            if (list) {
                list.innerHTML = '<div style="padding:14px 12px;color:#999;">알림을 불러오지 못했습니다.</div>';
             }
             }
            window.scrollTo(0, scrollY);
         });
         });
}
});
 
// ========== 프로필 시스템 ==========
function initProfile() {
    $('.profile-card').remove();
    $('.user-profile-portal').removeClass('user-profile-portal');
 
    var token = ++PROFILE_RENDER_TOKEN;
    var ns = mw.config.get('wgNamespaceNumber');
    var title = mw.config.get('wgTitle');
    var specialPage = mw.config.get('wgCanonicalSpecialPageName');
    var isProfileSettings = specialPage === '사용자정보';


function markAllNotificationsRead() {
     $('body').toggleClass('user-profile-page', ns === 2);
     return new mw.Api().postWithToken('csrf', {
    $('body').toggleClass('user-profile-settings-page', isProfileSettings);
        action: 'echomarkread',
        list: 'all'
    });
}


function markNotificationReadById(notificationId) {
     if (ns === 2) {
     if (!notificationId) {
         var profileUser = title.split('/')[0];
         return $.Deferred().resolve().promise();
        renderProfile(profileUser, token);
     }
     }


     return new mw.Api().postWithToken('csrf', {
     if (isProfileSettings) {
         action: 'echomarkread',
         initUserProfilePage();
        list: notificationId
     }
     });
}
}


function initNotifications() {
function renderProfile(username, token) {
     var quickBtn = document.getElementById('profile-quick-notifications');
     var api = new mw.Api();
    api.get({
        action: 'query',
        list: 'users',
        ususers: username,
        usprop: 'editcount'
    }).then(function(data) {
        if (token !== PROFILE_RENDER_TOKEN) return;
        if (mw.config.get('wgNamespaceNumber') !== 2) return;


    if (!quickBtn) return;
        var currentTitle = String(mw.config.get('wgTitle') || '').split('/')[0];
        if (currentTitle !== username) return;


    ensureNotificationPopup();
        var user = data.query.users[0];
    loadNotificationsIntoPopup();
        var contentEl = document.getElementById('mw-content-text');
        if (!contentEl) return;


    $(document)
         var pageContent = contentEl.querySelector('.mw-parser-output') || contentEl;
         .off('click.clbiNotificationToggle')
         injectProfileCard(username, user, pageContent);
         .on('click.clbiNotificationToggle', '#profile-quick-notifications', function(e) {
    });
            e.preventDefault();
}
            e.stopPropagation();


            var popup = document.getElementById('clbi-notification-popup');
function injectProfileCard(username, userData, container) {
            if (!popup) return;
    var isOwnPage = mw.config.get('wgUserName') === username;
    var editCount = (userData && userData.editcount) ? userData.editcount : 0;


            if (popup.style.display === 'none' || popup.style.display === '') {
    function escapeHtml(value) {
                popup.style.display = 'block';
        return String(value == null ? '' : value)
                positionNotificationPopup();
            .replace(/&/g, '&amp;')
                loadNotificationsIntoPopup();
            .replace(/</g, '&lt;')
             } else {
            .replace(/>/g, '&gt;')
                popup.style.display = 'none';
            .replace(/"/g, '&quot;')
            }
             .replace(/'/g, '&#039;');
        });
    }


     $(document)
     container.classList.add('user-profile-portal');
        .off('click.clbiNotificationOutside')
        .on('click.clbiNotificationOutside', function(e) {
            var popup = document.getElementById('clbi-notification-popup');
            var quickToggle = document.getElementById('profile-quick-notifications');
            if (!popup) return;


            if (!popup.contains(e.target) && (!quickToggle || !quickToggle.contains(e.target))) {
    var safeUsername = escapeHtml(username);
                popup.style.display = 'none';
    var avatarSrc = '/index.php?title=특수:Redirect/file/Pfp-' + encodeURIComponent(username) + '.png&width=220';
            }
    var fallbackSrc = '/index.php?title=특수:Redirect/file/Pfp-default.png&width=220';
         });
    var editBtn = isOwnPage
        ? '<a href="/index.php/특수:사용자정보" class="profile-edit-btn"><span class="profile-edit-label">프로필 수정</span><span class="profile-edit-arrow">›</span></a>'
         : '';


     $(document)
     var progressHtml = isOwnPage
         .off('click.clbiNotificationReadAll')
         ? '<div class="profile-page-progress is-syncing" data-profile-progress>' +
        .on('click.clbiNotificationReadAll', '#clbi-notification-readall', function(e) {
            '<div class="profile-section-title">LEVEL RECORD</div>' +
             e.preventDefault();
            '<div class="profile-page-progress-body">' +
            e.stopPropagation();
                '<div class="profile-page-progress-row">' +
                    '<span class="profile-page-level">SYNC</span>' +
                    '<span class="profile-page-total-xp">— XP</span>' +
                '</div>' +
                '<div class="profile-page-xp-bar" aria-hidden="true"><div class="profile-page-xp-fill"></div></div>' +
                '<div class="profile-page-progress-sub">SYNCING</div>' +
                '<div class="profile-page-progress-meta">TODAY — · DISCOVERED —</div>' +
             '</div>' +
        '</div>'
        : '';


            var button = this;
    var card = document.createElement('div');
            button.disabled = true;
    card.className = 'profile-card profile-page-console';
             button.textContent = '처리 중...';
    card.innerHTML =
        '<div class="profile-card-titlebar">' +
            '<span>USER PROFILE</span>' +
            '<span>OFFICIAL ARCHIVE</span>' +
        '</div>' +
        '<div class="profile-card-body">' +
             '<div class="profile-identity-row">' +
                '<div class="profile-avatar-bay">' +
                    '<img src="' + avatarSrc + '" onerror="this.onerror=null;this.src=\'' + fallbackSrc + '\';" alt="' + safeUsername + '">' +
                '</div>' +
                '<div class="profile-info-panel">' +
                    '<div class="profile-nameplate">' +
                        '<h2 class="profile-username">' + safeUsername + '</h2>' +
                        editBtn +
                    '</div>' +
                    '<div class="profile-name" data-field="name"></div>' +
                    '<div class="profile-role" data-field="role"></div>' +
                    '<div class="profile-discord" data-field="discord"></div>' +
                '</div>' +
            '</div>' +
            '<div class="profile-lower-grid">' +
                '<div class="profile-bio-panel">' +
                    '<div class="profile-section-title">BIOGRAPHY</div>' +
                    '<div class="profile-bio" data-field="bio"></div>' +
                '</div>' +
                '<div class="profile-stats-panel">' +
                    '<div class="profile-section-title">RECORD</div>' +
                    '<div class="profile-stats">' +
                        progressHtml +
                        '<div class="profile-stat-grid">' +
                            '<div class="profile-stat">' +
                                '<span class="clbi-stat-value">' + editCount + '</span>' +
                                '<span class="clbi-stat-label">수정 횟수</span>' +
                            '</div>' +
                            '<div class="profile-stat" data-contrib-pages-stat>' +
                                '<span class="clbi-stat-value" data-contrib-pages-value>SYNC</span>' +
                                '<span class="clbi-stat-label">기여 문서</span>' +
                            '</div>' +
                        '</div>' +
                        '<div class="profile-info-grid">' +
                            '<div class="profile-info-stat">' +
                                '<span class="profile-info-label">TIME</span>' +
                                '<span class="profile-info-value" data-profile-time>UTC --:--</span>' +
                            '</div>' +
                            '<div class="profile-info-stat">' +
                                '<span class="profile-info-label">LANGUAGE</span>' +
                                '<span class="profile-info-value" data-profile-language>—</span>' +
                            '</div>' +
                        '</div>' +
                    '</div>' +
                '</div>' +
            '</div>' +
        '</div>';


            markAllNotificationsRead()
    $('.profile-card').remove();
                .then(function() {
    container.insertBefore(card, container.firstChild);
                    loadNotificationsIntoPopup();
    loadProfileFields(username, card);
                })
    loadProfileContributionPages(username, card);
                .always(function() {
    updateProfilePageEnvironment(card, null);
                    button.disabled = false;
                    button.textContent = '전체 읽음';
                });
        });


     $(document)
     if (isOwnPage) {
         .off('click.clbiNotificationItem')
         loadProfileProgressForUserPage(card);
        .on('click.clbiNotificationItem', '.clbi-notification-item', function(e) {
    }
            e.preventDefault();
}
            e.stopPropagation();


            var href = this.getAttribute('href');
function getProfileLanguageLabel() {
            var notificationId = this.getAttribute('data-notification-id') || '';
    var lang = getCurrentLang();
 
     return SIDEBAR_LANGUAGE_LABELS[lang] || (lang ? lang.toUpperCase() : '');
            markNotificationReadById(notificationId).always(function() {
                loadNotificationsIntoPopup();
                if (href) {
                    window.location.href = href;
                }
            });
        });
 
     $(window)
        .off('resize.clbiNotification')
        .on('resize.clbiNotification', function() {
            var popup = document.getElementById('clbi-notification-popup');
            if (popup && popup.style.display === 'block') {
                positionNotificationPopup();
            }
        });
}
}
// ========== 알림 시스템 끝 ==========


function initUserProfilePage() {
function updateProfilePageEnvironment(card, summary) {
     $('body').addClass('user-profile-settings-page');
     if (!card) return;


     var saveBtn = document.getElementById('pref-save');
     var timezone = summary && summary.timezone ? summary.timezone : 'UTC';
     if (!saveBtn) return;
    var timeEl = card.querySelector('[data-profile-time]');
     var langEl = card.querySelector('[data-profile-language]');


     function getPrefRow(id) {
     if (timeEl) {
         var el = document.getElementById(id);
         try {
         if (!el) return null;
            timeEl.textContent = timezone + ' ' + new Intl.DateTimeFormat('ko-KR', {
        return el.closest('.clbi-pref-row') || el.parentNode;
                hour: '2-digit',
                minute: '2-digit',
                hour12: false,
                timeZone: timezone
            }).format(new Date());
         } catch (err) {
            timeEl.textContent = 'UTC ' + new Intl.DateTimeFormat('ko-KR', {
                hour: '2-digit',
                minute: '2-digit',
                hour12: false,
                timeZone: 'UTC'
            }).format(new Date());
        }
     }
     }


     function removePrefRow(id) {
     if (langEl) {
         var row = getPrefRow(id);
         langEl.textContent = getProfileLanguageLabel();
        if (row && row.parentNode) {
            row.parentNode.removeChild(row);
        }
     }
     }
}


    function createPrefSection(className, titleText) {
function loadProfileContributionPages(username, card) {
        var section = document.createElement('div');
    if (!username || !card) return;
        section.className = 'clbi-pref-section ' + className;
    if (!mw.loader || typeof mw.loader.using !== 'function') return;


        var title = document.createElement('div');
    var valueEl = card.querySelector('[data-contrib-pages-value]');
        title.className = 'clbi-pref-section-title';
    if (valueEl) valueEl.textContent = 'SYNC';
        title.textContent = titleText;


         var body = document.createElement('div');
    mw.loader.using(['mediawiki.api']).then(function () {
         body.className = 'clbi-pref-section-body';
         var api = new mw.Api();
         var pages = Object.create(null);
        var cont = {};
        var guard = 0;


         section.appendChild(title);
         function requestNext() {
        section.appendChild(body);
            guard++;


        return {
            var params = Object.assign({
            section: section,
                action: 'query',
            body: body
                list: 'usercontribs',
        };
                ucuser: username,
    }
                ucnamespace: 0,
                ucprop: 'title',
                uclimit: 'max',
                format: 'json',
                formatversion: 2
            }, cont);


    function moveRowToSection(id, targetBody, className) {
            return api.get(params).then(function (data) {
        var row = getPrefRow(id);
                var rows = data && data.query && data.query.usercontribs ? data.query.usercontribs : [];
        if (!row || !targetBody) return false;


        row.classList.add('clbi-pref-row-key-' + className);
                rows.forEach(function (row) {
        targetBody.appendChild(row);
                    if (row && row.title) pages[row.title] = true;
        return true;
                });
    }


    function rebuildProfileSettingsLayout() {
                if (data && data.continue && data.continue.uccontinue && guard < 40) {
        var root = document.querySelector('.clbi-prefs-profile');
                    cont = data.continue;
        if (!root || root.dataset.profileSettingsReworked === '1') return;
                    return requestNext();
                }


        root.dataset.profileSettingsReworked = '1';
                if (valueEl) valueEl.textContent = Object.keys(pages).length;
        root.classList.add('profile-settings-console');
            });
        }


         removePrefRow('pref-badges');
         requestNext().fail(function () {
            if (valueEl) valueEl.textContent = '';
        });
    });
}


        var originalRows = Array.prototype.slice.call(root.querySelectorAll('.clbi-pref-row'));
function loadProfileProgressForUserPage(card) {
        var actionNodes = [];
    if (!mw.config.get('wgUserName')) return;
    if (!mw.loader || typeof mw.loader.using !== 'function') return;


        if (saveBtn.parentNode === root || saveBtn.closest('.clbi-prefs-profile') === root) {
    mw.loader.using(['mediawiki.api']).then(function () {
             actionNodes.push(saveBtn);
        var api = new mw.Api();
         }
        api.get({
            action: 'progress_summary',
            format: 'json',
            formatversion: 2
        }).then(function (data) {
            var payload = data && data.progress_summary;
            if (!payload || !payload.available || !payload.summary) return;
             updateUserPageProgress(card, payload.summary);
            updateProfilePageEnvironment(card, payload.summary);
         });
    });
}


        var statusNode = document.getElementById('pref-status');
function updateUserPageProgress(card, summary) {
        if (statusNode && statusNode.closest('.clbi-prefs-profile') === root) {
    var panel = card.querySelector('[data-profile-progress]');
            actionNodes.push(statusNode);
    if (!panel || !summary) return;
        }


        var main = document.createElement('div');
    var level = summary.level || 1;
        main.className = 'clbi-pref-main-grid';
    var totalXp = summary.totalXp || 0;
    var xpIntoLevel = summary.xpIntoLevel || 0;
    var xpForNext = summary.xpForNextLevel || 1;
    var percent = Math.max(0, Math.min(100, summary.progressPercent || 0));
    var isMaxLevel = !!summary.isMaxLevel;
    var dailyXp = summary.dailyXp || 0;
    var discoveries = summary.discoveryCount || 0;


        var media = createPrefSection('clbi-pref-section-media', 'PROFILE IMAGE');
    panel.classList.remove('is-syncing');
        var identity = createPrefSection('clbi-pref-section-identity', 'IDENTITY RECORD');
    panel.classList.toggle('is-max-level', isMaxLevel);
        var bio = createPrefSection('clbi-pref-section-bio', 'BIOGRAPHY');
        var account = createPrefSection('clbi-pref-section-account', 'ACCOUNT CONTACT');
        var misc = createPrefSection('clbi-pref-section-misc', 'OTHER OPTIONS');


        main.appendChild(media.section);
    var levelEl = panel.querySelector('.profile-page-level');
        main.appendChild(identity.section);
    var totalEl = panel.querySelector('.profile-page-total-xp');
        main.appendChild(bio.section);
    var fillEl = panel.querySelector('.profile-page-xp-fill');
        main.appendChild(account.section);
    var subEl = panel.querySelector('.profile-page-progress-sub');
        main.appendChild(misc.section);
    var metaEl = panel.querySelector('.profile-page-progress-meta');


        root.innerHTML = '';
    if (levelEl) levelEl.textContent = (isMaxLevel ? 'MAX ' : 'LVL ') + level;
        root.appendChild(main);
    if (totalEl) totalEl.textContent = totalXp + ' XP';
    if (fillEl) fillEl.style.width = percent + '%';
    if (subEl) subEl.textContent = isMaxLevel ? 'MAX LEVEL' : (xpIntoLevel + ' / ' + xpForNext + ' TO NEXT');
    if (metaEl) metaEl.textContent = 'TODAY ' + dailyXp + ' XP · DISCOVERED ' + discoveries;
}


         moveRowToSection('pref-pfp-preview', media.body, 'pfp');
function loadProfileFields(username, card) {
         moveRowToSection('pref-pfp-btn', media.body, 'pfp');
    var api = new mw.Api();
         moveRowToSection('pref-pfp-input', media.body, 'pfp');
    api.get({
         action: 'userprofile',
        user: username
    }).then(function(data) {
        var profile = data.userprofile;
         updateProfileFields(card, {
            name: profile.name || '',
            discord: profile.discord || '',
            role: profile.role || '',
            bio: profile.bio || ''
        });
    }).fail(function() {
         updateProfileFields(card, {
            name: '',
            discord: '',
            role: '',
            bio: ''
        });
    });
}


        moveRowToSection('pref-name', identity.body, 'name');
function updateProfileFields(card, data) {
        moveRowToSection('pref-role', identity.body, 'role');
    var nameEl = card.querySelector('[data-field="name"]');
        moveRowToSection('pref-discord', identity.body, 'discord');
    var roleEl = card.querySelector('[data-field="role"]');
    var discordEl = card.querySelector('[data-field="discord"]');
    var bioEl = card.querySelector('[data-field="bio"]');
    if (nameEl) nameEl.textContent = data.name || '';
    if (roleEl) roleEl.textContent = data.role || '';
    if (discordEl) discordEl.textContent = data.discord ? ('디스코드: ' + data.discord) : '';
    if (bioEl) bioEl.textContent = data.bio || '';
}
// ========== 프로필 시스템 끝 ==========


        moveRowToSection('pref-bio', bio.body, 'bio');
// ========== 알림 시스템 ==========
function ensureNotificationPopup() {
    if (document.getElementById('clbi-notification-popup')) return;


        moveRowToSection('pref-new-email', account.body, 'email');
    var popup = document.createElement('div');
         moveRowToSection('pref-email-password', account.body, 'email');
    popup.id = 'clbi-notification-popup';
         moveRowToSection('pref-email-save', account.body, 'email');
    popup.style.cssText =
         'display:none;position:fixed;z-index:99999;width:320px;max-height:420px;' +
        'background:#0a0909;border:2px solid #854369;border-radius:5px;' +
         'box-shadow:0 0 0 1px #1a1a1a, 0 8px 24px rgba(0,0,0,0.55);overflow:hidden;';


         originalRows.forEach(function (row) {
    popup.innerHTML =
             if (!row.parentNode && !row.className.match(/clbi-pref-row-key-/)) {
         '<div style="padding:10px 12px;border-bottom:2px solid #854369;background:linear-gradient(to bottom, #171114 0%, #0a0909 100%);color:#E2E2E2;font-size:13px;font-weight:700;display:flex;align-items:center;justify-content:space-between;gap:8px;">' +
                misc.body.appendChild(row);
             '<span>알림</span>' +
             }
            '<button type="button" id="clbi-notification-readall" style="background:#171717;border:1px solid #854369;border-radius:6px;color:#E2E2E2;font-size:11px;font-weight:700;padding:4px 8px;cursor:pointer;">전체 읽음</button>' +
         });
        '</div>' +
        '<div id="clbi-notification-list" style="max-height:320px;overflow-y:auto;padding:8px 0;color:#E2E2E2;font-size:12px;">불러오는 중...</div>' +
        '<div style="padding:8px;border-top:1px solid #2a2a2a;background:#111;">' +
             '<a href="/index.php?title=Special:Notifications" id="clbi-notification-more" style="display:block;width:100%;text-align:center;padding:8px 10px;border-radius:6px;background:#171717;border:1px solid #854369;color:#E2E2E2 !important;text-decoration:none !important;font-size:12px;font-weight:700;">더보기</a>' +
         '</div>';


        if (!misc.body.children.length) {
    document.body.appendChild(popup);
            misc.section.parentNode.removeChild(misc.section);
}
        }


        var actions = document.createElement('div');
function positionNotificationPopup() {
        actions.className = 'clbi-pref-actions';
    var btn = document.getElementById('profile-quick-notifications');
    var popup = document.getElementById('clbi-notification-popup');
    if (!btn || !popup) return;


        if (saveBtn) actions.appendChild(saveBtn);
    var rect = btn.getBoundingClientRect();
        if (statusNode) actions.appendChild(statusNode);
    var top = rect.bottom + 6;
    var left = rect.left + (rect.width / 2) - (popup.offsetWidth / 2);


         root.appendChild(actions);
    if (left < 8) left = 8;
    if (left + popup.offsetWidth > window.innerWidth - 8) {
        left = window.innerWidth - popup.offsetWidth - 8;
    }
    if (top + popup.offsetHeight > window.innerHeight - 8) {
         top = Math.max(8, rect.top - popup.offsetHeight - 6);
     }
     }


     rebuildProfileSettingsLayout();
     popup.style.top = top + 'px';
    popup.style.left = left + 'px';
}


     var api = new mw.Api();
function parseNotificationItemsFromHtml(html) {
     var selectedFile = null;
     var parser = new DOMParser();
    var cropper = null;
     var doc = parser.parseFromString(html, 'text/html');


     if (!document.getElementById('clbi-gallery-modal')) {
     var selectors = [
         var gModal = document.createElement('div');
        '.mw-echo-ui-notificationItemWidget',
         gModal.id = 'clbi-gallery-modal';
        '.mw-echo-ui-notificationsInboxWidgetRow',
         gModal.style.cssText =
         '.echo-ui-notificationItemWidget',
            'display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.85);z-index:99999;align-items:center;justify-content:center;';
         'li[data-notification-id]',
         '.mw-echo-notifications-list li'
    ];


        gModal.innerHTML =
    var items = [];
            '<div style="background:#1e1e1e;border:2px solid #854369;border-radius:12px;padding:24px;max-width:480px;width:90%;display:flex;flex-direction:column;gap:16px;">' +
    for (var i = 0; i < selectors.length; i++) {
                '<div style="display:flex;justify-content:space-between;align-items:center;">' +
        items = Array.prototype.slice.call(doc.querySelectorAll(selectors[i]));
                    '<span style="font-size:14px;font-weight:700;color:#e2e2e2;">프로필 사진 선택</span>' +
         if (items.length) break;
                    '<button type="button" id="clbi-gallery-close" style="background:none;border:none;color:#aaa;font-size:18px;cursor:pointer;">✕</button>' +
                '</div>' +
                '<button type="button" id="clbi-gallery-upload-btn" style="background:#2a2a2a;border:2px dashed #854369;border-radius:8px;padding:32px;color:#e2e2e2;cursor:pointer;display:flex;flex-direction:column;align-items:center;gap:8px;font-size:13px;width:100%;">' +
                    '<span style="font-size:32px;">🖼️</span>새 사진 업로드' +
                '</button>' +
                '<div id="clbi-gallery-history-section" style="display:none;">' +
                    '<div style="font-size:11px;color:#888;margin-bottom:8px;">이전 사진 — 클릭하면 바로 적용</div>' +
                    '<div id="clbi-gallery-history" style="display:flex;gap:8px;flex-wrap:wrap;"></div>' +
                '</div>' +
            '</div>';
 
         document.body.appendChild(gModal);
     }
     }


     if (!document.getElementById('clbi-crop-modal')) {
     return items.slice(0, 5).map(function(item) {
         var cModal = document.createElement('div');
         var link = item.querySelector('a[href]');
         cModal.id = 'clbi-crop-modal';
         var href = link ? link.getAttribute('href') : '/index.php?title=Special:Notifications';
         cModal.style.cssText =
         var text = (item.textContent || '').replace(/\s+/g, ' ').trim();
            'display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.85);z-index:99999;align-items:center;justify-content:center;';


         cModal.innerHTML =
         var notificationId =
             '<div style="background:#1e1e1e;border:2px solid #854369;border-radius:12px;padding:24px;max-width:500px;width:90%;display:flex;flex-direction:column;gap:16px;">' +
             item.getAttribute('data-notification-id') ||
                '<div style="font-size:14px;font-weight:700;color:#e2e2e2;">사진 조정</div>' +
            item.getAttribute('data-id') ||
                '<div style="width:100%;max-height:380px;overflow:hidden;border-radius:8px;">' +
            item.getAttribute('data-notification') ||
                    '<img id="clbi-crop-image" style="max-width:100%;">' +
             '';
                '</div>' +
                '<div style="display:flex;gap:8px;justify-content:flex-end;">' +
                    '<button type="button" id="clbi-crop-cancel" style="background:#2a2a2a;color:#e2e2e2;border:1px solid #444;padding:8px 16px;border-radius:6px;cursor:pointer;">취소</button>' +
                    '<button type="button" id="clbi-crop-confirm" style="background:#854369;color:#fff;border:none;padding:8px 16px;border-radius:6px;cursor:pointer;">확정</button>' +
                '</div>' +
             '</div>';


         document.body.appendChild(cModal);
         if (!notificationId) {
    }
            var anyWithId = item.querySelector('[data-notification-id], [data-id], [data-notification]');
            if (anyWithId) {
                notificationId =
                    anyWithId.getAttribute('data-notification-id') ||
                    anyWithId.getAttribute('data-id') ||
                    anyWithId.getAttribute('data-notification') ||
                    '';
            }
        }


    var gModal = document.getElementById('clbi-gallery-modal');
        if (href && href.indexOf('http') !== 0) {
    var cModal = document.getElementById('clbi-crop-modal');
            href = href.charAt(0) === '/'
    var cropImage = document.getElementById('clbi-crop-image');
                ? href
    var pfpInput = document.getElementById('pref-pfp-input');
                : '/index.php' + (href.charAt(0) === '?' ? href : '/' + href);
        }


    function openGallery() {
        return {
        gModal.style.display = 'flex';
            id: notificationId,
            href: href,
            text: text || '알림'
        };
    });
}


        var username = mw.config.get('wgUserName');
function setNotificationIcon(hasItems) {
        api.get({
    var quickIcon = document.getElementById('profile-quick-notification-icon');
            action: 'query',
    var svg = hasItems ? CLBI_SVG_BELL_DOT : CLBI_SVG_BELL;
            titles: '파일:Pfp-' + username + '.png',
            prop: 'imageinfo',
            iiprop: 'url|timestamp',
            iilimit: 6
        }).then(function(data) {
            var pages = data.query.pages;
            var page = pages[Object.keys(pages)[0]];
            if (!page.imageinfo || page.imageinfo.length === 0) return;


            var historyEl = document.getElementById('clbi-gallery-history');
    if (quickIcon) {
            var sectionEl = document.getElementById('clbi-gallery-history-section');
        quickIcon.innerHTML = svg;
            historyEl.innerHTML = '';
        quickIcon.classList.toggle('has-notifications', !!hasItems);
    }
}


            page.imageinfo.forEach(function(info, idx) {
function renderNotificationPopup(items) {
                var wrap = document.createElement('div');
    var list = document.getElementById('clbi-notification-list');
                wrap.style.cssText = 'position:relative;cursor:pointer;';
    var badge = document.getElementById('clbi-notification-badge');
    if (!list) return;


                var img = document.createElement('img');
    if (!items || !items.length) {
                img.src = info.url;
        list.innerHTML = '<div style="padding:14px 12px;color:#999;">표시할 알림이 없습니다.</div>';
                img.style.cssText =
        if (badge) badge.style.display = 'none';
                    'width:72px;height:72px;object-fit:cover;border-radius:8px;border:2px solid #444;flex-shrink:0;';
        setNotificationIcon(false);
        return;
    }


                if (idx === 0) {
    var html = '';
                    img.style.borderColor = '#854369';
    for (var i = 0; i < items.length; i++) {
                    var badge = document.createElement('div');
        html +=
                    badge.textContent = '현재';
            '<a href="' + items[i].href + '" class="clbi-notification-item" data-notification-id="' + (items[i].id || '') + '" style="display:block;padding:10px 12px;color:#E2E2E2 !important;text-decoration:none !important;border-bottom:1px solid #1f1f1f;line-height:1.5;">' +
                    badge.style.cssText =
                items[i].text +
                        'position:absolute;bottom:4px;left:50%;transform:translateX(-50%);background:#854369;color:#fff;font-size:9px;padding:1px 6px;border-radius:10px;';
            '</a>';
                    wrap.appendChild(badge);
    }
                }
    list.innerHTML = html;


                img.addEventListener('mouseenter', function() {
    if (badge) {
                    if (idx !== 0) img.style.borderColor = '#854369';
        badge.textContent = items.length;
                });
        badge.style.display = 'block';
    }
    setNotificationIcon(true);
}


                img.addEventListener('mouseleave', function() {
function loadNotificationsIntoPopup() {
                    if (idx !== 0) img.style.borderColor = '#444';
    var list = document.getElementById('clbi-notification-list');
                });
    if (list) {
 
        list.innerHTML = '<div style="padding:14px 12px;color:#999;">불러오는 중...</div>';
                img.addEventListener('click', function() {
                    fetch(info.url)
                        .then(function(r) {
                            return r.blob();
                        })
                        .then(function(blob) {
                            selectedFile = new File([blob], 'profile.png', { type: 'image/png' });
                            document.getElementById('pref-pfp-preview').src = URL.createObjectURL(blob);
                            gModal.style.display = 'none';
                            document.getElementById('pref-pfp-btn').textContent = '✓ 사진 선택됨';
                        });
                });
 
                wrap.appendChild(img);
                historyEl.appendChild(wrap);
            });
 
            sectionEl.style.display = 'block';
        });
     }
     }


     function openCrop(src) {
     fetch('/index.php?title=Special:Notifications', { credentials: 'same-origin' })
         cropImage.src = src;
        .then(function(res) {
         cModal.style.display = 'flex';
            return res.text();
        })
         .then(function(html) {
            var items = parseNotificationItemsFromHtml(html);
            renderNotificationPopup(items);
        })
         .catch(function(err) {
            console.error(err);
            if (list) {
                list.innerHTML = '<div style="padding:14px 12px;color:#999;">알림을 불러오지 못했습니다.</div>';
            }
        });
}


        if (cropper) {
function markAllNotificationsRead() {
            cropper.destroy();
    return new mw.Api().postWithToken('csrf', {
            cropper = null;
        action: 'echomarkread',
        }
        list: 'all'
    });
}


        setTimeout(function() {
function markNotificationReadById(notificationId) {
            cropper = new Cropper(cropImage, {
    if (!notificationId) {
                aspectRatio: 1,
        return $.Deferred().resolve().promise();
                viewMode: 1,
                dragMode: 'move',
                autoCropArea: 0.8,
                cropBoxResizable: true,
                cropBoxMovable: true
            });
        }, 150);
     }
     }


     document.getElementById('pref-pfp-btn').addEventListener('click', function() {
     return new mw.Api().postWithToken('csrf', {
         openGallery();
         action: 'echomarkread',
        list: notificationId
     });
     });
}


     document.getElementById('clbi-gallery-upload-btn').addEventListener('click', function() {
function initNotifications() {
        pfpInput.click();
     var quickBtn = document.getElementById('profile-quick-notifications');
    });


     document.getElementById('clbi-gallery-close').addEventListener('click', function() {
     if (!quickBtn) return;
        gModal.style.display = 'none';
    });


     pfpInput.addEventListener('change', function() {
     ensureNotificationPopup();
        var file = this.files[0];
    loadNotificationsIntoPopup();
        if (!file) return;


         gModal.style.display = 'none';
    $(document)
         .off('click.clbiNotificationToggle')
        .on('click.clbiNotificationToggle', '#profile-quick-notifications', function(e) {
            e.preventDefault();
            e.stopPropagation();


        var reader = new FileReader();
            var popup = document.getElementById('clbi-notification-popup');
        reader.onload = function(e) {
             if (!popup) return;
             openCrop(e.target.result);
        };
        reader.readAsDataURL(file);
    });


    document.getElementById('clbi-crop-cancel').addEventListener('click', function() {
            if (popup.style.display === 'none' || popup.style.display === '') {
        cModal.style.display = 'none';
                popup.style.display = 'block';
        if (cropper) {
                positionNotificationPopup();
            cropper.destroy();
                loadNotificationsIntoPopup();
             cropper = null;
             } else {
        }
                popup.style.display = 'none';
        pfpInput.value = '';
            }
    });
        });


     document.getElementById('clbi-crop-confirm').addEventListener('click', function() {
     $(document)
        if (!cropper) return;
        .off('click.clbiNotificationOutside')
        .on('click.clbiNotificationOutside', function(e) {
            var popup = document.getElementById('clbi-notification-popup');
            var quickToggle = document.getElementById('profile-quick-notifications');
            if (!popup) return;


        var canvas = cropper.getCroppedCanvas({ width: 256, height: 256 });
            if (!popup.contains(e.target) && (!quickToggle || !quickToggle.contains(e.target))) {
         if (!canvas) return;
                popup.style.display = 'none';
            }
         });


        canvas.toBlob(function(blob) {
    $(document)
            selectedFile = new File([blob], 'profile.png', { type: 'image/png' });
        .off('click.clbiNotificationReadAll')
            document.getElementById('pref-pfp-preview').src = URL.createObjectURL(blob);
        .on('click.clbiNotificationReadAll', '#clbi-notification-readall', function(e) {
             cModal.style.display = 'none';
             e.preventDefault();
            cropper.destroy();
             e.stopPropagation();
             cropper = null;
            document.getElementById('pref-pfp-btn').textContent = '✓ 사진 선택됨';
        }, 'image/png');
    });


    var emailSaveBtn = document.getElementById('pref-email-save');
            var button = this;
    if (emailSaveBtn) {
            button.disabled = true;
        emailSaveBtn.addEventListener('click', function() {
             button.textContent = '처리 중...';
            var statusEl = document.getElementById('pref-email-status');
             var newEmail = document.getElementById('pref-new-email').value;
            var password = document.getElementById('pref-email-password').value;


             if (!newEmail || !password) {
             markAllNotificationsRead()
                 statusEl.textContent = '이메일과 비밀번호를 입력해주세요.';
                .then(function() {
                 return;
                    loadNotificationsIntoPopup();
            }
                 })
 
                .always(function() {
            statusEl.textContent = '변경 중...';
                    button.disabled = false;
                    button.textContent = '전체 읽음';
                 });
        });


            api.postWithToken('csrf', {
    $(document)
                action: 'changeemail',
        .off('click.clbiNotificationItem')
                email: newEmail,
        .on('click.clbiNotificationItem', '.clbi-notification-item', function(e) {
                password: password
             e.preventDefault();
             }).then(function() {
            e.stopPropagation();
                statusEl.textContent = '✓ 이메일 변경됨';
 
                document.getElementById('pref-new-email').value = '';
            var href = this.getAttribute('href');
                document.getElementById('pref-email-password').value = '';
            var notificationId = this.getAttribute('data-notification-id') || '';


                setTimeout(function() {
            markNotificationReadById(notificationId).always(function() {
                    statusEl.textContent = '';
                 loadNotificationsIntoPopup();
                 }, 3000);
                if (href) {
            }).fail(function(code, data) {
                    window.location.href = href;
                var msg = data && data.error && data.error.info ? data.error.info : '변경 실패';
                 }
                 statusEl.textContent = msg;
             });
             });
         });
         });
    }


     saveBtn.addEventListener('click', function() {
     $(window)
        var statusEl = document.getElementById('pref-status');
        .off('resize.clbiNotification')
        statusEl.textContent = '저장 중...';
        .on('resize.clbiNotification', function() {
            var popup = document.getElementById('clbi-notification-popup');
            if (popup && popup.style.display === 'block') {
                positionNotificationPopup();
            }
        });
}
// ========== 알림 시스템 끝 ==========


        var promises = [];
function initUserProfilePage() {
    $('body').addClass('user-profile-settings-page');


        if (selectedFile) {
    var saveBtn = document.getElementById('pref-save');
            var username = mw.config.get('wgUserName');
    if (!saveBtn) return;
            promises.push(
                api.postWithToken('csrf', {
                    action: 'upload',
                    filename: 'Pfp-' + username + '.png',
                    ignorewarnings: true,
                    file: selectedFile,
                    format: 'json'
                }, {
                    contentType: 'multipart/form-data'
                })
            );
        }


         var fields = ['name', 'discord', 'role', 'bio'];
    function getPrefRow(id) {
         var el = document.getElementById(id);
        if (!el) return null;
        return el.closest('.clbi-pref-row') || el.parentNode;
    }


        for (var i = 0; i < fields.length; i++) {
    function removePrefRow(id) {
            var el = document.getElementById('pref-' + fields[i]);
        var row = getPrefRow(id);
            if (!el) continue;
        if (row && row.parentNode) {
 
             row.parentNode.removeChild(row);
             promises.push(
                api.postWithToken('csrf', {
                    action: 'options',
                    optionname: 'profile-' + fields[i],
                    optionvalue: el.value
                })
            );
         }
         }
    }


        $.when.apply($, promises)
    function createPrefSection(className, titleText) {
            .then(function() {
        var section = document.createElement('div');
                statusEl.textContent = '✓ 저장됨';
        section.className = 'clbi-pref-section ' + className;
                selectedFile = null;
                document.getElementById('pref-pfp-btn').textContent = '사진 선택';


                setTimeout(function() {
        var title = document.createElement('div');
                    statusEl.textContent = '';
        title.className = 'clbi-pref-section-title';
                }, 2000);
        title.textContent = titleText;
            })
            .fail(function() {
                statusEl.textContent = '저장 실패';
            });
    });
}


/* =========================================
        var body = document.createElement('div');
  Banner / CRT Page Monitor thumbnail slices
        body.className = 'clbi-pref-section-body';
  - base 이미지는 틀에 들어간 파일 문법 그대로 사용
  - slice 레이어에는 300px MediaWiki 썸네일만 삽입
  ========================================= */


(function ($, mw) {
        section.appendChild(title);
    var thumbCache = {};
        section.appendChild(body);


    function parseSliceWidth(value) {
        return {
         var parsed = parseInt(value, 10);
            section: section,
            body: body
         };
    }


         if (!isFinite(parsed) || parsed < 120) {
    function moveRowToSection(id, targetBody, className) {
            return 300;
        var row = getPrefRow(id);
        }
         if (!row || !targetBody) return false;
 
        return parsed;
    }


    function getImageSrc(img) {
         row.classList.add('clbi-pref-row-key-' + className);
         return img ? (img.currentSrc || img.getAttribute('src') || img.src || '') : '';
        targetBody.appendChild(row);
        return true;
     }
     }


     function getFileNameFromSrc(src) {
     function rebuildProfileSettingsLayout() {
         var a;
         var root = document.querySelector('.clbi-prefs-profile');
         var parts;
         if (!root || root.dataset.profileSettingsReworked === '1') return;
        var fileName;


         if (!src) return '';
         root.dataset.profileSettingsReworked = '1';
        root.classList.add('profile-settings-console');


         a = document.createElement('a');
         removePrefRow('pref-badges');
        a.href = src;


         parts = (a.pathname || '').split('/').filter(function (part) {
         var originalRows = Array.prototype.slice.call(root.querySelectorAll('.clbi-pref-row'));
            return !!part;
         var actionNodes = [];
         });


         if (!parts.length) return '';
         if (saveBtn.parentNode === root || saveBtn.closest('.clbi-prefs-profile') === root) {
            actionNodes.push(saveBtn);
        }


         fileName = parts.pop();
         var statusNode = document.getElementById('pref-status');
 
         if (statusNode && statusNode.closest('.clbi-prefs-profile') === root) {
         /*
             actionNodes.push(statusNode);
        * MediaWiki thumb URL 예시:
        * /images/thumb/a/ab/File.png/1000px-File.png
        * /images/thumb/a/ab/File.svg/1000px-File.svg.png
        *
        * 이 경우 실제 파일명은 마지막 조각이 아니라 그 앞 조각이다.
        */
        if (/^\d+px-/.test(fileName) && parts.length) {
             fileName = parts.pop();
         }
         }


         fileName = fileName.replace(/^\d+px-/, '');
         var main = document.createElement('div');
        main.className = 'clbi-pref-main-grid';


         try {
         var media = createPrefSection('clbi-pref-section-media', 'PROFILE IMAGE');
            fileName = decodeURIComponent(fileName);
        var identity = createPrefSection('clbi-pref-section-identity', 'IDENTITY RECORD');
         } catch (e) {}
         var bio = createPrefSection('clbi-pref-section-bio', 'BIOGRAPHY');
        var account = createPrefSection('clbi-pref-section-account', 'ACCOUNT CONTACT');
        var misc = createPrefSection('clbi-pref-section-misc', 'OTHER OPTIONS');


         return fileName;
         main.appendChild(media.section);
    }
        main.appendChild(identity.section);
        main.appendChild(bio.section);
        main.appendChild(account.section);
        main.appendChild(misc.section);


    function resolveThumbUrl(img, width, callback) {
         root.innerHTML = '';
         var src = getImageSrc(img);
         root.appendChild(main);
         var fileName = getFileNameFromSrc(src);
        var cacheKey;
        var entry;


         if (!src) return;
         moveRowToSection('pref-pfp-preview', media.body, 'pfp');
        moveRowToSection('pref-pfp-btn', media.body, 'pfp');
        moveRowToSection('pref-pfp-input', media.body, 'pfp');


         if (!fileName || !mw || !mw.loader) {
         moveRowToSection('pref-name', identity.body, 'name');
            callback(src);
        moveRowToSection('pref-role', identity.body, 'role');
            return;
        moveRowToSection('pref-discord', identity.body, 'discord');
         }
 
         moveRowToSection('pref-bio', bio.body, 'bio');


         cacheKey = fileName + '|' + width;
         moveRowToSection('pref-new-email', account.body, 'email');
         entry = thumbCache[cacheKey];
         moveRowToSection('pref-email-password', account.body, 'email');
        moveRowToSection('pref-email-save', account.body, 'email');


         if (entry) {
         originalRows.forEach(function (row) {
             if (entry.resolved) {
             if (!row.parentNode && !row.className.match(/clbi-pref-row-key-/)) {
                callback(entry.url || src);
                 misc.body.appendChild(row);
            } else {
                 entry.callbacks.push(callback);
             }
             }
             return;
        });
 
        if (!misc.body.children.length) {
             misc.section.parentNode.removeChild(misc.section);
         }
         }


         entry = {
         var actions = document.createElement('div');
            resolved: false,
         actions.className = 'clbi-pref-actions';
            url: '',
            callbacks: [callback]
         };


         thumbCache[cacheKey] = entry;
         if (saveBtn) actions.appendChild(saveBtn);
        if (statusNode) actions.appendChild(statusNode);


         function finish(url) {
         root.appendChild(actions);
            var callbacks = entry.callbacks.slice();
    }
            var i;


            entry.resolved = true;
    rebuildProfileSettingsLayout();
            entry.url = url || src;
            entry.callbacks = [];


            for (i = 0; i < callbacks.length; i++) {
    var api = new mw.Api();
                callbacks[i](entry.url);
    var selectedFile = null;
            }
    var cropper = null;
        }


        mw.loader.using('mediawiki.api').done(function () {
    if (!document.getElementById('clbi-gallery-modal')) {
            var api = new mw.Api();
        var gModal = document.createElement('div');
        gModal.id = 'clbi-gallery-modal';
        gModal.style.cssText =
            'display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.85);z-index:99999;align-items:center;justify-content:center;';


             api.get({
        gModal.innerHTML =
                 action: 'query',
             '<div style="background:#1e1e1e;border:2px solid #854369;border-radius:12px;padding:24px;max-width:480px;width:90%;display:flex;flex-direction:column;gap:16px;">' +
                titles: 'File:' + fileName,
                 '<div style="display:flex;justify-content:space-between;align-items:center;">' +
                 prop: 'imageinfo',
                    '<span style="font-size:14px;font-weight:700;color:#e2e2e2;">프로필 사진 선택</span>' +
                 iiprop: 'url',
                    '<button type="button" id="clbi-gallery-close" style="background:none;border:none;color:#aaa;font-size:18px;cursor:pointer;">✕</button>' +
                 iiurlwidth: width,
                 '</div>' +
                 formatversion: 2
                 '<button type="button" id="clbi-gallery-upload-btn" style="background:#2a2a2a;border:2px dashed #854369;border-radius:8px;padding:32px;color:#e2e2e2;cursor:pointer;display:flex;flex-direction:column;align-items:center;gap:8px;font-size:13px;width:100%;">' +
            }).done(function (data) {
                    '<span style="font-size:32px;">🖼️</span>새 사진 업로드' +
                var page;
                 '</button>' +
                 var info;
                 '<div id="clbi-gallery-history-section" style="display:none;">' +
                    '<div style="font-size:11px;color:#888;margin-bottom:8px;">이전 사진 — 클릭하면 바로 적용</div>' +
                    '<div id="clbi-gallery-history" style="display:flex;gap:8px;flex-wrap:wrap;"></div>' +
                 '</div>' +
            '</div>';


                if (
        document.body.appendChild(gModal);
                    data &&
                    data.query &&
                    data.query.pages &&
                    data.query.pages.length
                ) {
                    page = data.query.pages[0];
 
                    if (
                        page &&
                        page.imageinfo &&
                        page.imageinfo.length
                    ) {
                        info = page.imageinfo[0];
                    }
                }
 
                finish((info && (info.thumburl || info.url)) || src);
            }).fail(function () {
                finish(src);
            });
        }).fail(function () {
            finish(src);
        });
     }
     }


     function applySliceImages(frame, thumbUrl) {
     if (!document.getElementById('clbi-crop-modal')) {
         var slices;
         var cModal = document.createElement('div');
         var i;
         cModal.id = 'clbi-crop-modal';
         var img;
         cModal.style.cssText =
            'display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.85);z-index:99999;align-items:center;justify-content:center;';


         if (!frame || !thumbUrl) return;
         cModal.innerHTML =
            '<div style="background:#1e1e1e;border:2px solid #854369;border-radius:12px;padding:24px;max-width:500px;width:90%;display:flex;flex-direction:column;gap:16px;">' +
                '<div style="font-size:14px;font-weight:700;color:#e2e2e2;">사진 조정</div>' +
                '<div style="width:100%;max-height:380px;overflow:hidden;border-radius:8px;">' +
                    '<img id="clbi-crop-image" style="max-width:100%;">' +
                '</div>' +
                '<div style="display:flex;gap:8px;justify-content:flex-end;">' +
                    '<button type="button" id="clbi-crop-cancel" style="background:#2a2a2a;color:#e2e2e2;border:1px solid #444;padding:8px 16px;border-radius:6px;cursor:pointer;">취소</button>' +
                    '<button type="button" id="clbi-crop-confirm" style="background:#854369;color:#fff;border:none;padding:8px 16px;border-radius:6px;cursor:pointer;">확정</button>' +
                '</div>' +
            '</div>';


         slices = frame.querySelectorAll('.crt-page-monitor-slice');
         document.body.appendChild(cModal);
    }


        for (i = 0; i < slices.length; i++) {
    var gModal = document.getElementById('clbi-gallery-modal');
            slices[i].innerHTML = '';
    var cModal = document.getElementById('clbi-crop-modal');
    var cropImage = document.getElementById('clbi-crop-image');
    var pfpInput = document.getElementById('pref-pfp-input');


            img = document.createElement('img');
    function openGallery() {
            img.className = 'crt-page-monitor-slice-img';
        gModal.style.display = 'flex';
            img.src = thumbUrl;
            img.alt = '';
            img.decoding = 'async';
            img.loading = 'eager';
            img.setAttribute('aria-hidden', 'true');


             slices[i].appendChild(img);
        var username = mw.config.get('wgUserName');
        }
        api.get({
            action: 'query',
            titles: '파일:Pfp-' + username + '.png',
            prop: 'imageinfo',
            iiprop: 'url|timestamp',
            iilimit: 6
        }).then(function(data) {
            var pages = data.query.pages;
             var page = pages[Object.keys(pages)[0]];
            if (!page.imageinfo || page.imageinfo.length === 0) return;


        frame.setAttribute('data-crt-slices-ready', '1');
            var historyEl = document.getElementById('clbi-gallery-history');
    }
            var sectionEl = document.getElementById('clbi-gallery-history-section');
            historyEl.innerHTML = '';


    function initBannerFrame(frame) {
            page.imageinfo.forEach(function(info, idx) {
        var baseImg;
                var wrap = document.createElement('div');
        var width;
                wrap.style.cssText = 'position:relative;cursor:pointer;';


        if (!frame) return;
                var img = document.createElement('img');
        if (frame.getAttribute('data-crt-slices-ready') === '1') return;
                img.src = info.url;
                img.style.cssText =
                    'width:72px;height:72px;object-fit:cover;border-radius:8px;border:2px solid #444;flex-shrink:0;';


        baseImg = frame.querySelector('.crt-page-monitor-image-base img');
                if (idx === 0) {
                    img.style.borderColor = '#854369';
                    var badge = document.createElement('div');
                    badge.textContent = '현재';
                    badge.style.cssText =
                        'position:absolute;bottom:4px;left:50%;transform:translateX(-50%);background:#854369;color:#fff;font-size:9px;padding:1px 6px;border-radius:10px;';
                    wrap.appendChild(badge);
                }


        if (!baseImg) return;
                img.addEventListener('mouseenter', function() {
                    if (idx !== 0) img.style.borderColor = '#854369';
                });


        width = parseSliceWidth(frame.getAttribute('data-crt-slice-width'));
                img.addEventListener('mouseleave', function() {
                    if (idx !== 0) img.style.borderColor = '#444';
                });


        resolveThumbUrl(baseImg, width, function (thumbUrl) {
                img.addEventListener('click', function() {
            if (!frame || !frame.parentNode) return;
                    fetch(info.url)
            applySliceImages(frame, thumbUrl);
                        .then(function(r) {
                            return r.blob();
                        })
                        .then(function(blob) {
                            selectedFile = new File([blob], 'profile.png', { type: 'image/png' });
                            document.getElementById('pref-pfp-preview').src = URL.createObjectURL(blob);
                            gModal.style.display = 'none';
                            document.getElementById('pref-pfp-btn').textContent = '✓ 사진 선택됨';
                        });
                });
 
                wrap.appendChild(img);
                historyEl.appendChild(wrap);
            });
 
            sectionEl.style.display = 'block';
         });
         });
     }
     }


     function initBannerFrames(root) {
     function openCrop(src) {
         var scope = root && root.querySelectorAll ? root : document;
         cropImage.src = src;
         var frames = scope.querySelectorAll('.crt-page-monitor-frame');
         cModal.style.display = 'flex';
        var i;


         for (i = 0; i < frames.length; i++) {
         if (cropper) {
             initBannerFrame(frames[i]);
             cropper.destroy();
            cropper = null;
         }
         }
        setTimeout(function() {
            cropper = new Cropper(cropImage, {
                aspectRatio: 1,
                viewMode: 1,
                dragMode: 'move',
                autoCropArea: 0.8,
                cropBoxResizable: true,
                cropBoxMovable: true
            });
        }, 150);
     }
     }


     $(function () {
     document.getElementById('pref-pfp-btn').addEventListener('click', function() {
         initBannerFrames(document);
         openGallery();
     });
     });


     if (mw && mw.hook) {
     document.getElementById('clbi-gallery-upload-btn').addEventListener('click', function() {
        mw.hook('wikipage.content').add(function ($content) {
        pfpInput.click();
            initBannerFrames($content && $content[0] ? $content[0] : document);
     });
        });
     }
})(jQuery, window.mw);


/* =========================================
    document.getElementById('clbi-gallery-close').addEventListener('click', function() {
  Doc Tab System — tab switching UI
        gModal.style.display = 'none';
  글리치 플리커 + RGB split + 방향 슬라이드
    });
  ========================================= */


(function () {
    pfpInput.addEventListener('change', function() {
    'use strict';
        var file = this.files[0];
        if (!file) return;


    function initDocTabs() {
         gModal.style.display = 'none';
         var tabBars = document.querySelectorAll('.doc-tab-bar');
        if (!tabBars.length) return;


         tabBars.forEach(function (bar) {
         var reader = new FileReader();
             if (bar.getAttribute('data-tabs-init')) return;
        reader.onload = function(e) {
            bar.setAttribute('data-tabs-init', '1');
             openCrop(e.target.result);
        };
        reader.readAsDataURL(file);
    });


            var tabs = Array.from(bar.querySelectorAll('.doc-tab'));
    document.getElementById('clbi-crop-cancel').addEventListener('click', function() {
             if (!tabs.length) return;
        cModal.style.display = 'none';
        if (cropper) {
            cropper.destroy();
             cropper = null;
        }
        pfpInput.value = '';
    });


            var panel = bar.closest('.doc-panel');
    document.getElementById('clbi-crop-confirm').addEventListener('click', function() {
            var display = panel ? panel.querySelector('.doc-display') : null;
        if (!cropper) return;
            if (!display) display = document.getElementById('doc-main-display');
            if (!display) return;


            tabs.forEach(function (tab, i) {
        var canvas = cropper.getCroppedCanvas({ width: 256, height: 256 });
                tab.addEventListener('click', function () {
        if (!canvas) return;
                    var currentIdx = tabs.findIndex(function (t) {
                        return t.classList.contains('active');
                    });
                    if (currentIdx === i) return;
                    switchTab(tabs, display, i, i > currentIdx ? 1 : -1);
                });
            });


            var initIdx = tabs.findIndex(function (t) { return t.classList.contains('active'); });
        canvas.toBlob(function(blob) {
             if (initIdx !== -1) {
            selectedFile = new File([blob], 'profile.png', { type: 'image/png' });
                var initRef = tabs[initIdx].dataset.ref;
             document.getElementById('pref-pfp-preview').src = URL.createObjectURL(blob);
                var initEl = initRef ? document.getElementById(initRef) : null;
            cModal.style.display = 'none';
                display.innerHTML = initEl ? initEl.innerHTML : (tabs[initIdx].dataset.content || '');
            cropper.destroy();
            }
            cropper = null;
        });
            document.getElementById('pref-pfp-btn').textContent = '✓ 사진 선택됨';
        }, 'image/png');
    });


     }
     var emailSaveBtn = document.getElementById('pref-email-save');
    if (emailSaveBtn) {
        emailSaveBtn.addEventListener('click', function() {
            var statusEl = document.getElementById('pref-email-status');
            var newEmail = document.getElementById('pref-new-email').value;
            var password = document.getElementById('pref-email-password').value;


    var isAnimating = false;
            if (!newEmail || !password) {
                statusEl.textContent = '이메일과 비밀번호를 입력해주세요.';
                return;
            }


    function switchTab(tabs, display, nextIdx, dir) {
            statusEl.textContent = '변경 중...';
        if (isAnimating) return;
        isAnimating = true;


        tabs.forEach(function (t) { t.classList.remove('active'); });
            api.postWithToken('csrf', {
        tabs[nextIdx].classList.add('active');
                action: 'changeemail',
                email: newEmail,
                password: password
            }).then(function() {
                statusEl.textContent = '✓ 이메일 변경됨';
                document.getElementById('pref-new-email').value = '';
                document.getElementById('pref-email-password').value = '';


        var ref = tabs[nextIdx].dataset.ref;
                setTimeout(function() {
        var nextContent;
                    statusEl.textContent = '';
        if (ref) {
                }, 3000);
            var refEl = document.getElementById(ref);
             }).fail(function(code, data) {
            nextContent = refEl ? refEl.innerHTML : '';
                var msg = data && data.error && data.error.info ? data.error.info : '변경 실패';
        } else {
                 statusEl.textContent = msg;
             nextContent = tabs[nextIdx].dataset.content || '';
        }
 
        glitchOut(display, dir, function () {
            display.innerHTML = nextContent;
            glitchIn(display, dir, function () {
                 isAnimating = false;
             });
             });
         });
         });
     }
     }


     function glitchOut(el, dir, cb) {
     saveBtn.addEventListener('click', function() {
         var duration = 160;
         var statusEl = document.getElementById('pref-status');
        var start = null;
         statusEl.textContent = '저장 중...';
         var slideX = dir * 16;


         function step(ts) {
         var promises = [];
            if (!start) start = ts;
            var p = Math.min((ts - start) / duration, 1);
            var ease = p * p;


             var tx = slideX * ease;
        if (selectedFile) {
             var skew = dir * ease * 1.0;
             var username = mw.config.get('wgUserName');
            var opacity = 1 - ease;
             promises.push(
             var rgb = ease * 5;
                api.postWithToken('csrf', {
                    action: 'upload',
                    filename: 'Pfp-' + username + '.png',
                    ignorewarnings: true,
                    file: selectedFile,
                    format: 'json'
                }, {
                    contentType: 'multipart/form-data'
                })
             );
        }


            el.style.transform = 'translateX(' + tx + 'px) skewX(' + skew + 'deg)';
        var fields = ['name', 'discord', 'role', 'bio'];
            el.style.opacity = opacity;
            el.style.filter =
                'drop-shadow(' + (-rgb) + 'px 0 0 rgba(80,160,255,0.75)) ' +
                'drop-shadow(' + rgb + 'px 0 0 rgba(255,55,90,0.65)) ' +
                'brightness(' + (1 + ease * 0.25) + ')';


            if (p < 1) {
        for (var i = 0; i < fields.length; i++) {
                requestAnimationFrame(step);
            var el = document.getElementById('pref-' + fields[i]);
             } else {
            if (!el) continue;
                 el.style.opacity = '0';
 
                 cb();
             promises.push(
             }
                 api.postWithToken('csrf', {
                    action: 'options',
                    optionname: 'profile-' + fields[i],
                    optionvalue: el.value
                 })
             );
         }
         }
        requestAnimationFrame(step);
    }


    function glitchIn(el, dir, cb) {
        $.when.apply($, promises)
        var duration = 200;
            .then(function() {
        var start = null;
                statusEl.textContent = '✓ 저장됨';
        var startX = -dir * 16;
                selectedFile = null;
                document.getElementById('pref-pfp-btn').textContent = '사진 선택';
 
                setTimeout(function() {
                    statusEl.textContent = '';
                }, 2000);
            })
            .fail(function() {
                statusEl.textContent = '저장 실패';
            });
    });
}


        el.style.transform = 'translateX(' + startX + 'px) skewX(' + (-dir * 1.0) + 'deg)';
/* =========================================
        el.style.opacity = '0';
  Banner / CRT Page Monitor thumbnail slices
  - base 이미지는 틀에 들어간 파일 문법 그대로 사용
  - slice 레이어에는 300px MediaWiki 썸네일만 삽입
  ========================================= */


        function step(ts) {
(function ($, mw) {
            if (!start) start = ts;
    var thumbCache = {};
            var p = Math.min((ts - start) / duration, 1);
            var ease = 1 - Math.pow(1 - p, 3);


            var tx = startX * (1 - ease);
    function parseSliceWidth(value) {
            var skew = -dir * 1.0 * (1 - ease);
        var parsed = parseInt(value, 10);
            var opacity = ease;
            var rgb = (1 - ease) * 3;
            var brightness = 1 + (1 - ease) * 0.35;


            el.style.transform = 'translateX(' + tx + 'px) skewX(' + skew + 'deg)';
        if (!isFinite(parsed) || parsed < 120) {
             el.style.opacity = opacity;
             return 300;
            el.style.filter =
        }
                'drop-shadow(' + (-rgb) + 'px 0 0 rgba(80,160,255,0.65)) ' +
                'drop-shadow(' + rgb + 'px 0 0 rgba(255,55,90,0.55)) ' +
                'brightness(' + brightness + ')';


            if (p < 1) {
         return parsed;
                requestAnimationFrame(step);
            } else {
                el.style.transform = '';
                el.style.opacity = '';
                el.style.filter = '';
                cb();
            }
         }
        requestAnimationFrame(step);
     }
     }


if (document.readyState === 'loading') {
    function getImageSrc(img) {
    document.addEventListener('DOMContentLoaded', initDocTabs);
        return img ? (img.currentSrc || img.getAttribute('src') || img.src || '') : '';
} else {
     }
     initDocTabs();
}


if (typeof mw !== 'undefined' && mw.hook) {
     function getFileNameFromSrc(src) {
     mw.hook('wikipage.content').add(function () {
         var a;
         initDocTabs();
        var parts;
    });
        var fileName;
}


})();
        if (!src) return '';


/* =========================================
        a = document.createElement('a');
  Doc Section Switch — 좌측 섹션 전환
        a.href = src;
  ========================================= */


$(document).on('click', '.doc-nav-item[data-section]', function () {
        parts = (a.pathname || '').split('/').filter(function (part) {
    var name = $(this).attr('data-section');
            return !!part;
    var display = document.getElementById('doc-main-display');
        });
    var titleEl = document.getElementById('doc-center-title');
    var tabBar = document.getElementById('doc-tab-bar-text');


    if (!display) return;
        if (!parts.length) return '';


    $('.doc-nav-item[data-section]').removeClass('active');
        fileName = parts.pop();
    $('.doc-nav-item[data-section="' + name + '"]').addClass('active');


    if (name === 'text') {
        /*
        if (titleEl) titleEl.textContent = '개요';
        * MediaWiki thumb URL 예시:
        if (tabBar) $(tabBar).show();
        * /images/thumb/a/ab/File.png/1000px-File.png
        var activeTab = tabBar ? tabBar.querySelector('.doc-tab.active') : null;
        * /images/thumb/a/ab/File.svg/1000px-File.svg.png
         if (!activeTab && tabBar) activeTab = tabBar.querySelector('.doc-tab');
        *
        if (activeTab) {
        * 이 경우 실제 파일명은 마지막 조각이 아니라 그 앞 조각이다.
             var ref = activeTab.dataset.ref;
        */
            var refEl = ref ? document.getElementById(ref) : null;
         if (/^\d+px-/.test(fileName) && parts.length) {
            display.innerHTML = refEl ? refEl.innerHTML : (activeTab.dataset.content || '');
             fileName = parts.pop();
         }
         }
    } else {
        if (titleEl) titleEl.textContent = name === 'factions' ? '세력' : name === 'people' ? '인물' : name;
        if (tabBar) $(tabBar).hide();
        var refEl = document.getElementById('doc-content-' + name);
        display.innerHTML = refEl ? refEl.innerHTML : '';
    }
});


/* =========================================
        fileName = fileName.replace(/^\d+px-/, '');
  CRT WebGL Renderer — cool-retro-term IBM DOS style
 
  ========================================= */
        try {
(function () {
            fileName = decodeURIComponent(fileName);
    'use strict';
        } catch (e) {}


    function createNoiseTexture(gl) {
         return fileName;
        var size = 512;
        var data = new Uint8Array(size * size * 4);
        var s = 12345;
        function rand() {
            s = (s * 1664525 + 1013904223) & 0xffffffff;
            return (s >>> 0) / 0xffffffff;
        }
        for (var i = 0; i < data.length; i++) {
            data[i] = (rand() * 255) | 0;
        }
        var tex = gl.createTexture();
        gl.bindTexture(gl.TEXTURE_2D, tex);
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
         return tex;
     }
     }


     var VERT = [
     function resolveThumbUrl(img, width, callback) {
        'attribute vec2 a_pos;',
         var src = getImageSrc(img);
        'varying vec2 v_uv;',
         var fileName = getFileNameFromSrc(src);
        'void main() {',
         var cacheKey;
         '  v_uv = vec2(a_pos.x * 0.5 + 0.5, 0.5 - a_pos.y * 0.5);',
        var entry;
         '  gl_Position = vec4(a_pos, 0.0, 1.0);',
 
         '}'
        if (!src) return;
    ].join('\n');


    var FRAG = [
         if (!fileName || !mw || !mw.loader) {
         'precision mediump float;',
            callback(src);
        'uniform sampler2D u_tex;',
            return;
        'uniform sampler2D u_noise;',
         }
         'uniform vec2 u_res;',
        'uniform vec2 u_imgSize;',
        'uniform float u_time;',
        'uniform vec2 u_noiseScale;',
        'varying vec2 v_uv;',


         'float sum2(vec2 v) { return v.x + v.y; }',
         cacheKey = fileName + '|' + width;
        'float min2(vec2 v) { return min(v.x, v.y); }',
         entry = thumbCache[cacheKey];
         'float rgb2grey(vec3 v) { return dot(v, vec3(0.21, 0.72, 0.04)); }',


         'vec2 coverUV(vec2 uv) {',
         if (entry) {
        '  float imgAR = u_imgSize.x / u_imgSize.y;',
            if (entry.resolved) {
        '  float scrAR = u_res.x / u_res.y;',
                callback(entry.url || src);
         '  float scale = imgAR / scrAR;',
            } else {
         '  float offsetY = (1.0 - scale) * 0.5;',
                entry.callbacks.push(callback);
        ' return vec2(uv.x, uv.y * scale + offsetY);',
            }
         '}',
            return;
         }
 
         entry = {
            resolved: false,
            url: '',
            callbacks: [callback]
         };


         'vec2 barrel(vec2 v, vec2 cc, float k) {',
         thumbCache[cacheKey] = entry;
        '  float ar = u_res.x / u_res.y;',
        '  vec2 c2 = cc;',
        '  if (ar > 1.0) c2.x /= ar; else c2.y *= ar;',
        '  float dist = dot(c2, c2) * k;',
        '  return v - cc * (1.0 + dist) * dist;',
        '}',


         'vec4 sampleInitialNoise(float t) {',
         function finish(url) {
        '  return texture2D(u_noise, vec2(fract(t/2048.0), fract(t/1048576.0)));',
            var callbacks = entry.callbacks.slice();
        '}',
            var i;


        'vec4 sampleScreenNoise(vec2 uv) {',
            entry.resolved = true;
        '  return texture2D(u_noise, u_noiseScale * uv);',
            entry.url = url || src;
        '}',
            entry.callbacks = [];


        'vec3 applyRgbShift(vec2 texUV, float shift) {',
            for (i = 0; i < callbacks.length; i++) {
        '  vec2 d = vec2(shift, 0.0);',
                callbacks[i](entry.url);
        '  vec3 r = texture2D(u_tex, clamp(texUV + d, 0.0, 1.0)).rgb;',
            }
        '  vec3 c = texture2D(u_tex, texUV).rgb;',
         }
        '  vec3 l = texture2D(u_tex, clamp(texUV - d, 0.0, 1.0)).rgb;',
        '  return vec3(',
        '    l.r*0.10 + r.r*0.30 + c.r*0.60,',
        '    l.g*0.20 + r.g*0.20 + c.g*0.60,',
        '    l.b*0.30 + r.b*0.10 + c.b*0.60',
        '  );',
         '}',


         'vec3 applyBloom(vec2 texUV, float strength) {',
         mw.loader.using('mediawiki.api').done(function () {
        '  vec2 px = 2.0 / u_res;',
            var api = new mw.Api();
        '  vec3 acc = vec3(0.0);',
        '  acc += texture2D(u_tex, clamp(texUV + vec2( px.x,  0.0), 0.0, 1.0)).rgb;',
        '  acc += texture2D(u_tex, clamp(texUV + vec2(-px.x,  0.0), 0.0, 1.0)).rgb;',
        ' acc += texture2D(u_tex, clamp(texUV + vec2( 0.0,  px.y), 0.0, 1.0)).rgb;',
        '  acc += texture2D(u_tex, clamp(texUV + vec2( 0.0, -px.y), 0.0, 1.0)).rgb;',
        '  acc += texture2D(u_tex, clamp(texUV + vec2( px.x,  px.y), 0.0, 1.0)).rgb * 0.5;',
        '  acc += texture2D(u_tex, clamp(texUV + vec2(-px.x,  px.y), 0.0, 1.0)).rgb * 0.5;',
        '  acc += texture2D(u_tex, clamp(texUV + vec2( px.x, -px.y), 0.0, 1.0)).rgb * 0.5;',
        '  acc += texture2D(u_tex, clamp(texUV + vec2(-px.x, -px.y), 0.0, 1.0)).rgb * 0.5;',
        '  return acc / 6.0 * strength;',
        '}',


        'vec3 applyScanlines(vec2 uv, vec3 col) {',
            api.get({
        ' float line = mod(uv.y * u_res.y, 2.0);',
                action: 'query',
        ' vec3 hi = ((1.0 + 0.30) - 0.2 * col) * col;',
                titles: 'File:' + fileName,
        ' vec3 lo = ((1.0 - 0.30) + 0.1 * col) * col;',
                prop: 'imageinfo',
        '  return line < 1.0 ? lo : hi;',
                iiprop: 'url',
        '}',
                iiurlwidth: width,
                formatversion: 2
            }).done(function (data) {
                var page;
                var info;


'vec3 applyRasterization(vec2 uv, vec3 col) {',
                if (
'  float t = u_time;',
                    data &&
'  vec2 noiseUV = uv + vec2(fract(t * 0.030), fract(t * 0.060));',
                    data.query &&
'  float wobbleX = (texture2D(u_noise, noiseUV * 0.8).r - 0.5) * 0.0018;',
                    data.query.pages &&
'  float wobbleY = (texture2D(u_noise, noiseUV * 0.8 + 0.5).r - 0.5) * 0.0008;',
                    data.query.pages.length
'  vec2 wobbledUV = clamp(uv + vec2(wobbleX, wobbleY), 0.0, 1.0);',
                ) {
'  vec3 wobbled = texture2D(u_tex, wobbledUV).rgb;',
                    page = data.query.pages[0];
'  return mix(col, wobbled, 0.35);',
'}',


        'float glowingLine(vec2 uv, float t) {',
                    if (
'  float pos = fract(t * 0.2);',
                        page &&
'  float lineY = pos * (u_res.y + 330.0) - 120.0;',
                        page.imageinfo &&
        '  float y = uv.y * u_res.y;',
                        page.imageinfo.length
        '  return fract(smoothstep(-300.0, 0.0, y - lineY));',
                    ) {
        '}',
                        info = page.imageinfo[0];
                    }
                }


        'vec2 applyHSync(vec2 uv, vec4 noise, float strength) {',
                finish((info && (info.thumburl || info.url)) || src);
        '  float randval = strength - noise.r;',
            }).fail(function () {
        '  float scale = step(0.0, randval) * randval * strength;',
                finish(src);
        '  float freq = mix(4.0, 40.0, noise.g);',
            });
         '  uv.x += sin((uv.y + u_time * 0.001) * freq) * scale;',
         }).fail(function () {
         '  return uv;',
            finish(src);
        '}',
         });
    }


        'void main() {',
    function applySliceImages(frame, thumbUrl) {
         '  vec2 cc = vec2(0.5) - v_uv;',
         var slices;
        var i;
        var img;


         '  float curvature = 0.18;',
         if (!frame || !thumbUrl) return;
        '  vec2 uv = barrel(v_uv, cc, curvature);',


         '  float inScreen = min2(step(vec2(0.0), uv) - step(vec2(1.0), uv));',
         slices = frame.querySelectorAll('.crt-page-monitor-slice');
        ' if (inScreen < 0.5) { gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); return; }',


         '  vec2 texUV = clamp(coverUV(uv), 0.0, 1.0);',
         for (i = 0; i < slices.length; i++) {
            slices[i].innerHTML = '';


        '  vec4 initNoise = sampleInitialNoise(u_time);',
            img = document.createElement('img');
        ' vec4 screenNoise = sampleScreenNoise(uv);',
            img.className = 'crt-page-monitor-slice-img';
            img.src = thumbUrl;
            img.alt = '';
            img.decoding = 'async';
            img.loading = 'eager';
            img.setAttribute('aria-hidden', 'true');


        '  texUV = applyHSync(texUV, initNoise, 0.006);',
            slices[i].appendChild(img);
         '  texUV = clamp(texUV, 0.0, 1.0);',
         }


         ' texUV += (vec2(screenNoise.b, screenNoise.a) - 0.5) * 0.0006;',
         frame.setAttribute('data-crt-slices-ready', '1');
        ' texUV = clamp(texUV, 0.0, 1.0);',
    }


        '  vec3 col = applyRgbShift(texUV, 0.003);',
    function initBannerFrame(frame) {
         '  col += applyBloom(texUV, 0.22);',
        var baseImg;
         var width;


         '  vec2 bpx = 1.5 / u_res;',
         if (!frame) return;
        '  vec3 blurCol = vec3(0.0);',
         if (frame.getAttribute('data-crt-slices-ready') === '1') return;
         '  blurCol += texture2D(u_tex, clamp(texUV + vec2(-bpx.x, -bpx.y), 0.0, 1.0)).rgb;',
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2( 0.0,  -bpx.y), 0.0, 1.0)).rgb;',
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2( bpx.x, -bpx.y), 0.0, 1.0)).rgb;',
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2(-bpx.x,  0.0  ), 0.0, 1.0)).rgb;',
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2( bpx.x,  0.0  ), 0.0, 1.0)).rgb;',
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2(-bpx.x,  bpx.y), 0.0, 1.0)).rgb;',
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2( 0.0,    bpx.y), 0.0, 1.0)).rgb;',
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2( bpx.x,  bpx.y), 0.0, 1.0)).rgb;',
        '  col = mix(col, blurCol / 8.0, 0.40);',


         '  col = applyScanlines(uv, col);',
         baseImg = frame.querySelector('.crt-page-monitor-image-base img');
        ' col = applyRasterization(texUV, col);',


         '  float glow = glowingLine(uv, u_time);',
         if (!baseImg) return;
'  col += glow * 0.08 * vec3(0.85, 0.95, 1.0);',


         '  float dist = length(cc);',
         width = parseSliceWidth(frame.getAttribute('data-crt-slice-width'));
        '  col += screenNoise.a * 0.07 * (1.0 - dist * 1.3);',


         '  float grey = rgb2grey(col);',
         resolveThumbUrl(baseImg, width, function (thumbUrl) {
        '  vec3 phosphor = vec3(0.75, 0.88, 1.0);',
            if (!frame || !frame.parentNode) return;
         '  col = mix(col, grey * phosphor, 0.35);',
            applySliceImages(frame, thumbUrl);
         });
    }


         '  vec2 vig = v_uv * (1.0 - v_uv);',
    function initBannerFrames(root) {
         '  col *= pow(vig.x * vig.y * 15.0, 0.25);',
         var scope = root && root.querySelectorAll ? root : document;
         var frames = scope.querySelectorAll('.crt-page-monitor-frame');
        var i;


         '  col *= 1.0 + (initNoise.g - 0.5) * 0.06;',
         for (i = 0; i < frames.length; i++) {
 
            initBannerFrame(frames[i]);
        '  col += vec3(0.012) * (1.0 - dist) * (1.0 - dist);',
        }
    }


        '  col = pow(clamp(col, 0.0, 1.0), vec3(0.90));',
    $(function () {
        initBannerFrames(document);
    });


         ' gl_FragColor = vec4(col, 1.0);',
    if (mw && mw.hook) {
         '}'
         mw.hook('wikipage.content').add(function ($content) {
     ].join('\n');
            initBannerFrames($content && $content[0] ? $content[0] : document);
         });
     }
})(jQuery, window.mw);


    function initCRTCanvas(screen, imgEl) {
/* =========================================
        var existing = screen.querySelector('.crt-webgl-canvas');
  Doc Tab System — tab switching UI
        if (existing) existing.remove();
  글리치 플리커 + RGB split + 방향 슬라이드
  ========================================= */


        var canvas = document.createElement('canvas');
(function () {
        canvas.className = 'crt-webgl-canvas';
    'use strict';
        canvas.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;z-index:19;pointer-events:none;display:block;';
        screen.appendChild(canvas);


         var gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
    function initDocTabs() {
         if (!gl) return;
         var tabBars = document.querySelectorAll('.doc-tab-bar');
         if (!tabBars.length) return;


         function compile(type, src) {
         tabBars.forEach(function (bar) {
             var s = gl.createShader(type);
             if (bar.getAttribute('data-tabs-init')) return;
            gl.shaderSource(s, src);
             bar.setAttribute('data-tabs-init', '1');
            gl.compileShader(s);
             if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
                console.error('[CRT shader]', gl.getShaderInfoLog(s));
            }
            return s;
        }


        var prog = gl.createProgram();
            var tabs = Array.from(bar.querySelectorAll('.doc-tab'));
        gl.attachShader(prog, compile(gl.VERTEX_SHADER, VERT));
            if (!tabs.length) return;
        gl.attachShader(prog, compile(gl.FRAGMENT_SHADER, FRAG));
        gl.linkProgram(prog);
        gl.useProgram(prog);


        var buf = gl.createBuffer();
            var panel = bar.closest('.doc-panel');
        gl.bindBuffer(gl.ARRAY_BUFFER, buf);
            var display = panel ? panel.querySelector('.doc-display') : null;
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1,-1, 1,-1, -1,1, 1,1]), gl.STATIC_DRAW);
            if (!display) display = document.getElementById('doc-main-display');
        var aPos = gl.getAttribLocation(prog, 'a_pos');
            if (!display) return;
        gl.enableVertexAttribArray(aPos);
        gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);


        var uTex    = gl.getUniformLocation(prog, 'u_tex');
            tabs.forEach(function (tab, i) {
        var uNoise  = gl.getUniformLocation(prog, 'u_noise');
                tab.addEventListener('click', function () {
        var uRes    = gl.getUniformLocation(prog, 'u_res');
                    var currentIdx = tabs.findIndex(function (t) {
        var uImgSize = gl.getUniformLocation(prog, 'u_imgSize');
                        return t.classList.contains('active');
        var uTime    = gl.getUniformLocation(prog, 'u_time');
                    });
        var uNoiseSc = gl.getUniformLocation(prog, 'u_noiseScale');
                    if (currentIdx === i) return;
                    switchTab(tabs, display, i, i > currentIdx ? 1 : -1);
                });
            });
 
            var initIdx = tabs.findIndex(function (t) { return t.classList.contains('active'); });
            if (initIdx !== -1) {
                var initRef = tabs[initIdx].dataset.ref;
                var initEl = initRef ? document.getElementById(initRef) : null;
                display.innerHTML = initEl ? initEl.innerHTML : (tabs[initIdx].dataset.content || '');
            }
        });
 
    }


        var imgTex = gl.createTexture();
    var isAnimating = false;
        gl.activeTexture(gl.TEXTURE0);
        gl.bindTexture(gl.TEXTURE_2D, imgTex);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);


         gl.activeTexture(gl.TEXTURE1);
    function switchTab(tabs, display, nextIdx, dir) {
         createNoiseTexture(gl);
         if (isAnimating) return;
         isAnimating = true;


         var texReady = false;
         tabs.forEach(function (t) { t.classList.remove('active'); });
        function uploadImg() {
        tabs[nextIdx].classList.add('active');
            if (!imgEl || !imgEl.complete || !imgEl.naturalWidth) return;
            try {
                gl.activeTexture(gl.TEXTURE0);
                gl.bindTexture(gl.TEXTURE_2D, imgTex);
                gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, imgEl);
                texReady = true;
            } catch(e) { console.error('[CRT] tex:', e); }
        }


         var lastW = 0, lastH = 0;
         var ref = tabs[nextIdx].dataset.ref;
         function resize() {
        var nextContent;
             var w = screen.offsetWidth, h = screen.offsetHeight;
         if (ref) {
            if (w === lastW && h === lastH) return;
             var refEl = document.getElementById(ref);
             lastW = w; lastH = h;
             nextContent = refEl ? refEl.innerHTML : '';
             canvas.width = w; canvas.height = h;
        } else {
            gl.viewport(0, 0, w, h);
             nextContent = tabs[nextIdx].dataset.content || '';
         }
         }


         var raf;
         glitchOut(display, dir, function () {
         var t0 = performance.now();
            display.innerHTML = nextContent;
            glitchIn(display, dir, function () {
                isAnimating = false;
            });
         });
    }


        function render() {
    function glitchOut(el, dir, cb) {
            raf = requestAnimationFrame(render);
        var duration = 160;
            if (!texReady) { uploadImg(); return; }
        var start = null;
            resize();
        var slideX = dir * 16;
            var t = (performance.now() - t0) / 1000;
 
            gl.uniform1i(uTex, 0);
        function step(ts) {
            gl.uniform1i(uNoise, 1);
             if (!start) start = ts;
             gl.uniform2f(uRes, canvas.width, canvas.height);
             var p = Math.min((ts - start) / duration, 1);
             gl.uniform2f(uImgSize, imgEl.naturalWidth, imgEl.naturalHeight);
             var ease = p * p;
            gl.uniform1f(uTime, t);
            gl.uniform2f(uNoiseSc, canvas.width / 512.0, canvas.height / 512.0);
             gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
        }


        if (imgEl.complete && imgEl.naturalWidth) { uploadImg(); }
            var tx = slideX * ease;
        else { imgEl.addEventListener('load', uploadImg); }
            var skew = dir * ease * 1.0;
            var opacity = 1 - ease;
            var rgb = ease * 5;


        render();
            el.style.transform = 'translateX(' + tx + 'px) skewX(' + skew + 'deg)';
        screen._crtCleanup = function () { cancelAnimationFrame(raf); };
            el.style.opacity = opacity;
    }
            el.style.filter =
                'drop-shadow(' + (-rgb) + 'px 0 0 rgba(80,160,255,0.75)) ' +
                'drop-shadow(' + rgb + 'px 0 0 rgba(255,55,90,0.65)) ' +
                'brightness(' + (1 + ease * 0.25) + ')';


    function initAllCRTScreens(root) {
             if (p < 1) {
        var scope = root && root.querySelectorAll ? root : document;
                 requestAnimationFrame(step);
        scope.querySelectorAll('.crt-page-monitor-screen').forEach(function (screen) {
             if (screen.getAttribute('data-crt-webgl') === '1') return;
            screen.setAttribute('data-crt-webgl', '1');
            var frame = screen.closest('.crt-page-monitor-frame');
            if (!frame) return;
            var imgEl = frame.querySelector('.crt-page-monitor-slice-img, .crt-page-monitor-image-base img');
            if (imgEl && imgEl.complete && imgEl.naturalWidth) {
                initCRTCanvas(screen, imgEl);
            } else if (imgEl) {
                 imgEl.addEventListener('load', function () { initCRTCanvas(screen, imgEl); });
             } else {
             } else {
                 var obs = new MutationObserver(function () {
                 el.style.opacity = '0';
                    var img = frame.querySelector('.crt-page-monitor-slice-img');
                 cb();
                    if (!img) return;
                    obs.disconnect();
                    if (img.complete && img.naturalWidth) {
                        initCRTCanvas(screen, img);
                    } else {
                        img.addEventListener('load', function () { initCRTCanvas(screen, img); });
                    }
                 });
                obs.observe(frame, { childList: true, subtree: true });
             }
             }
         });
         }
        requestAnimationFrame(step);
     }
     }


     $(function () { initAllCRTScreens(document); });
     function glitchIn(el, dir, cb) {
 
        var duration = 200;
    if (typeof mw !== 'undefined' && mw.hook) {
         var start = null;
         mw.hook('wikipage.content').add(function ($c) {
        var startX = -dir * 16;
            document.querySelectorAll('.crt-page-monitor-screen').forEach(function (s) {
                if (s._crtCleanup) s._crtCleanup();
                s.removeAttribute('data-crt-webgl');
            });
            initAllCRTScreens($c && $c[0] ? $c[0] : document);
        });
    }
})();


/* =========================================
        el.style.transform = 'translateX(' + startX + 'px) skewX(' + (-dir * 1.0) + 'deg)';
Progress System UI
        el.style.opacity = '0';
MediaWiki:Common.js controlled frontend
========================================= */
(function (mw, $) {
    'use strict';


    if (window.ProgressSystemWebUiInitialized) return;
        function step(ts) {
    window.ProgressSystemWebUiInitialized = true;
            if (!start) start = ts;
            var p = Math.min((ts - start) / duration, 1);
            var ease = 1 - Math.pow(1 - p, 3);


    var api = null;
            var tx = startX * (1 - ease);
            var skew = -dir * 1.0 * (1 - ease);
            var opacity = ease;
            var rgb = (1 - ease) * 3;
            var brightness = 1 + (1 - ease) * 0.35;


    function withApi(done, fail) {
            el.style.transform = 'translateX(' + tx + 'px) skewX(' + skew + 'deg)';
        if (api) {
            el.style.opacity = opacity;
            done(api);
            el.style.filter =
            return;
                'drop-shadow(' + (-rgb) + 'px 0 0 rgba(80,160,255,0.65)) ' +
        }
                'drop-shadow(' + rgb + 'px 0 0 rgba(255,55,90,0.55)) ' +
                'brightness(' + brightness + ')';


        if (!mw.loader || typeof mw.loader.using !== 'function') {
            if (p < 1) {
            if (typeof fail === 'function') fail();
                requestAnimationFrame(step);
             return;
            } else {
                el.style.transform = '';
                el.style.opacity = '';
                el.style.filter = '';
                cb();
             }
         }
         }
 
         requestAnimationFrame(step);
         mw.loader.using(['mediawiki.api']).then(function () {
            api = new mw.Api();
            done(api);
        }, function () {
            if (typeof fail === 'function') fail();
        });
     }
     }


    var inFlightPageIds = new Set();
if (document.readyState === 'loading') {
     var handledPageIds = new Set();
     document.addEventListener('DOMContentLoaded', initDocTabs);
    var notificationQueue = [];
} else {
     var notificationActive = false;
     initDocTabs();
    var summaryRequested = false;
}
    var currentSummary = null;
    var pendingSummary = null;
    var pendingOptions = null;
    var visibilityBound = false;
    var barTimerA = null;
    var barTimerB = null;
    var barTimerC = null;
    var summaryRetryTimer = null;
    var summaryRetryAttempts = 0;


    function isLoggedIn() {
if (typeof mw !== 'undefined' && mw.hook) {
        return !!mw.config.get('wgUserName');
    mw.hook('wikipage.content').add(function () {
     }
        initDocTabs();
     });
}


    function getPageId() {
})();
        var id = parseInt(mw.config.get('wgArticleId') || 0, 10);
        return Number.isFinite(id) ? id : 0;
    }


    function isRewardableClientSide() {
/* =========================================
        if (!isLoggedIn()) return false;
  Doc Section Switch — 좌측 섹션 전환
        if (parseInt(mw.config.get('wgNamespaceNumber'), 10) !== 0) return false;
  ========================================= */
        if (mw.config.get('wgIsMainPage')) return false;
        if (getPageId() <= 0) return false;
        return true;
    }


    function getPanelHtml() {
$(document).on('click', '.doc-nav-item[data-section]', function () {
        return '' +
    var name = $(this).attr('data-section');
            '<div id="progress-panel" class="profile-progress-block is-syncing" aria-live="polite" data-progress-state="syncing">' +
    var display = document.getElementById('doc-main-display');
                '<div class="progress-title-row" hidden></div>' +
    var titleEl = document.getElementById('doc-center-title');
                '<div class="progress-level-row">' +
    var tabBar = document.getElementById('doc-tab-bar-text');
                    '<span class="progress-level-label">SYNC</span>' +
                    '<span class="progress-total-xp">— XP</span>' +
                '</div>' +
                '<div class="progress-xp-bar" aria-hidden="true">' +
                    '<div class="progress-xp-gain"></div>' +
                    '<div class="progress-xp-fill"></div>' +
                '</div>' +
                '<div class="progress-sub-row">' +
                    '<span class="progress-xp-next">SYNCING</span>' +
                    '<span class="progress-daily-xp">TODAY —</span>' +
                '</div>' +
                '<div class="progress-discovery-row">DISCOVERED —</div>' +
            '</div>';
    }


     function getDividerHtml() {
     if (!display) return;
        /* 프로필 패널 최신 규칙: 레벨 패널과 버튼 영역 사이에 별도 나눔선은 만들지 않는다. */
        return '';
    }


     function setPanelSync($panel) {
     $('.doc-nav-item[data-section]').removeClass('active');
        if (!$panel || !$panel.length) return;
    $('.doc-nav-item[data-section="' + name + '"]').addClass('active');


        $panel.addClass('is-syncing').removeClass('is-max-level').attr('data-progress-state', 'syncing');
    if (name === 'text') {
         $panel.find('.progress-title-row').text('').prop('hidden', true);
        if (titleEl) titleEl.textContent = '개요';
         $panel.find('.progress-level-label').text('SYNC');
         if (tabBar) $(tabBar).show();
         $panel.find('.progress-total-xp').text('— XP');
         var activeTab = tabBar ? tabBar.querySelector('.doc-tab.active') : null;
        $panel.find('.progress-xp-next').text('SYNCING');
         if (!activeTab && tabBar) activeTab = tabBar.querySelector('.doc-tab');
        $panel.find('.progress-daily-xp').text('TODAY —');
        if (activeTab) {
         $panel.find('.progress-discovery-row').text('DISCOVERED —');
            var ref = activeTab.dataset.ref;
         $panel.find('.progress-xp-fill').css({ transition: 'none', width: '0%' });
            var refEl = ref ? document.getElementById(ref) : null;
         $panel.find('.progress-xp-gain').css({ transition: 'none', width: '0%', opacity: 0 });
            display.innerHTML = refEl ? refEl.innerHTML : (activeTab.dataset.content || '');
         }
    } else {
        if (titleEl) titleEl.textContent = name === 'factions' ? '세력' : name === 'people' ? '인물' : name;
         if (tabBar) $(tabBar).hide();
         var refEl = document.getElementById('doc-content-' + name);
        display.innerHTML = refEl ? refEl.innerHTML : '';
     }
     }
});


    function placePanel($panel) {
/* =========================================
        var $right = $('#clbi-right-sidebar');
  CRT WebGL Renderer — cool-retro-term IBM DOS style
        if (!$right.length) return false;
  ========================================= */
(function () {
    'use strict';


        var $userBox = $right.children('.clbi-right-box').first();
    function createNoiseTexture(gl) {
         if (!$userBox.length) return false;
         var size = 512;
 
         var data = new Uint8Array(size * size * 4);
         var $buttonArea = $userBox.children('.clbi-right-content').first();
         var s = 12345;
         var $oldFallback = $panel.closest('.progress-panel-fallback');
         function rand() {
 
             s = (s * 1664525 + 1013904223) & 0xffffffff;
         if ($buttonArea.length) {
             return (s >>> 0) / 0xffffffff;
             var $divider = $('#profile-progress-divider');
 
             $panel.insertBefore($buttonArea);
 
            if (!$divider.length) {
                $divider = $(getDividerHtml());
            }
 
            $divider.insertAfter($panel);
        } else {
            $('#profile-progress-divider').remove();
            $userBox.append($panel);
         }
         }
 
         for (var i = 0; i < data.length; i++) {
         if ($oldFallback.length && !$oldFallback.find('#progress-panel').length) {
             data[i] = (rand() * 255) | 0;
             $oldFallback.remove();
         }
         }
 
        var tex = gl.createTexture();
         return true;
        gl.bindTexture(gl.TEXTURE_2D, tex);
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
         return tex;
     }
     }


     function ensurePanel() {
     var VERT = [
         if (!isLoggedIn()) return $();
        'attribute vec2 a_pos;',
        'varying vec2 v_uv;',
        'void main() {',
         '  v_uv = vec2(a_pos.x * 0.5 + 0.5, 0.5 - a_pos.y * 0.5);',
        '  gl_Position = vec4(a_pos, 0.0, 1.0);',
        '}'
    ].join('\n');


        var $right = $('#clbi-right-sidebar');
    var FRAG = [
         if (!$right.length) return $();
        'precision mediump float;',
        'uniform sampler2D u_tex;',
        'uniform sampler2D u_noise;',
         'uniform vec2 u_res;',
        'uniform vec2 u_imgSize;',
        'uniform float u_time;',
        'uniform vec2 u_noiseScale;',
        'varying vec2 v_uv;',


         var $panel = $('#progress-panel');
         'float sum2(vec2 v) { return v.x + v.y; }',
        'float min2(vec2 v) { return min(v.x, v.y); }',
        'float rgb2grey(vec3 v) { return dot(v, vec3(0.21, 0.72, 0.04)); }',


         if (!$panel.length) {
         'vec2 coverUV(vec2 uv) {',
            $panel = $(getPanelHtml());
        '  float imgAR = u_imgSize.x / u_imgSize.y;',
            if (!placePanel($panel)) return $();
        '  float scrAR = u_res.x / u_res.y;',
            setPanelSync($panel);
        '  float scale = imgAR / scrAR;',
         } else {
         '  float offsetY = (1.0 - scale) * 0.5;',
            $panel.addClass('profile-progress-block');
        '  return vec2(uv.x, uv.y * scale + offsetY);',
            placePanel($panel);
        '}',


            if (!currentSummary && $panel.attr('data-progress-state') !== 'syncing') {
        'vec2 barrel(vec2 v, vec2 cc, float k) {',
                setPanelSync($panel);
        '  float ar = u_res.x / u_res.y;',
            }
        '  vec2 c2 = cc;',
         }
        ' if (ar > 1.0) c2.x /= ar; else c2.y *= ar;',
        ' float dist = dot(c2, c2) * k;',
        '  return v - cc * (1.0 + dist) * dist;',
         '}',


         return $('#progress-panel');
         'vec4 sampleInitialNoise(float t) {',
    }
        ' return texture2D(u_noise, vec2(fract(t/2048.0), fract(t/1048576.0)));',
        '}',


    function clampPercent(value) {
        'vec4 sampleScreenNoise(vec2 uv) {',
         return Math.max(0, Math.min(100, value || 0));
         return texture2D(u_noise, u_noiseScale * uv);',
    }
        '}',


    function hasXpNotification(items) {
        'vec3 applyRgbShift(vec2 texUV, float shift) {',
         if (!items || !items.length) return false;
        '  vec2 d = vec2(shift, 0.0);',
         return items.some(function (item) {
         '  vec3 r = texture2D(u_tex, clamp(texUV + d, 0.0, 1.0)).rgb;',
            return item && item.type === 'xp' && parseInt(item.amount || 0, 10) > 0;
         '  vec3 c = texture2D(u_tex, texUV).rgb;',
         });
        '  vec3 l = texture2D(u_tex, clamp(texUV - d, 0.0, 1.0)).rgb;',
    }
        '  return vec3(',
        '    l.r*0.10 + r.r*0.30 + c.r*0.60,',
        '   l.g*0.20 + r.g*0.20 + c.g*0.60,',
        '    l.b*0.30 + r.b*0.10 + c.b*0.60',
         );',
        '}',


    function clearBarTimers() {
        'vec3 applyBloom(vec2 texUV, float strength) {',
         [barTimerA, barTimerB, barTimerC].forEach(function (timer) {
        '  vec2 px = 2.0 / u_res;',
            if (timer) clearTimeout(timer);
        '  vec3 acc = vec3(0.0);',
         });
         '  acc += texture2D(u_tex, clamp(texUV + vec2( px.x,  0.0), 0.0, 1.0)).rgb;',
         barTimerA = null;
        '  acc += texture2D(u_tex, clamp(texUV + vec2(-px.x,  0.0), 0.0, 1.0)).rgb;',
         barTimerB = null;
        '  acc += texture2D(u_tex, clamp(texUV + vec2( 0.0,  px.y), 0.0, 1.0)).rgb;',
         barTimerC = null;
        '  acc += texture2D(u_tex, clamp(texUV + vec2( 0.0, -px.y), 0.0, 1.0)).rgb;',
    }
         '  acc += texture2D(u_tex, clamp(texUV + vec2( px.x,  px.y), 0.0, 1.0)).rgb * 0.5;',
         '  acc += texture2D(u_tex, clamp(texUV + vec2(-px.x,  px.y), 0.0, 1.0)).rgb * 0.5;',
         '  acc += texture2D(u_tex, clamp(texUV + vec2( px.x, -px.y), 0.0, 1.0)).rgb * 0.5;',
         '  acc += texture2D(u_tex, clamp(texUV + vec2(-px.x, -px.y), 0.0, 1.0)).rgb * 0.5;',
        '  return acc / 6.0 * strength;',
        '}',


    function setBarInstant($fill, $gain, percent) {
        'vec3 applyScanlines(vec2 uv, vec3 col) {',
         clearBarTimers();
         '  float line = mod(uv.y * u_res.y, 2.0);',
         percent = clampPercent(percent);
         '  vec3 hi = ((1.0 + 0.30) - 0.2 * col) * col;',
        $fill.css({ transition: 'none', width: percent + '%' });
         '  vec3 lo = ((1.0 - 0.30) + 0.1 * col) * col;',
        $gain.css({ transition: 'none', left: '0%', width: '0%', opacity: 0 });
         '  return line < 1.0 ? lo : hi;',
         if ($fill[0]) $fill[0].offsetHeight;
         '}',
         $fill.css({ transition: '' });
         $gain.css({ transition: '' });
    }


    function animateGain($fill, $gain, fromPercent, toPercent, levelChanged) {
'vec3 applyRasterization(vec2 uv, vec3 col) {',
        clearBarTimers();
'  float t = u_time;',
'  vec2 noiseUV = uv + vec2(fract(t * 0.030), fract(t * 0.060));',
'  float wobbleX = (texture2D(u_noise, noiseUV * 0.8).r - 0.5) * 0.0018;',
'  float wobbleY = (texture2D(u_noise, noiseUV * 0.8 + 0.5).r - 0.5) * 0.0008;',
'  vec2 wobbledUV = clamp(uv + vec2(wobbleX, wobbleY), 0.0, 1.0);',
'  vec3 wobbled = texture2D(u_tex, wobbledUV).rgb;',
'  return mix(col, wobbled, 0.35);',
'}',


         fromPercent = clampPercent(fromPercent);
         'float glowingLine(vec2 uv, float t) {',
         toPercent = clampPercent(toPercent);
'  float pos = fract(t * 0.2);',
'  float lineY = pos * (u_res.y + 330.0) - 120.0;',
         '  float y = uv.y * u_res.y;',
        '  return fract(smoothstep(-300.0, 0.0, y - lineY));',
        '}',


         $fill.css({ transition: 'none', width: fromPercent + '%' });
         'vec2 applyHSync(vec2 uv, vec4 noise, float strength) {',
        '  float randval = strength - noise.r;',
        '  float scale = step(0.0, randval) * randval * strength;',
        ' float freq = mix(4.0, 40.0, noise.g);',
        '  uv.x += sin((uv.y + u_time * 0.001) * freq) * scale;',
        ' return uv;',
        '}',


         if (levelChanged) {
         'void main() {',
            var firstDelta = Math.max(0, 100 - fromPercent);
        '  vec2 cc = vec2(0.5) - v_uv;',


            $gain.css({
        '  float curvature = 0.18;',
                transition: 'none',
        '  vec2 uv = barrel(v_uv, cc, curvature);',
                opacity: firstDelta > 0 ? 1 : 0,
                left: fromPercent + '%',
                width: firstDelta + '%'
            });


            if ($fill[0]) $fill[0].offsetHeight;
        '  float inScreen = min2(step(vec2(0.0), uv) - step(vec2(1.0), uv));',
        '  if (inScreen < 0.5) { gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); return; }',


            barTimerA = setTimeout(function () {
        '  vec2 texUV = clamp(coverUV(uv), 0.0, 1.0);',
                $fill.css({
                    transition: 'width 540ms cubic-bezier(0.22, 0.7, 0.18, 1)',
                    width: '100%'
                });
            }, 260);


            barTimerB = setTimeout(function () {
        '  vec4 initNoise = sampleInitialNoise(u_time);',
                $fill.css({ transition: 'none', width: '0%' });
        ' vec4 screenNoise = sampleScreenNoise(uv);',
                $gain.css({ transition: 'none', opacity: toPercent > 0 ? 1 : 0, left: '0%', width: toPercent + '%' });


                if ($fill[0]) $fill[0].offsetHeight;
        '  texUV = applyHSync(texUV, initNoise, 0.006);',
        '  texUV = clamp(texUV, 0.0, 1.0);',


                $fill.css({
        '  texUV += (vec2(screenNoise.b, screenNoise.a) - 0.5) * 0.0006;',
                    transition: 'width 460ms cubic-bezier(0.22, 0.7, 0.18, 1)',
        ' texUV = clamp(texUV, 0.0, 1.0);',
                    width: toPercent + '%'
                });
            }, 860);


            barTimerC = setTimeout(function () {
        '  vec3 col = applyRgbShift(texUV, 0.003);',
                $gain.css({ transition: 'opacity 180ms ease', opacity: 0 });
        '  col += applyBloom(texUV, 0.22);',
            }, 1380);


            return;
        '  vec2 bpx = 1.5 / u_res;',
         }
        '  vec3 blurCol = vec3(0.0);',
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2(-bpx.x, -bpx.y), 0.0, 1.0)).rgb;',
         '  blurCol += texture2D(u_tex, clamp(texUV + vec2( 0.0,  -bpx.y), 0.0, 1.0)).rgb;',
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2( bpx.x, -bpx.y), 0.0, 1.0)).rgb;',
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2(-bpx.x,  0.0  ), 0.0, 1.0)).rgb;',
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2( bpx.x,  0.0  ), 0.0, 1.0)).rgb;',
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2(-bpx.x,  bpx.y), 0.0, 1.0)).rgb;',
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2( 0.0,    bpx.y), 0.0, 1.0)).rgb;',
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2( bpx.x,  bpx.y), 0.0, 1.0)).rgb;',
        '  col = mix(col, blurCol / 8.0, 0.40);',


         var delta = Math.max(0, toPercent - fromPercent);
         '  col = applyScanlines(uv, col);',
        '  col = applyRasterization(texUV, col);',
 
        '  float glow = glowingLine(uv, u_time);',
'  col += glow * 0.08 * vec3(0.85, 0.95, 1.0);',


         if (delta <= 0.15) {
         '  float dist = length(cc);',
            setBarInstant($fill, $gain, toPercent);
        '  col += screenNoise.a * 0.07 * (1.0 - dist * 1.3);',
            return;
        }


         $gain.css({
         '  float grey = rgb2grey(col);',
            transition: 'none',
        ' vec3 phosphor = vec3(0.75, 0.88, 1.0);',
            opacity: 1,
        ' col = mix(col, grey * phosphor, 0.35);',
            left: fromPercent + '%',
            width: delta + '%'
        });


         if ($fill[0]) $fill[0].offsetHeight;
         '  vec2 vig = v_uv * (1.0 - v_uv);',
        '  col *= pow(vig.x * vig.y * 15.0, 0.25);',


         barTimerA = setTimeout(function () {
         '  col *= 1.0 + (initNoise.g - 0.5) * 0.06;',
            $fill.css({
                transition: 'width 560ms cubic-bezier(0.22, 0.7, 0.18, 1)',
                width: toPercent + '%'
            });
        }, 260);


         barTimerB = setTimeout(function () {
         '  col += vec3(0.012) * (1.0 - dist) * (1.0 - dist);',
            $gain.css({ transition: 'opacity 180ms ease', opacity: 0 });
        }, 940);
    }


    function updatePanel(summary, options) {
        '  col = pow(clamp(col, 0.0, 1.0), vec3(0.90));',
        if (!summary) return;


         options = options || {};
         '  gl_FragColor = vec4(col, 1.0);',
        '}'
    ].join('\n');


         var $panel = ensurePanel();
    function initCRTCanvas(screen, imgEl) {
         if (!$panel.length) {
         var existing = screen.querySelector('.crt-webgl-canvas');
            pendingSummary = $.extend({}, summary);
         if (existing) existing.remove();
            pendingOptions = $.extend({}, options);
            return;
        }


         var level = summary.level || 1;
         var canvas = document.createElement('canvas');
         var totalXp = summary.totalXp || 0;
         canvas.className = 'crt-webgl-canvas';
         var xpIntoLevel = summary.xpIntoLevel || 0;
         canvas.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;z-index:19;pointer-events:none;display:block;';
        var xpForNext = summary.xpForNextLevel || 1;
         screen.appendChild(canvas);
        var percent = clampPercent(summary.progressPercent);
        var isMaxLevel = !!summary.isMaxLevel;
        var dailyXp = summary.dailyXp || 0;
        var discoveries = summary.discoveryCount || 0;
         var title = summary.equippedTitle || summary.title || '';


         $panel.removeClass('is-syncing').toggleClass('is-max-level', isMaxLevel).attr('data-progress-state', 'ready');
         var gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
        $panel.find('.progress-level-label').text((isMaxLevel ? 'MAX ' : 'LVL ') + level);
         if (!gl) return;
        $panel.find('.progress-total-xp').text(totalXp + ' XP');
        $panel.find('.progress-xp-next').text(isMaxLevel ? 'MAX LEVEL' : (xpIntoLevel + ' / ' + xpForNext + ' TO NEXT'));
         $panel.find('.progress-daily-xp').text('TODAY ' + dailyXp + ' XP');
        $panel.find('.progress-discovery-row').text('DISCOVERED ' + discoveries);


         var $title = $panel.find('.progress-title-row');
         function compile(type, src) {
        if (title) {
            var s = gl.createShader(type);
             $title.text(title).prop('hidden', false);
            gl.shaderSource(s, src);
        } else {
             gl.compileShader(s);
            $title.text('').prop('hidden', true);
            if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
                console.error('[CRT shader]', gl.getShaderInfoLog(s));
            }
            return s;
         }
         }


         var $fill = $panel.find('.progress-xp-fill');
         var prog = gl.createProgram();
         var $gain = $panel.find('.progress-xp-gain');
        gl.attachShader(prog, compile(gl.VERTEX_SHADER, VERT));
         var animate = !!options.animateGain && currentSummary && totalXp > (currentSummary.totalXp || 0);
         gl.attachShader(prog, compile(gl.FRAGMENT_SHADER, FRAG));
         gl.linkProgram(prog);
        gl.useProgram(prog);


         if (animate) {
         var buf = gl.createBuffer();
            animateGain(
        gl.bindBuffer(gl.ARRAY_BUFFER, buf);
                $fill,
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1,-1, 1,-1, -1,1, 1,1]), gl.STATIC_DRAW);
                $gain,
        var aPos = gl.getAttribLocation(prog, 'a_pos');
                clampPercent(currentSummary.progressPercent),
        gl.enableVertexAttribArray(aPos);
                percent,
         gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);
                level !== (currentSummary.level || 1)
            );
         } else {
            setBarInstant($fill, $gain, percent);
        }


         currentSummary = $.extend({}, summary);
         var uTex    = gl.getUniformLocation(prog, 'u_tex');
         pendingSummary = null;
         var uNoise  = gl.getUniformLocation(prog, 'u_noise');
         pendingOptions = null;
         var uRes    = gl.getUniformLocation(prog, 'u_res');
         if (summaryRetryTimer) {
         var uImgSize = gl.getUniformLocation(prog, 'u_imgSize');
            clearTimeout(summaryRetryTimer);
        var uTime    = gl.getUniformLocation(prog, 'u_time');
            summaryRetryTimer = null;
         var uNoiseSc = gl.getUniformLocation(prog, 'u_noiseScale');
        }
         summaryRetryAttempts = 0;
    }


    function clearSummaryRetry() {
        var imgTex = gl.createTexture();
         if (summaryRetryTimer) clearTimeout(summaryRetryTimer);
         gl.activeTexture(gl.TEXTURE0);
         summaryRetryTimer = null;
        gl.bindTexture(gl.TEXTURE_2D, imgTex);
         summaryRetryAttempts = 0;
         gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    }
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
         gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);


    function scheduleSummaryRetry(delay) {
         gl.activeTexture(gl.TEXTURE1);
        if (!isLoggedIn()) return;
         createNoiseTexture(gl);
         if (summaryRetryTimer) return;
         if (summaryRetryAttempts >= 12) return;


         summaryRetryAttempts += 1;
         var texReady = false;
         summaryRetryTimer = setTimeout(function () {
         function uploadImg() {
             summaryRetryTimer = null;
             if (!imgEl || !imgEl.complete || !imgEl.naturalWidth) return;
             requestSummary();
             try {
        }, delay || 1800);
                gl.activeTexture(gl.TEXTURE0);
    }
                gl.bindTexture(gl.TEXTURE_2D, imgTex);
                gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, imgEl);
                texReady = true;
            } catch(e) { console.error('[CRT] tex:', e); }
        }


    function requestSummary() {
        var lastW = 0, lastH = 0;
        if (!isLoggedIn()) return;
        function resize() {
        if (summaryRequested) return;
            var w = screen.offsetWidth, h = screen.offsetHeight;
            if (w === lastW && h === lastH) return;
            lastW = w; lastH = h;
            canvas.width = w; canvas.height = h;
            gl.viewport(0, 0, w, h);
        }


         summaryRequested = true;
         var raf;
        var visualTime = 0;
        var lastVisualNow = 0;


         withApi(function (api) {
         function render(now) {
             api.get({
             var delta;
                action: 'progress_summary',
             raf = requestAnimationFrame(render);
                format: 'json',
                formatversion: 2
            }).then(function (data) {
                var payload = data && data.progress_summary;
                if (payload && payload.available && payload.summary) {
                    clearSummaryRetry();
                    updatePanel(payload.summary, { animateGain: false });
                } else {
                    scheduleSummaryRetry(2200);
                }
             }).catch(function () {
                scheduleSummaryRetry(2200);
            }).always(function () {
                summaryRequested = false;
            });
        }, function () {
            summaryRequested = false;
            scheduleSummaryRetry(2200);
        });
    }


    function queueNotifications(items) {
            if (!lastVisualNow) lastVisualNow = now;
        if (!items || !items.length) return;
            delta = Math.max(0, Math.min(100, now - lastVisualNow));
            lastVisualNow = now;


        items.forEach(function (item) {
            if (document.hidden || isClbiCompositorBusy()) return;
             if (!item) return;
             if (!texReady) { uploadImg(); return; }
            notificationQueue.push(item);
        });


        showNextNotification();
            visualTime += delta;
    }
            resize();
 
            var t = visualTime / 1000;
    function notificationText(item) {
            gl.uniform1i(uTex, 0);
        if (item.type === 'xp') {
            gl.uniform1i(uNoise, 1);
             return '+' + (item.amount || 0) + ' XP · ' + (item.label || '문서 열람');
            gl.uniform2f(uRes, canvas.width, canvas.height);
            gl.uniform2f(uImgSize, imgEl.naturalWidth, imgEl.naturalHeight);
            gl.uniform1f(uTime, t);
             gl.uniform2f(uNoiseSc, canvas.width / 512.0, canvas.height / 512.0);
            gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
         }
         }


         if (item.type === 'achievement') {
         if (imgEl.complete && imgEl.naturalWidth) { uploadImg(); }
            var xp = item.amount ? ' · +' + item.amount + ' XP' : '';
        else { imgEl.addEventListener('load', uploadImg); }
            return '업적 달성 · ' + (item.label || '새 업적') + xp;
        }


         if (item.type === 'level') {
         render();
            return item.label || '레벨 상승';
        screen._crtCleanup = function () { cancelAnimationFrame(raf); };
        }
    }


         return item.label || '보상 획득';
    function initAllCRTScreens(root) {
         var scope = root && root.querySelectorAll ? root : document;
        scope.querySelectorAll('.crt-page-monitor-screen').forEach(function (screen) {
            if (screen.getAttribute('data-crt-webgl') === '1') return;
            screen.setAttribute('data-crt-webgl', '1');
            var frame = screen.closest('.crt-page-monitor-frame');
            if (!frame) return;
            var imgEl = frame.querySelector('.crt-page-monitor-slice-img, .crt-page-monitor-image-base img');
            if (imgEl && imgEl.complete && imgEl.naturalWidth) {
                initCRTCanvas(screen, imgEl);
            } else if (imgEl) {
                imgEl.addEventListener('load', function () { initCRTCanvas(screen, imgEl); });
            } else {
                var obs = new MutationObserver(function () {
                    var img = frame.querySelector('.crt-page-monitor-slice-img');
                    if (!img) return;
                    obs.disconnect();
                    if (img.complete && img.naturalWidth) {
                        initCRTCanvas(screen, img);
                    } else {
                        img.addEventListener('load', function () { initCRTCanvas(screen, img); });
                    }
                });
                obs.observe(frame, { childList: true, subtree: true });
            }
        });
     }
     }


     function showNextNotification() {
     $(function () { initAllCRTScreens(document); });
        if (notificationActive) return;
        if (!notificationQueue.length) return;


        notificationActive = true;
    if (typeof mw !== 'undefined' && mw.hook) {
        var item = notificationQueue.shift();
         mw.hook('wikipage.content').add(function ($c) {
         var $root = $('#progress-toast-root');
             document.querySelectorAll('.crt-page-monitor-screen').forEach(function (s) {
 
                if (s._crtCleanup) s._crtCleanup();
        if (!$root.length) {
                s.removeAttribute('data-crt-webgl');
             $('body').append('<div id="progress-toast-root"></div>');
            });
            $root = $('#progress-toast-root');
             initAllCRTScreens($c && $c[0] ? $c[0] : document);
        }
 
        var $toast = $('<div class="progress-toast"></div>');
        $toast.text(notificationText(item));
        $root.append($toast);
 
        requestAnimationFrame(function () {
             $toast.addClass('is-visible');
         });
         });
        setTimeout(function () {
            $toast.removeClass('is-visible');
            setTimeout(function () {
                $toast.remove();
                notificationActive = false;
                showNextNotification();
            }, 220);
        }, 2600);
     }
     }
})();


    function applyPendingSummaryIfPossible() {
/* =========================================
        if (!pendingSummary) return;
Progress System UI
        updatePanel(pendingSummary, pendingOptions || { animateGain: false });
MediaWiki:Common.js controlled frontend
     }
========================================= */
(function (mw, $) {
     'use strict';


     function handlePageView() {
     if (window.ProgressSystemWebUiInitialized) return;
        ensurePanel();
    window.ProgressSystemWebUiInitialized = true;
        applyPendingSummaryIfPossible();


        if (!isRewardableClientSide()) {
    var api = null;
            requestSummary();
            return;
        }


        var pageId = getPageId();
    function withApi(done, fail) {
         if (handledPageIds.has(pageId)) {
         if (api) {
             requestSummary();
             done(api);
             return;
             return;
         }
         }


         if (inFlightPageIds.has(pageId)) {
         if (!mw.loader || typeof mw.loader.using !== 'function') {
             requestSummary();
             if (typeof fail === 'function') fail();
             return;
             return;
         }
         }


         inFlightPageIds.add(pageId);
         mw.loader.using(['mediawiki.api']).then(function () {
            api = new mw.Api();
            done(api);
        }, function () {
            if (typeof fail === 'function') fail();
        });
    }


        withApi(function (api) {
    var inFlightPageIds = new Set();
            api.postWithToken('csrf', {
    var handledPageIds = new Set();
                action: 'progress_view',
    var notificationQueue = [];
                format: 'json',
    var notificationActive = false;
                formatversion: 2,
    var summaryRequested = false;
                errorformat: 'plaintext',
    var currentSummary = null;
                pageid: pageId
    var pendingSummary = null;
            }).then(function (data) {
    var pendingOptions = null;
                var payload = data && data.progress_view;
    var visibilityBound = false;
                if (!payload) return;
    var barTimerA = null;
    var barTimerB = null;
    var barTimerC = null;
    var summaryRetryTimer = null;
    var summaryRetryAttempts = 0;


                handledPageIds.add(pageId);
    function isLoggedIn() {
        return !!mw.config.get('wgUserName');
    }


                var animate = hasXpNotification(payload.notifications);
    function getPageId() {
 
        var id = parseInt(mw.config.get('wgArticleId') || 0, 10);
                if (payload.summary) {
         return Number.isFinite(id) ? id : 0;
                    updatePanel(payload.summary, { animateGain: animate });
                }
 
                if (payload.notifications && payload.notifications.length) {
                    queueNotifications(payload.notifications);
                }
            }).catch(function () {
                requestSummary();
            }).always(function () {
                inFlightPageIds.delete(pageId);
            });
         }, function () {
            inFlightPageIds.delete(pageId);
            requestSummary();
        });
     }
     }


     function bindVisibilitySync() {
     function isRewardableClientSide() {
         if (visibilityBound) return;
         if (!isLoggedIn()) return false;
         visibilityBound = true;
         if (parseInt(mw.config.get('wgNamespaceNumber'), 10) !== 0) return false;
 
        if (mw.config.get('wgIsMainPage')) return false;
        document.addEventListener('visibilitychange', function () {
        if (getPageId() <= 0) return false;
            if (document.visibilityState === 'visible') {
         return true;
                requestSummary();
            }
         });
     }
     }


     function bootProgressSystem(reason) {
     function getPanelHtml() {
         ensurePanel();
         return '' +
        applyPendingSummaryIfPossible();
            '<div id="progress-panel" class="profile-progress-block is-syncing" aria-live="polite" data-progress-state="syncing">' +
 
                '<div class="progress-title-row" hidden></div>' +
        if (isRewardableClientSide()) {
                '<div class="progress-level-row">' +
            handlePageView();
                    '<span class="progress-level-label">SYNC</span>' +
        } else {
                    '<span class="progress-total-xp">— XP</span>' +
             requestSummary();
                '</div>' +
        }
                '<div class="progress-xp-bar" aria-hidden="true">' +
                    '<div class="progress-xp-gain"></div>' +
                    '<div class="progress-xp-fill"></div>' +
                '</div>' +
                '<div class="progress-sub-row">' +
                    '<span class="progress-xp-next">SYNCING</span>' +
                    '<span class="progress-daily-xp">TODAY —</span>' +
                '</div>' +
                '<div class="progress-discovery-row">DISCOVERED —</div>' +
             '</div>';
    }


        setTimeout(function () {
    function getDividerHtml() {
            ensurePanel();
         /* 프로필 패널 최신 규칙: 레벨 패널과 버튼 영역 사이에 별도 나눔선은 만들지 않는다. */
            applyPendingSummaryIfPossible();
         return '';
            requestSummary();
        }, 350);
 
         setTimeout(function () {
            ensurePanel();
            applyPendingSummaryIfPossible();
            requestSummary();
         }, 1500);
     }
     }


     function handleSpaPageView() {
     function setPanelSync($panel) {
         ensurePanel();
         if (!$panel || !$panel.length) return;
        applyPendingSummaryIfPossible();


         requestAnimationFrame(function () {
         $panel.addClass('is-syncing').removeClass('is-max-level').attr('data-progress-state', 'syncing');
            setTimeout(function () {
        $panel.find('.progress-title-row').text('').prop('hidden', true);
                handlePageView();
        $panel.find('.progress-level-label').text('SYNC');
            }, 80);
        $panel.find('.progress-total-xp').text('— XP');
         });
        $panel.find('.progress-xp-next').text('SYNCING');
        $panel.find('.progress-daily-xp').text('TODAY —');
        $panel.find('.progress-discovery-row').text('DISCOVERED —');
        $panel.find('.progress-xp-fill').css({ transition: 'none', width: '0%' });
         $panel.find('.progress-xp-gain').css({ transition: 'none', width: '0%', opacity: 0 });
     }
     }


     function applySummary(summary, options) {
     function placePanel($panel) {
         updatePanel(summary, options || { animateGain: false });
         var $right = $('#clbi-right-sidebar');
    }
        if (!$right.length) return false;
 
        var $userBox = $right.children('.clbi-right-box').first();
        if (!$userBox.length) return false;


    window.ProgressSystemWebUi = {
        var $buttonArea = $userBox.children('.clbi-right-content').first();
         boot: bootProgressSystem,
         var $oldFallback = $panel.closest('.progress-panel-fallback');
        requestSummary: requestSummary,
        applySummary: applySummary,
        handlePageView: handlePageView,
        handleSpaPageView: handleSpaPageView,
        ensurePanel: ensurePanel
    };


    $(function () {
        if ($buttonArea.length) {
        bindVisibilitySync();
            var $divider = $('#profile-progress-divider');
        bootProgressSystem('documentReady');
    });


    mw.hook('wikipage.content').add(function () {
            $panel.insertBefore($buttonArea);
        ensurePanel();
        applyPendingSummaryIfPossible();
        setTimeout(function () {
            ensurePanel();
            applyPendingSummaryIfPossible();
            requestSummary();
        }, 120);
    });
})(mediaWiki, jQuery);


            if (!$divider.length) {
                $divider = $(getDividerHtml());
            }


/* CLBI Nations / Historical Events year tabs
            $divider.insertAfter($panel);
* Mirrors the country information panel model:
        } else {
* active tab uses .is-active/aria-selected and inactive pages use hidden.
            $('#profile-progress-divider').remove();
*/
            $userBox.append($panel);
(function (mw, $) {
        }
    'use strict';


    function activateClbiNationsHistoryYear(panel, targetYear) {
        if ($oldFallback.length && !$oldFallback.find('#progress-panel').length) {
        var tabs;
            $oldFallback.remove();
         var pages;
         }


         if (!panel || !targetYear) return false;
         return true;
    }


        tabs = Array.prototype.slice.call(panel.querySelectorAll('.clbi-nations-history-year-button[data-year]'));
    function ensurePanel() {
         pages = Array.prototype.slice.call(panel.querySelectorAll('.clbi-nations-history-page[data-year-panel]'));
         if (!isLoggedIn()) return $();


         if (!tabs.length || !pages.length) return false;
        var $right = $('#clbi-right-sidebar');
         if (!$right.length) return $();


         tabs.forEach(function (tab) {
         var $panel = $('#progress-panel');
            var active = tab.getAttribute('data-year') === targetYear;
            tab.classList.toggle('is-active', active);
            tab.setAttribute('aria-selected', active ? 'true' : 'false');
            tab.setAttribute('tabindex', active ? '0' : '-1');
        });


         pages.forEach(function (page) {
         if (!$panel.length) {
             var active = page.getAttribute('data-year-panel') === targetYear;
            $panel = $(getPanelHtml());
             page.classList.toggle('is-active', active);
            if (!placePanel($panel)) return $();
            setPanelSync($panel);
        } else {
             $panel.addClass('profile-progress-block');
             placePanel($panel);


             if (active) {
             if (!currentSummary && $panel.attr('data-progress-state') !== 'syncing') {
                page.removeAttribute('hidden');
                 setPanelSync($panel);
            } else {
                 page.setAttribute('hidden', 'hidden');
             }
             }
         });
         }


         return true;
         return $('#progress-panel');
     }
     }


     function moveClbiNationsHistoryYear(panel, direction) {
     function clampPercent(value) {
         var tabs;
         return Math.max(0, Math.min(100, value || 0));
        var activeIndex;
    }
        var nextIndex;
        var target;


         if (!panel) return false;
    function hasXpNotification(items) {
         if (!items || !items.length) return false;
        return items.some(function (item) {
            return item && item.type === 'xp' && parseInt(item.amount || 0, 10) > 0;
        });
    }


        tabs = Array.prototype.slice.call(panel.querySelectorAll('.clbi-nations-history-year-button[data-year]'));
    function clearBarTimers() {
         if (!tabs.length) return false;
         [barTimerA, barTimerB, barTimerC].forEach(function (timer) {
 
             if (timer) clearTimeout(timer);
        activeIndex = tabs.findIndex(function (tab) {
             return tab.classList.contains('is-active') || tab.getAttribute('aria-selected') === 'true';
         });
         });
        barTimerA = null;
        barTimerB = null;
        barTimerC = null;
    }


         if (activeIndex < 0) activeIndex = 0;
    function setBarInstant($fill, $gain, percent) {
 
         clearBarTimers();
         nextIndex = (activeIndex + direction + tabs.length) % tabs.length;
        percent = clampPercent(percent);
         target = tabs[nextIndex].getAttribute('data-year');
         $fill.css({ transition: 'none', width: percent + '%' });
 
         $gain.css({ transition: 'none', left: '0%', width: '0%', opacity: 0 });
         if (activateClbiNationsHistoryYear(panel, target)) {
         if ($fill[0]) $fill[0].offsetHeight;
            tabs[nextIndex].focus();
        $fill.css({ transition: '' });
            return true;
         $gain.css({ transition: '' });
         }
 
        return false;
     }
     }


     function initClbiNationsHistoryYearTabs(root) {
     function animateGain($fill, $gain, fromPercent, toPercent, levelChanged) {
         var scope = root && root.querySelectorAll ? root : document;
         clearBarTimers();
        var panels = scope.querySelectorAll('.clbi-nations-history-panel');


         Array.prototype.forEach.call(panels, function (panel) {
         fromPercent = clampPercent(fromPercent);
            if (panel.getAttribute('data-clbi-history-tabs-ready') === '1') return;
        toPercent = clampPercent(toPercent);


            panel.setAttribute('data-clbi-history-tabs-ready', '1');
        $fill.css({ transition: 'none', width: fromPercent + '%' });


            panel.addEventListener('click', function (event) {
        if (levelChanged) {
                var tab = event.target.closest ? event.target.closest('.clbi-nations-history-year-button[data-year]') : null;
            var firstDelta = Math.max(0, 100 - fromPercent);


                if (!tab || !panel.contains(tab)) return;
            $gain.css({
 
                transition: 'none',
                 if (activateClbiNationsHistoryYear(panel, tab.getAttribute('data-year'))) {
                 opacity: firstDelta > 0 ? 1 : 0,
                    event.preventDefault();
                left: fromPercent + '%',
                 }
                 width: firstDelta + '%'
             });
             });


             panel.addEventListener('keydown', function (event) {
             if ($fill[0]) $fill[0].offsetHeight;
                var tab = event.target.closest ? event.target.closest('.clbi-nations-history-year-button[data-year]') : null;
                var handled = false;


                 if (!tab || !panel.contains(tab)) return;
            barTimerA = setTimeout(function () {
                 $fill.css({
                    transition: 'width 540ms cubic-bezier(0.22, 0.7, 0.18, 1)',
                    width: '100%'
                });
            }, 260);


                if (event.key === 'ArrowLeft') handled = moveClbiNationsHistoryYear(panel, -1);
            barTimerB = setTimeout(function () {
                 else if (event.key === 'ArrowRight') handled = moveClbiNationsHistoryYear(panel, 1);
                 $fill.css({ transition: 'none', width: '0%' });
                else if (event.key === 'Home') handled = activateClbiNationsHistoryYear(panel, (panel.querySelector('.clbi-nations-history-year-button[data-year]') || {}).getAttribute && panel.querySelector('.clbi-nations-history-year-button[data-year]').getAttribute('data-year'));
                 $gain.css({ transition: 'none', opacity: toPercent > 0 ? 1 : 0, left: '0%', width: toPercent + '%' });
                 else if (event.key === 'End') {
                    var tabs = panel.querySelectorAll('.clbi-nations-history-year-button[data-year]');
                    var last = tabs[tabs.length - 1];
                    handled = last ? activateClbiNationsHistoryYear(panel, last.getAttribute('data-year')) : false;
                    if (handled) last.focus();
                }


                 if (handled) {
                 if ($fill[0]) $fill[0].offsetHeight;
                    event.preventDefault();
                    event.stopPropagation();
                }
            });
        });
    }


    window.initClbiNationsHistoryYearTabs = initClbiNationsHistoryYearTabs;
                $fill.css({
                    transition: 'width 460ms cubic-bezier(0.22, 0.7, 0.18, 1)',
                    width: toPercent + '%'
                });
            }, 860);


    $(function () {
            barTimerC = setTimeout(function () {
        initClbiNationsHistoryYearTabs(document);
                $gain.css({ transition: 'opacity 180ms ease', opacity: 0 });
    });
            }, 1380);


    if (mw && mw.hook) {
             return;
        mw.hook('wikipage.content').add(function ($content) {
         }
             initClbiNationsHistoryYearTabs($content && $content[0] ? $content[0] : document);
         });
    }
})(mediaWiki, jQuery);


        var delta = Math.max(0, toPercent - fromPercent);


/* =========================================
        if (delta <= 0.15) {
  Decoration runtime renderer
            setBarInstant($fill, $gain, toPercent);
  ========================================= */
            return;
(function (mw) {
        }
    'use strict';


    var REGISTRY_TITLE = 'MediaWiki:Decorations.json';
        $gain.css({
    var RENDERED_ATTR = 'data-wiki-decoration-rendered';
            transition: 'none',
    var HOST_ATTR = 'data-wiki-decoration-host';
            opacity: 1,
    var runtimeToken = 0;
            left: fromPercent + '%',
    var lastRegistry = null;
            width: delta + '%'
    var lastRenderedPageKey = '';
        });
    var scheduledRender = 0;
    var nationsPlacementObserver = null;
    var observedNationsStack = null;
    var pixelAssetCache = {};
    var pixelCanvasCache = {};


    function normalizePageName(value) {
         if ($fill[0]) $fill[0].offsetHeight;
         return String(value || '')
            .split('?')[0]
            .replace(/^\/index\.php\//, '')
            .replace(/_/g, ' ')
            .trim();
    }


    function currentPageKey() {
        barTimerA = setTimeout(function () {
        var raw = mw && mw.config ? String(mw.config.get('wgPageName') || '') : '';
            $fill.css({
         return normalizePageName(raw) || raw || '대문';
                transition: 'width 560ms cubic-bezier(0.22, 0.7, 0.18, 1)',
    }
                width: toPercent + '%'
            });
         }, 260);


 
        barTimerB = setTimeout(function () {
    function cssAttrEscape(value) {
            $gain.css({ transition: 'opacity 180ms ease', opacity: 0 });
        return String(value || '').replace(/\\/g, '\\\\').replace(/"/g, '\\"');
        }, 940);
     }
     }


     function getActiveNationsEra() {
     function updatePanel(summary, options) {
         var content = document.querySelector('.clbi-nations-era-content.is-active[data-era-content]:not([hidden])');
         if (!summary) return;
        var title;
        var globe;


         if (content) return content.getAttribute('data-era-content') || '';
         options = options || {};


         title = document.querySelector('.clbi-nations-era-title-plate.is-active[data-era]');
         var $panel = ensurePanel();
         if (title) return title.getAttribute('data-era') || '';
         if (!$panel.length) {
 
            pendingSummary = $.extend({}, summary);
        globe = document.querySelector('.clbi-nations-globe-window[data-nations-globe]');
            pendingOptions = $.extend({}, options);
        if (globe) {
             return;
             return globe.getAttribute('data-current-era') || globe.getAttribute('data-nations-current-era') || globe.getAttribute('data-era-year') || '';
         }
         }


         return '';
         var level = summary.level || 1;
    }
        var totalXp = summary.totalXp || 0;
 
        var xpIntoLevel = summary.xpIntoLevel || 0;
    function getActiveNationsEraPanel() {
        var xpForNext = summary.xpForNextLevel || 1;
         var era = getActiveNationsEra();
         var percent = clampPercent(summary.progressPercent);
         var selector;
         var isMaxLevel = !!summary.isMaxLevel;
         if (!era) return document.querySelector('.clbi-nations-era-content.is-active[data-era-content]:not([hidden])');
         var dailyXp = summary.dailyXp || 0;
         selector = '.clbi-nations-era-content[data-era-content="' + cssAttrEscape(era) + '"]';
         var discoveries = summary.discoveryCount || 0;
         return document.querySelector(selector) || document.querySelector('.clbi-nations-era-content.is-active[data-era-content]:not([hidden])');
         var title = summary.equippedTitle || summary.title || '';
    }


    function getActiveNationsContinent() {
        $panel.removeClass('is-syncing').toggleClass('is-max-level', isMaxLevel).attr('data-progress-state', 'ready');
         var eraPanel = getActiveNationsEraPanel();
         $panel.find('.progress-level-label').text((isMaxLevel ? 'MAX ' : 'LVL ') + level);
         var root = eraPanel || document;
         $panel.find('.progress-total-xp').text(totalXp + ' XP');
         var tab = root.querySelector('.clbi-nations-tabpanel-tab.is-active[data-continent], .clbi-nations-tabpanel-tab[aria-selected="true"][data-continent]');
         $panel.find('.progress-xp-next').text(isMaxLevel ? 'MAX LEVEL' : (xpIntoLevel + ' / ' + xpForNext + ' TO NEXT'));
         var panel;
        $panel.find('.progress-daily-xp').text('TODAY ' + dailyXp + ' XP');
         $panel.find('.progress-discovery-row').text('DISCOVERED ' + discoveries);


         if (tab) return tab.getAttribute('data-continent') || '';
        var $title = $panel.find('.progress-title-row');
         if (title) {
            $title.text(title).prop('hidden', false);
        } else {
            $title.text('').prop('hidden', true);
        }


         panel = root.querySelector('.clbi-nations-tabpanel-continent.is-active[data-continent-panel]');
         var $fill = $panel.find('.progress-xp-fill');
         if (panel) return panel.getAttribute('data-continent-panel') || '';
         var $gain = $panel.find('.progress-xp-gain');
        var animate = !!options.animateGain && currentSummary && totalXp > (currentSummary.totalXp || 0);


         return '';
         if (animate) {
    }
            animateGain(
                $fill,
                $gain,
                clampPercent(currentSummary.progressPercent),
                percent,
                level !== (currentSummary.level || 1)
            );
        } else {
            setBarInstant($fill, $gain, percent);
        }


    function getDecorationNationsBodySelector(era) {
        currentSummary = $.extend({}, summary);
         if (era) {
        pendingSummary = null;
             return '.clbi-nations-era-content[data-era-content="' + cssAttrEscape(era) + '"] .clbi-nations-tabpanel-body';
        pendingOptions = null;
         if (summaryRetryTimer) {
             clearTimeout(summaryRetryTimer);
            summaryRetryTimer = null;
         }
         }
         return '.clbi-nations-era-content.is-active[data-era-content]:not([hidden]) .clbi-nations-tabpanel-body, .clbi-nations-tabpanel-body';
         summaryRetryAttempts = 0;
     }
     }


     /*
     function clearSummaryRetry() {
    Decoration semantic placement resolver
        if (summaryRetryTimer) clearTimeout(summaryRetryTimer);
    -----------------------------------------
        summaryRetryTimer = null;
    장식 저장 데이터의 placement 값은 "사용자가 고른 의미상 위치"를 나타낸다.
        summaryRetryAttempts = 0;
     resolver는 그 의미값을 실제 DOM 부착 위치와 표시 조건으로 번역한다.
     }


     예: 국가 및 조합에서 사용자가 1950년 / 아메리카를 지정하면 의미상 scope는
     function scheduleSummaryRetry(delay) {
    그 조합이지만, 이미지를 붙일 기준면은 대륙 패널 자체가 아니라
        if (!isLoggedIn()) return;
    .clbi-nations-tabpanel-body이다. 따라서 placement=nations-continent-body는
        if (summaryRetryTimer) return;
    .clbi-nations-tabpanel-body에 이미지를 붙이고, 현재 활성 연도와 대륙이 저장값과
        if (summaryRetryAttempts >= 12) return;
    일치할 때만 렌더링한다.


    유지보수 규칙:
         summaryRetryAttempts += 1;
    - 새 조합형 문서가 생기면 entry.target을 매번 특수하게 저장하지 말고 placement를 추가한다.
         summaryRetryTimer = setTimeout(function () {
    - DevTools.js 에디터 미리보기와 Common.js 런타임 렌더러의 resolver는 같은 의미를 가져야 한다.
            summaryRetryTimer = null;
    - target은 물리적 기준면, era/continent 같은 필드는 표시 조건으로 다룬다.
            requestSummary();
    */
         }, delay || 1800);
    function shouldUseNationsBodyPlacement(entry) {
         var placement = String(entry && entry.placement || '').trim();
         var target = String(entry && entry.target || '').trim();
        var era = String(entry && entry.era || '').trim();
        var continent = String(entry && entry.continent || '').trim();
 
        if (!document.querySelector('.clbi-nations-panel-stack')) return false;
         if (placement === 'nations-continent-body') return true;
        if (era || continent) return true;
        if (target.indexOf('clbi-nations-tabpanel-continent') !== -1) return true;
        return false;
     }
     }


     function resolveDecorationPlacement(entry) {
     function requestSummary() {
         var placement = String(entry && entry.placement || '').trim();
         if (!isLoggedIn()) return;
        var selector = String(entry && entry.target || '').trim() || '.liberty-content-main';
         if (summaryRequested) return;
         var era = String(entry && entry.era || '').trim();
        var continent = String(entry && entry.continent || '').trim();
        var target;


         if (!placement && shouldUseNationsBodyPlacement(entry)) {
         summaryRequested = true;
            placement = 'nations-continent-body';
        }


         if (placement === 'boot-gate' || placement === 'loading-screen') {
         withApi(function (api) {
             selector = '#boot-gate-screen .boot-gate-decoration-layer, #boot-gate-screen';
             api.get({
            target = document.querySelector(selector);
                 action: 'progress_summary',
            return {
                 format: 'json',
                 placement: placement,
                 formatversion: 2
                 target: target,
            }).then(function (data) {
                 targetSelector: selector,
                var payload = data && data.progress_summary;
                visible: !!document.getElementById('boot-gate-screen')
                if (payload && payload.available && payload.summary) {
            };
                    clearSummaryRetry();
        }
                    updatePanel(payload.summary, { animateGain: false });
 
                } else {
        if (placement === 'nations-continent-body') {
                    scheduleSummaryRetry(2200);
            selector = getDecorationNationsBodySelector(era);
                 }
            target = document.querySelector(selector) || document.querySelector('.clbi-nations-tabpanel-body') || document.querySelector(String(entry && entry.target || '').trim());
            }).catch(function () {
            return {
                 scheduleSummaryRetry(2200);
                placement: placement,
            }).always(function () {
                 target: target,
                summaryRequested = false;
                targetSelector: selector,
             });
                 visible: (!era || era === getActiveNationsEra()) && (!continent || continent === getActiveNationsContinent())
         }, function () {
             };
             summaryRequested = false;
         }
             scheduleSummaryRetry(2200);
 
         });
        return {
             placement: placement,
             target: document.querySelector(selector),
            targetSelector: selector,
            visible: true
         };
     }
     }


     function normalizeNumber(value, fallback) {
     function queueNotifications(items) {
         var n = parseFloat(value);
         if (!items || !items.length) return;
        return Number.isFinite(n) ? n : fallback;
    }


    function normalizeBool(value, fallback) {
        items.forEach(function (item) {
        if (value === true || value === 'true' || value === '1' || value === 1) return true;
            if (!item) return;
        if (value === false || value === 'false' || value === '0' || value === 0) return false;
            notificationQueue.push(item);
         return fallback;
         });
    }


    function normalizeSrc(src) {
         showNextNotification();
        src = String(src || '').trim();
        if (!src) return '';
        if (/^(?:https?:)?\/\//i.test(src) || src.charAt(0) === '/' || src.indexOf('data:') === 0 || src.indexOf('blob:') === 0) return src;
         return '/index.php/Special:Redirect/file/' + encodeURIComponent(src);
     }
     }


    function notificationText(item) {
        if (item.type === 'xp') {
            return '+' + (item.amount || 0) + ' XP · ' + (item.label || '문서 열람');
        }


    function normalizeAssetType(entry) {
        if (item.type === 'achievement') {
        var type = String(entry && entry.assetType || '').trim().toLowerCase();
            var xp = item.amount ? ' · +' + item.amount + ' XP' : '';
        var ref = String(entry && (entry.asset || entry.src) || '').trim();
            return '업적 달성 · ' + (item.label || '새 업적') + xp;
        }


         if (type === 'clbi-pixel-json' || type === 'pixel-rle' || type === 'pixel-json') return 'pixel-json';
         if (item.type === 'level') {
        if (!type && /\.json(?:[?#].*)?$/i.test(ref)) return 'pixel-json';
            return item.label || '레벨 상승';
        return type || 'image';
        }
    }


    function isPixelJsonDecoration(entry) {
         return item.label || '보상 획득';
         return normalizeAssetType(entry) === 'pixel-json';
     }
     }


     function getPixelJsonRef(entry) {
     function showNextNotification() {
         return String(entry && (entry.asset || entry.src) || '').trim();
         if (notificationActive) return;
    }
        if (!notificationQueue.length) return;


    function normalizePixelJsonUrl(ref) {
         notificationActive = true;
         ref = String(ref || '').trim();
         var item = notificationQueue.shift();
        if (!ref) return '';
         var $root = $('#progress-toast-root');
         if (/^(?:https?:)?\/\//i.test(ref) || ref.charAt(0) === '/' || ref.indexOf('data:') === 0 || ref.indexOf('blob:') === 0) return ref;
        if (/^(?:file|파일):/i.test(ref)) return '/index.php/Special:Redirect/file/' + encodeURIComponent(ref.replace(/^(?:file|파일):/i, ''));
         if (mw && mw.util && typeof mw.util.getUrl === 'function') {
            if (ref.indexOf(':') !== -1) {
                return mw.util.getUrl(ref, { action: 'raw', ctype: 'application/json' });
            }
            return mw.util.getUrl('MediaWiki:' + ref, { action: 'raw', ctype: 'application/json' });
        }
        return ref;
    }


    function parsePixelColor(value) {
         if (!$root.length) {
        var text;
             $('body').append('<div id="progress-toast-root"></div>');
        var m;
             $root = $('#progress-toast-root');
         if (Array.isArray(value)) {
             return [
                Math.max(0, Math.min(255, Number(value[0]) || 0)),
                Math.max(0, Math.min(255, Number(value[1]) || 0)),
                Math.max(0, Math.min(255, Number(value[2]) || 0)),
                value.length > 3 ? Math.max(0, Math.min(255, Number(value[3]) || 0)) : 255
            ];
        }
        text = String(value || '').trim();
        m = text.match(/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);
        if (!m) return [0, 0, 0, 0];
        text = m[1];
        if (text.length === 3 || text.length === 4) {
             return [
                parseInt(text.charAt(0) + text.charAt(0), 16),
                parseInt(text.charAt(1) + text.charAt(1), 16),
                parseInt(text.charAt(2) + text.charAt(2), 16),
                text.length === 4 ? parseInt(text.charAt(3) + text.charAt(3), 16) : 255
            ];
         }
         }
        return [
            parseInt(text.slice(0, 2), 16),
            parseInt(text.slice(2, 4), 16),
            parseInt(text.slice(4, 6), 16),
            text.length === 8 ? parseInt(text.slice(6, 8), 16) : 255
        ];
    }


        var $toast = $('<div class="progress-toast"></div>');
        $toast.text(notificationText(item));
        $root.append($toast);


    function decodePixelRle36(value) {
        requestAnimationFrame(function () {
        var text = String(value || '').trim();
            $toast.addClass('is-visible');
         var parts;
         });
        var runs = [];
        var i;
        var x;
        var y;
        var len;
        var colorIndex;


         if (!text) return runs;
         setTimeout(function () {
        parts = text.split(',');
            $toast.removeClass('is-visible');
        for (i = 0; i + 3 < parts.length; i += 4) {
            setTimeout(function () {
            x = parseInt(parts[i], 36);
                $toast.remove();
            y = parseInt(parts[i + 1], 36);
                notificationActive = false;
             len = parseInt(parts[i + 2], 36);
                showNextNotification();
            colorIndex = parseInt(parts[i + 3], 36);
             }, 220);
            if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(len) || !Number.isFinite(colorIndex)) continue;
        }, 2600);
            runs.push([x, y, len, colorIndex]);
    }
        }
 
        return runs;
    function applyPendingSummaryIfPossible() {
        if (!pendingSummary) return;
        updatePanel(pendingSummary, pendingOptions || { animateGain: false });
     }
     }


     function normalizePixelAsset(doc) {
     function handlePageView() {
         var encoding = String(doc && (doc.encoding || doc.e) || '').trim().toLowerCase();
         ensurePanel();
        var width = Math.round(Number(doc && (doc.width || doc.w)) || 0);
         applyPendingSummaryIfPossible();
        var height = Math.round(Number(doc && (doc.height || doc.h)) || 0);
        var paletteSource = Array.isArray(doc && doc.palette) ? doc.palette : (Array.isArray(doc && doc.p) ? doc.p : []);
         var palette = paletteSource.map(parsePixelColor);
        var runs;


        /*
         if (!isRewardableClientSide()) {
        CLBI Pixel Forge v0.2.3 compact format:
             requestSummary();
        - MediaWiki 단일 문서 크기 제한을 피하기 위해 사람이 읽기 쉬운 [[x,y,len,c], ...] 배열 대신
             return;
          base36 토큰 문자열을 쓴다.
        - 형식은 x,y,len,colorIndex를 4개 토큰 단위로 반복한 rle36이다.
        - 복원 후 좌표계는 기존 runs 배열과 완전히 같으며, 최종 CSS px에 1:1로 찍는다.
        */
         if ((encoding === 'rle36' || encoding === 'clbi-rle36') && typeof (doc && doc.r) === 'string') {
             runs = decodePixelRle36(doc.r);
        } else {
             runs = Array.isArray(doc && doc.runs) ? doc.runs : [];
         }
         }


         if (!width || !height || width < 1 || height < 1) throw new Error('invalid pixel decoration size');
         var pageId = getPageId();
         if (width > 8192 || height > 8192) throw new Error('pixel decoration too large');
         if (handledPageIds.has(pageId)) {
        return {
             requestSummary();
             type: String(doc && (doc.type || doc.t) || 'clbi-pixel-decoration'),
             return;
             version: Number(doc && (doc.version || doc.v)) || 1,
         }
            encoding: encoding || 'runs',
            width: width,
            height: height,
            palette: palette,
            runs: runs
         };
    }


    function fetchPixelAsset(ref) {
        if (inFlightPageIds.has(pageId)) {
        var url = normalizePixelJsonUrl(ref);
            requestSummary();
         var cached;
            return;
         if (!url) return Promise.reject(new Error('pixel json ref is empty'));
         }
        cached = pixelAssetCache[url];
 
         if (cached) return cached.promise;
         inFlightPageIds.add(pageId);
        cached = {
 
             promise: fetch(url, { credentials: 'same-origin', cache: 'force-cache' })
         withApi(function (api) {
                .then(function (response) {
             api.postWithToken('csrf', {
                    if (!response.ok) throw new Error('HTTP ' + response.status);
                action: 'progress_view',
                    return response.json();
                format: 'json',
                })
                formatversion: 2,
                 .then(normalizePixelAsset)
                errorformat: 'plaintext',
        };
                pageid: pageId
        pixelAssetCache[url] = cached;
            }).then(function (data) {
        return cached.promise;
                var payload = data && data.progress_view;
    }
                if (!payload) return;
 
                 handledPageIds.add(pageId);


    function drawPixelAssetToCanvas(canvas, asset) {
                var animate = hasXpNotification(payload.notifications);
        var ctx;
        var image;
        var data;
        var i;
        var run;
        var x;
        var y;
        var len;
        var color;
        var colorIndex;
        var p;
        var k;


        canvas.width = asset.width;
                if (payload.summary) {
        canvas.height = asset.height;
                    updatePanel(payload.summary, { animateGain: animate });
        ctx = canvas.getContext('2d');
                }
        ctx.imageSmoothingEnabled = false;
        image = ctx.createImageData(asset.width, asset.height);
        data = image.data;


        for (i = 0; i < asset.runs.length; i += 1) {
                if (payload.notifications && payload.notifications.length) {
            run = asset.runs[i];
                    queueNotifications(payload.notifications);
            if (!Array.isArray(run) || run.length < 4) continue;
                }
             x = Math.round(Number(run[0]) || 0);
             }).catch(function () {
            y = Math.round(Number(run[1]) || 0);
                requestSummary();
             len = Math.round(Number(run[2]) || 0);
             }).always(function () {
            colorIndex = Math.round(Number(run[3]) || 0);
                inFlightPageIds.delete(pageId);
             color = asset.palette[colorIndex];
             });
            if (!color || len <= 0 || y < 0 || y >= asset.height || x >= asset.width) continue;
        }, function () {
            if (x < 0) {
             inFlightPageIds.delete(pageId);
                len += x;
             requestSummary();
                x = 0;
        });
            }
    }
             len = Math.min(len, asset.width - x);
             for (k = 0; k < len; k += 1) {
                p = ((y * asset.width) + x + k) * 4;
                data[p] = color[0];
                data[p + 1] = color[1];
                data[p + 2] = color[2];
                data[p + 3] = color[3];
            }
        }


         ctx.putImageData(image, 0, 0);
    function bindVisibilitySync() {
    }
         if (visibilityBound) return;
        visibilityBound = true;


    function preparePixelCanvas(ref) {
         document.addEventListener('visibilitychange', function () {
         var url = normalizePixelJsonUrl(ref);
            if (document.visibilityState === 'visible') {
        var cached;
                requestSummary();
        if (!url) return Promise.reject(new Error('pixel json ref is empty'));
             }
        cached = pixelCanvasCache[url];
        if (cached) return cached.promise;
        cached = {};
        cached.promise = fetchPixelAsset(ref).then(function (asset) {
            var canvas = document.createElement('canvas');
            drawPixelAssetToCanvas(canvas, asset);
             canvas.style.imageRendering = 'pixelated';
            canvas.setAttribute('data-decoration-asset-size', asset.width + 'x' + asset.height);
            cached.canvas = canvas;
            cached.width = asset.width;
            cached.height = asset.height;
            return canvas;
         });
         });
        pixelCanvasCache[url] = cached;
        return cached.promise;
     }
     }


     function getPreparedPixelCanvasSync(ref) {
     function bootProgressSystem(reason) {
         var url = normalizePixelJsonUrl(ref);
         ensurePanel();
         var cached = url ? pixelCanvasCache[url] : null;
         applyPendingSummaryIfPossible();
        return cached && cached.canvas ? cached.canvas : null;
    }


    function applyDecorationBaseStyle(node, entry) {
         if (isRewardableClientSide()) {
         node.style.left = normalizeNumber(entry.x, 0) + 'px';
            handlePageView();
        node.style.top = normalizeNumber(entry.y, 0) + 'px';
         } else {
        node.style.opacity = String(normalizeNumber(entry.opacity, 1));
            requestSummary();
        node.style.zIndex = String(Math.round(normalizeNumber(entry.zIndex, 0)));
         }
         node.style.pointerEvents = String(entry.pointerEvents || 'none');
        if (entry.blendMode) node.style.mixBlendMode = String(entry.blendMode);
        if (entry.filter) node.style.filter = String(entry.filter);
         if (entry.transform) node.style.transform = String(entry.transform);
    }


    function isDecorationNodeActiveForNationsState(node) {
        setTimeout(function () {
        var era = node ? String(node.getAttribute('data-decoration-era') || '').trim() : '';
            ensurePanel();
         var continent = node ? String(node.getAttribute('data-decoration-continent') || '').trim() : '';
            applyPendingSummaryIfPossible();
        if (era && era !== getActiveNationsEra()) return false;
            requestSummary();
        if (continent && continent !== getActiveNationsContinent()) return false;
         }, 350);
         return true;
 
        setTimeout(function () {
            ensurePanel();
            applyPendingSummaryIfPossible();
            requestSummary();
         }, 1500);
     }
     }


     function setDecorationNodeVisibility(node, visible) {
     function handleSpaPageView() {
         if (!node) return;
         ensurePanel();
         visible = visible !== false;
         applyPendingSummaryIfPossible();
        /* aria-hidden stays true because wiki decorations are purely visual. */
        if (node.hidden !== !visible) node.hidden = !visible;
        if (node.style.display !== (visible ? '' : 'none')) node.style.display = visible ? '' : 'none';
        node.setAttribute('data-decoration-visible', visible ? '1' : '0');
    }


    function updateDecorationVisibility(root) {
        requestAnimationFrame(function () {
        var scope = root && root.querySelectorAll ? root : document;
            setTimeout(function () {
        var count = 0;
                handlePageView();
        Array.prototype.forEach.call(scope.querySelectorAll('[' + RENDERED_ATTR + '="1"]'), function (node) {
             }, 80);
            setDecorationNodeVisibility(node, isDecorationNodeActiveForNationsState(node));
             count += 1;
         });
         });
        return count;
     }
     }


     function hasRenderedDecorations(root) {
     function applySummary(summary, options) {
         var scope = root && root.querySelector ? root : document;
         updatePanel(summary, options || { animateGain: false });
        return !!(scope && scope.querySelector && scope.querySelector('[' + RENDERED_ATTR + '="1"]'));
     }
     }


     function applyPixelJsonDecoration(entry, target, visible) {
     window.ProgressSystemWebUi = {
         var ref = getPixelJsonRef(entry);
        boot: bootProgressSystem,
         var template;
        requestSummary: requestSummary,
         var canvas;
        applySummary: applySummary,
         var ctx;
        handlePageView: handlePageView,
         if (!ref) return false;
        handleSpaPageView: handleSpaPageView,
        ensurePanel: ensurePanel
    };
 
    $(function () {
         bindVisibilitySync();
         bootProgressSystem('documentReady');
    });
 
    mw.hook('wikipage.content').add(function () {
        ensurePanel();
         applyPendingSummaryIfPossible();
         setTimeout(function () {
            ensurePanel();
            applyPendingSummaryIfPossible();
            requestSummary();
         }, 120);
    });
})(mediaWiki, jQuery);


        function makeCanvasFromTemplate(source) {
            var out = document.createElement('canvas');
            var outCtx;
            out.className = 'wiki-decoration wiki-decoration-pixel-json';
            out.setAttribute(RENDERED_ATTR, '1');
            out.setAttribute('aria-hidden', 'true');
            out.setAttribute('data-decoration-id', String(entry.id || ''));
            out.setAttribute('data-decoration-asset-type', 'pixel-json');
            if (entry.placement) out.setAttribute('data-decoration-placement', String(entry.placement));
            if (entry.era) out.setAttribute('data-decoration-era', String(entry.era));
            if (entry.continent) out.setAttribute('data-decoration-continent', String(entry.continent));
            out.width = source.width;
            out.height = source.height;
            out.style.imageRendering = 'pixelated';
            out.style.width = source.width + 'px';
            out.style.height = source.height + 'px';
            out.setAttribute('data-decoration-asset-size', source.width + 'x' + source.height);
            outCtx = out.getContext('2d');
            outCtx.imageSmoothingEnabled = false;
            outCtx.drawImage(source, 0, 0);
            applyDecorationBaseStyle(out, entry);
            setDecorationNodeVisibility(out, visible);
            return out;
        }


        template = getPreparedPixelCanvasSync(ref);
/* CLBI Nations / Historical Events year tabs
        if (template) {
* Mirrors the country information panel model:
            target.appendChild(makeCanvasFromTemplate(template));
* active tab uses .is-active/aria-selected and inactive pages use hidden.
            return true;
*/
        }
(function (mw, $) {
    'use strict';


        /* Fallback path only.  A full entry pack should prepare the template before the
    function activateClbiNationsHistoryYear(panel, targetYear) {
          normal UI is released, so users should not see a blank decoration canvas. */
        var tabs;
        preparePixelCanvas(ref).then(function (source) {
         var pages;
            if (!target || !target.parentNode || !source) return;
            target.appendChild(makeCanvasFromTemplate(source));
         }).catch(function () {});


         return true;
         if (!panel || !targetYear) return false;
    }


    function preloadPixelAssetsForRegistry(registry) {
         tabs = Array.prototype.slice.call(panel.querySelectorAll('.clbi-nations-history-year-button[data-year]'));
         var promises = [];
        pages = Array.prototype.slice.call(panel.querySelectorAll('.clbi-nations-history-page[data-year-panel]'));
        decorationList(registry).forEach(function (entry) {
            var ref;
            if (!entry || !matchesPage(entry) || !isPixelJsonDecoration(entry)) return;
            ref = getPixelJsonRef(entry);
            if (!ref) return;
            promises.push(preparePixelCanvas(ref).catch(function () { return null; }));
        });
        return Promise.all(promises);
    }


    function decorationList(registry) {
         if (!tabs.length || !pages.length) return false;
         if (!registry || typeof registry !== 'object') return [];
        if (Array.isArray(registry)) return registry;
        if (Array.isArray(registry.decorations)) return registry.decorations;
        return [];
    }


    function matchesPage(entry) {
        tabs.forEach(function (tab) {
        var page = currentPageKey();
            var active = tab.getAttribute('data-year') === targetYear;
        var underscored = page.replace(/ /g, '_');
            tab.classList.toggle('is-active', active);
        var pages = entry && entry.pages;
            tab.setAttribute('aria-selected', active ? 'true' : 'false');
        var target = entry && entry.page;
            tab.setAttribute('tabindex', active ? '0' : '-1');
         var i;
         });


         if (normalizeBool(entry && entry.global, false)) return true;
         pages.forEach(function (page) {
        if (String(entry && entry.placement || '').trim() === 'boot-gate' || String(entry && entry.placement || '').trim() === 'loading-screen') {
            var active = page.getAttribute('data-year-panel') === targetYear;
             return true;
             page.classList.toggle('is-active', active);
        }
        if (normalizePageName(target).toLowerCase() === '__boot__' || normalizePageName(target).toLowerCase() === 'loading-screen') return true;
        if (!target && !pages) return true;


        if (Array.isArray(pages)) {
            if (active) {
             for (i = 0; i < pages.length; i += 1) {
                page.removeAttribute('hidden');
                 if (normalizePageName(pages[i]) === page || String(pages[i] || '') === underscored) return true;
             } else {
                 page.setAttribute('hidden', 'hidden');
             }
             }
        }
        target = normalizePageName(target);
        return target === page || target === underscored;
    }
    function clearRendered(root) {
        var scope = root && root.querySelectorAll ? root : document;
        Array.prototype.forEach.call(scope.querySelectorAll('[' + RENDERED_ATTR + '="1"]'), function (node) {
            if (node.parentNode) node.parentNode.removeChild(node);
         });
         });
    }


    function ensureHost(target) {
         return true;
         var style;
        if (!target) return;
        target.setAttribute(HOST_ATTR, '1');
        style = window.getComputedStyle ? window.getComputedStyle(target) : null;
        if (style && style.position === 'static') target.style.position = 'relative';
     }
     }


     function applyDecoration(entry) {
     function moveClbiNationsHistoryYear(panel, direction) {
         var resolved;
         var tabs;
        var activeIndex;
        var nextIndex;
         var target;
         var target;
        var src;
        var img;
        var width;
        var height;


         if (!entry || typeof entry !== 'object' || normalizeBool(entry.enabled, true) === false) return false;
         if (!panel) return false;
        resolved = resolveDecorationPlacement(entry);
        if (!resolved) return false;
        target = resolved.target;
        if (!target) return false;


         ensureHost(target);
         tabs = Array.prototype.slice.call(panel.querySelectorAll('.clbi-nations-history-year-button[data-year]'));
        if (!tabs.length) return false;


         if (isPixelJsonDecoration(entry)) {
         activeIndex = tabs.findIndex(function (tab) {
             return applyPixelJsonDecoration(entry, target, resolved.visible !== false);
             return tab.classList.contains('is-active') || tab.getAttribute('aria-selected') === 'true';
         }
         });


        src = normalizeSrc(entry.src);
         if (activeIndex < 0) activeIndex = 0;
         if (!src) return false;


         img = document.createElement('img');
         nextIndex = (activeIndex + direction + tabs.length) % tabs.length;
        img.className = 'wiki-decoration';
         target = tabs[nextIndex].getAttribute('data-year');
        img.setAttribute(RENDERED_ATTR, '1');
        img.setAttribute('aria-hidden', 'true');
         img.setAttribute('alt', '');
        img.setAttribute('decoding', 'async');
        img.setAttribute('loading', 'eager');
        img.setAttribute('data-decoration-id', String(entry.id || ''));
        if (entry.placement) img.setAttribute('data-decoration-placement', String(entry.placement));
        if (entry.era) img.setAttribute('data-decoration-era', String(entry.era));
        if (entry.continent) img.setAttribute('data-decoration-continent', String(entry.continent));
        img.src = src;


         applyDecorationBaseStyle(img, entry);
         if (activateClbiNationsHistoryYear(panel, target)) {
        width = normalizeNumber(entry.width, NaN);
            tabs[nextIndex].focus();
        height = normalizeNumber(entry.height, NaN);
            return true;
        if (Number.isFinite(width) && width > 0) img.style.width = width + 'px';
         }
        if (Number.isFinite(height) && height > 0) img.style.height = height + 'px';
        if (entry.objectFit) img.style.objectFit = String(entry.objectFit);
         setDecorationNodeVisibility(img, resolved.visible !== false);


        target.appendChild(img);
         return false;
         return true;
     }
     }


     function render(registry) {
     function initClbiNationsHistoryYearTabs(root) {
         var token = runtimeToken;
         var scope = root && root.querySelectorAll ? root : document;
        lastRegistry = registry || { decorations: [] };
         var panels = scope.querySelectorAll('.clbi-nations-history-panel');
         lastRenderedPageKey = currentPageKey();
 
        bindNationsPlacementRefresh();
         Array.prototype.forEach.call(panels, function (panel) {
         clearRendered(document);
             if (panel.getAttribute('data-clbi-history-tabs-ready') === '1') return;
        decorationList(lastRegistry).forEach(function (entry) {
 
             if (token === runtimeToken && matchesPage(entry)) applyDecoration(entry);
            panel.setAttribute('data-clbi-history-tabs-ready', '1');
        });
    }


    function renderPrepared() {
            panel.addEventListener('click', function (event) {
        var registry = getPreparedRegistrySync() || lastRegistry;
                var tab = event.target.closest ? event.target.closest('.clbi-nations-history-year-button[data-year]') : null;
        if (!registry) return false;
        render(registry);
        return true;
    }


    function syncDecorationState() {
                if (!tab || !panel.contains(tab)) return;
        if (lastRenderedPageKey === currentPageKey() && hasRenderedDecorations(document)) {
 
            updateDecorationVisibility(document);
                if (activateClbiNationsHistoryYear(panel, tab.getAttribute('data-year'))) {
            return true;
                    event.preventDefault();
        }
                }
        if (lastRegistry) {
             });
            render(lastRegistry);
             return true;
        }
        return renderPrepared();
    }


    function scheduleRenderFromCache() {
            panel.addEventListener('keydown', function (event) {
        if (scheduledRender) return;
                var tab = event.target.closest ? event.target.closest('.clbi-nations-history-year-button[data-year]') : null;
        scheduledRender = window.requestAnimationFrame ? window.requestAnimationFrame(function () {
                var handled = false;
            scheduledRender = 0;
            if (!syncDecorationState()) reload();
        }) : window.setTimeout(function () {
            scheduledRender = 0;
            if (!syncDecorationState()) reload();
        }, 0);
    }


    function scheduleDecorationVisibilityUpdate() {
                if (!tab || !panel.contains(tab)) return;
        if (scheduledRender) return;
        scheduledRender = window.requestAnimationFrame ? window.requestAnimationFrame(function () {
            scheduledRender = 0;
            if (lastRenderedPageKey !== currentPageKey() || !hasRenderedDecorations(document)) {
                if (!syncDecorationState()) reload();
                return;
            }
            updateDecorationVisibility(document);
        }) : window.setTimeout(function () {
            scheduledRender = 0;
            if (lastRenderedPageKey !== currentPageKey() || !hasRenderedDecorations(document)) {
                if (!syncDecorationState()) reload();
                return;
            }
            updateDecorationVisibility(document);
        }, 0);
    }


    function bindNationsPlacementRefresh() {
                if (event.key === 'ArrowLeft') handled = moveClbiNationsHistoryYear(panel, -1);
        var stack = document.querySelector('.clbi-nations-panel-stack');
                else if (event.key === 'ArrowRight') handled = moveClbiNationsHistoryYear(panel, 1);
                else if (event.key === 'Home') handled = activateClbiNationsHistoryYear(panel, (panel.querySelector('.clbi-nations-history-year-button[data-year]') || {}).getAttribute && panel.querySelector('.clbi-nations-history-year-button[data-year]').getAttribute('data-year'));
                else if (event.key === 'End') {
                    var tabs = panel.querySelectorAll('.clbi-nations-history-year-button[data-year]');
                    var last = tabs[tabs.length - 1];
                    handled = last ? activateClbiNationsHistoryYear(panel, last.getAttribute('data-year')) : false;
                    if (handled) last.focus();
                }


        if (!stack || observedNationsStack === stack) return;
                if (handled) {
         observedNationsStack = stack;
                    event.preventDefault();
                    event.stopPropagation();
                }
            });
         });
    }


        if (nationsPlacementObserver) {
    window.initClbiNationsHistoryYearTabs = initClbiNationsHistoryYearTabs;
            nationsPlacementObserver.disconnect();
        }


        if (typeof MutationObserver === 'function') {
    $(function () {
            nationsPlacementObserver = new MutationObserver(scheduleDecorationVisibilityUpdate);
        initClbiNationsHistoryYearTabs(document);
            nationsPlacementObserver.observe(stack, {
    });
                subtree: true,
                attributes: true,
                attributeFilter: ['class', 'hidden', 'aria-selected', 'data-current-era', 'data-nations-current-era', 'data-era-year']
            });
        }
    }


     function getPreparedRegistrySync() {
     if (mw && mw.hook) {
        var registry = null;
        mw.hook('wikipage.content').add(function ($content) {
        var url;
             initClbiNationsHistoryYearTabs($content && $content[0] ? $content[0] : document);
        try {
            if (window.EntryStore && typeof window.EntryStore.getJsonSync === 'function') {
                registry = window.EntryStore.getJsonSync(REGISTRY_TITLE);
                if (!registry && mw && mw.util && typeof mw.util.getUrl === 'function') {
                    url = mw.util.getUrl(REGISTRY_TITLE, { action: 'raw', ctype: 'application/json' });
                    registry = window.EntryStore.getJsonSync(url);
                }
             }
        } catch (err) {}
        return registry && typeof registry === 'object' ? registry : null;
    }
 
    function fetchRegistry() {
        var url;
        var prepared = getPreparedRegistrySync();
        if (prepared) return Promise.resolve(prepared);
        if (!mw || !mw.util || typeof fetch !== 'function') return Promise.resolve({ decorations: [] });
        url = mw.util.getUrl(REGISTRY_TITLE, {
            action: 'raw',
            ctype: 'application/json'
         });
         });
        return fetch(url, { credentials: 'same-origin', cache: 'force-cache' })
            .then(function (response) {
                if (!response.ok) throw new Error('HTTP ' + response.status);
                return response.text();
            })
            .then(function (text) {
                if (!text || !text.trim()) return { decorations: [] };
                return JSON.parse(text);
            })
            .catch(function () {
                return { decorations: [] };
            });
     }
     }
})(mediaWiki, jQuery);


    function reload() {
        var token;
        runtimeToken += 1;
        token = runtimeToken;
        return fetchRegistry().then(function (registry) {
            return preloadPixelAssetsForRegistry(registry).then(function () {
                if (token === runtimeToken) render(registry);
                return registry;
            });
        });
    }


    document.addEventListener('click', function (event) {
/* =========================================
        var target = event.target && event.target.closest ? event.target.closest('.clbi-nations-tabpanel-tab[data-continent], [data-nations-era-move]') : null;
  Decoration runtime renderer
        if (target) window.setTimeout(scheduleDecorationVisibilityUpdate, 0);
  ========================================= */
    }, true);
(function (mw) {
    'use strict';


     function decorationDiagnostics() {
     var REGISTRY_TITLE = 'MediaWiki:Decorations.json';
        return {
    var RENDERED_ATTR = 'data-wiki-decoration-rendered';
            build: '20260708-nations-mouse-click-live-cache-guard-001',
    var HOST_ATTR = 'data-wiki-decoration-host';
            hasRegistry: !!lastRegistry,
    var MAIN_PAGE_PLACEMENT = 'main-body-well';
            entries: decorationList(lastRegistry).length,
    var MAIN_PAGE_TARGET = '.main-portal .main-body-well';
            rendered: document.querySelectorAll('[' + RENDERED_ATTR + '="1"]').length,
    var runtimeToken = 0;
            preparedRegistry: !!getPreparedRegistrySync(),
    var lastRegistry = null;
            pixelAssets: Object.keys(pixelAssetCache || {}).length,
    var lastRenderedPageKey = '';
            pixelCanvases: Object.keys(pixelCanvasCache || {}).length,
    var scheduledRender = 0;
            visibilityOnlySync: true,
    var nationsPlacementObserver = null;
             lastRenderedPage: lastRenderedPageKey,
    var observedNationsStack = null;
            visibleRendered: document.querySelectorAll('[' + RENDERED_ATTR + '="1"][data-decoration-visible="1"]').length,
    var mainPagePlacementObserver = null;
             scheduled: !!scheduledRender
    var mainPagePlacementMutationObserver = null;
        };
    var observedMainPagePortal = null;
     }
    var scheduledMainPageRebase = 0;
 
    var pixelAssetCache = {};
     window.Decorations = window.Decorations || {};
    var pixelCanvasCache = {};
    window.Decorations.reload = reload;
 
     window.Decorations.render = render;
    function normalizePageName(value) {
    window.Decorations.renderPrepared = renderPrepared;
        return String(value || '')
    window.Decorations.sync = syncDecorationState;
             .split('?')[0]
    window.Decorations.updateVisibility = updateDecorationVisibility;
            .replace(/^\/index\.php\//, '')
    window.Decorations.diagnostics = decorationDiagnostics;
            .replace(/_/g, ' ')
    window.Decorations.clear = clearRendered;
             .trim();
    window.Decorations.apply = applyDecoration;
     }
    window.Decorations.pageKey = currentPageKey;
 
    window.Decorations.loadPixelAsset = fetchPixelAsset;
     function currentPageKey() {
    window.Decorations.preparePixelCanvas = preparePixelCanvas;
        var raw = mw && mw.config ? String(mw.config.get('wgPageName') || '') : '';
    window.Decorations.getPreparedPixelCanvasSync = getPreparedPixelCanvasSync;
        return normalizePageName(raw) || raw || '대문';
    window.Decorations.drawPixelAssetToCanvas = drawPixelAssetToCanvas;
     }
 
 
    window.CLBI_DECORATIONS = window.CLBI_DECORATIONS || {};
    function ensureMainPageBodyWell() {
    window.CLBI_DECORATIONS.reload = reload;
        var portal;
    window.CLBI_DECORATIONS.render = render;
        var topMount;
    window.CLBI_DECORATIONS.renderPrepared = renderPrepared;
        var panel;
    window.CLBI_DECORATIONS.sync = syncDecorationState;
        var well;
    window.CLBI_DECORATIONS.updateVisibility = updateDecorationVisibility;
        var manifesto;
    window.CLBI_DECORATIONS.diagnostics = decorationDiagnostics;
 
    window.CLBI_DECORATIONS.clear = clearRendered;
        if (currentPageKey() !== '대문') return null;
    window.CLBI_DECORATIONS.apply = applyDecoration;
 
    window.CLBI_DECORATIONS.pageKey = currentPageKey;
        portal = document.querySelector('.main-portal');
    window.CLBI_DECORATIONS.loadPixelAsset = fetchPixelAsset;
        if (!portal) return null;
    window.CLBI_DECORATIONS.preparePixelCanvas = preparePixelCanvas;
 
    window.CLBI_DECORATIONS.getPreparedPixelCanvasSync = getPreparedPixelCanvasSync;
        topMount = portal.querySelector('[data-component="category-nav"]');
    window.CLBI_DECORATIONS.drawPixelAssetToCanvas = drawPixelAssetToCanvas;
        panel = portal.querySelector('.main-body-panel');
 
        well = portal.querySelector('.main-body-well');
    if (document.readyState === 'loading') {
        manifesto = portal.querySelector('.main-manifesto');
        document.addEventListener('DOMContentLoaded', reload);
 
    } else {
        if (!panel) {
        reload();
            panel = document.createElement('div');
    }
            panel.className = 'main-body-panel';
 
            panel.setAttribute('data-main-body-panel-generated', '1');
    if (mw && mw.hook) {
 
        mw.hook('wikipage.content').add(function () {
            if (topMount && topMount.parentNode) {
            reload();
                if (topMount.nextSibling) {
        });
                    topMount.parentNode.insertBefore(panel, topMount.nextSibling);
     }
                } else {
})(mediaWiki);
                    topMount.parentNode.appendChild(panel);
                }
            } else {
                portal.appendChild(panel);
            }
        }
 
        if (!well) {
            well = document.createElement('div');
            well.className = 'main-body-well';
            well.setAttribute('data-main-body-well-generated', '1');
            panel.appendChild(well);
        } else if (well.parentNode !== panel) {
            panel.appendChild(well);
        }
 
        if (manifesto && manifesto.parentNode !== well) {
            well.insertBefore(manifesto, well.firstChild);
        }
 
        return well;
    }
 
 
    function cssAttrEscape(value) {
        return String(value || '').replace(/\\/g, '\\\\').replace(/"/g, '\\"');
     }
 
    function getActiveNationsEra() {
        var content = document.querySelector('.clbi-nations-era-content.is-active[data-era-content]:not([hidden])');
        var title;
        var globe;
 
        if (content) return content.getAttribute('data-era-content') || '';
 
        title = document.querySelector('.clbi-nations-era-title-plate.is-active[data-era]');
        if (title) return title.getAttribute('data-era') || '';
 
        globe = document.querySelector('.clbi-nations-globe-window[data-nations-globe]');
        if (globe) {
            return globe.getAttribute('data-current-era') || globe.getAttribute('data-nations-current-era') || globe.getAttribute('data-era-year') || '';
        }
 
        return '';
    }
 
    function getActiveNationsEraPanel() {
        var era = getActiveNationsEra();
        var selector;
        if (!era) return document.querySelector('.clbi-nations-era-content.is-active[data-era-content]:not([hidden])');
        selector = '.clbi-nations-era-content[data-era-content="' + cssAttrEscape(era) + '"]';
        return document.querySelector(selector) || document.querySelector('.clbi-nations-era-content.is-active[data-era-content]:not([hidden])');
    }
 
    function getActiveNationsContinent() {
        var eraPanel = getActiveNationsEraPanel();
        var root = eraPanel || document;
        var tab = root.querySelector('.clbi-nations-tabpanel-tab.is-active[data-continent], .clbi-nations-tabpanel-tab[aria-selected="true"][data-continent]');
        var panel;
 
        if (tab) return tab.getAttribute('data-continent') || '';
 
        panel = root.querySelector('.clbi-nations-tabpanel-continent.is-active[data-continent-panel]');
        if (panel) return panel.getAttribute('data-continent-panel') || '';
 
        return '';
    }
 
    function getDecorationNationsBodySelector(era) {
        if (era) {
            return '.clbi-nations-era-content[data-era-content="' + cssAttrEscape(era) + '"] .clbi-nations-tabpanel-body';
        }
        return '.clbi-nations-era-content.is-active[data-era-content]:not([hidden]) .clbi-nations-tabpanel-body, .clbi-nations-tabpanel-body';
    }
 
    /*
    Decoration semantic placement resolver
    -----------------------------------------
    장식 저장 데이터의 placement 값은 "사용자가 고른 의미상 위치"를 나타낸다.
    resolver는 그 의미값을 실제 DOM 부착 위치와 표시 조건으로 번역한다.
 
    예: 시대 문서에서 사용자가 1950년 / 아메리카를 지정하면 의미상 scope는
    그 조합이지만, 이미지를 붙일 기준면은 대륙 패널 자체가 아니라
    .clbi-nations-tabpanel-body이다. 따라서 placement=nations-continent-body는
    .clbi-nations-tabpanel-body에 이미지를 붙이고, 현재 활성 연도와 대륙이 저장값과
    일치할 때만 렌더링한다.
 
    유지보수 규칙:
    - 새 조합형 문서가 생기면 entry.target을 매번 특수하게 저장하지 말고 placement를 추가한다.
    - DevTools.js 에디터 미리보기와 Common.js 런타임 렌더러의 resolver는 같은 의미를 가져야 한다.
    - target은 물리적 기준면, era/continent 같은 필드는 표시 조건으로 다룬다.
    */
    function shouldUseNationsBodyPlacement(entry) {
        var placement = String(entry && entry.placement || '').trim();
        var target = String(entry && entry.target || '').trim();
        var era = String(entry && entry.era || '').trim();
        var continent = String(entry && entry.continent || '').trim();
 
        if (!document.querySelector('.clbi-nations-panel-stack')) return false;
        if (placement === 'nations-continent-body') return true;
        if (era || continent) return true;
        if (target.indexOf('clbi-nations-tabpanel-continent') !== -1) return true;
        return false;
    }
 
    function resolveDecorationPlacement(entry) {
        var placement = String(entry && entry.placement || '').trim();
        var selector = String(entry && entry.target || '').trim() || '.liberty-content-main';
        var era = String(entry && entry.era || '').trim();
        var continent = String(entry && entry.continent || '').trim();
        var target;
 
        if (!placement && shouldUseNationsBodyPlacement(entry)) {
            placement = 'nations-continent-body';
        }
 
        if (placement === 'boot-gate' || placement === 'loading-screen') {
            selector = '#boot-gate-screen .boot-gate-decoration-layer, #boot-gate-screen';
            target = document.querySelector(selector);
            return {
                placement: placement,
                target: target,
                targetSelector: selector,
                visible: !!document.getElementById('boot-gate-screen')
            };
        }
 
        if (placement === 'nations-continent-body') {
            selector = getDecorationNationsBodySelector(era);
            target = document.querySelector(selector) || document.querySelector('.clbi-nations-tabpanel-body') || document.querySelector(String(entry && entry.target || '').trim());
            return {
                placement: placement,
                target: target,
                targetSelector: selector,
                visible: (!era || era === getActiveNationsEra()) && (!continent || continent === getActiveNationsContinent())
            };
        }
 
        /*
        대문의 일반 장식은 저장된 target과 관계없이 본문 우물 안에서 렌더링한다.
        우물이 overflow:hidden이므로 #1d1d1d 프레임 밖으로 나갈 수 없다.
        boot/loading 및 국가 패널 전용 placement는 위 분기에서 기존 동작을 유지한다.
        */
        var mainPageWell = ensureMainPageBodyWell();
        if (mainPageWell) {
            return {
                placement: MAIN_PAGE_PLACEMENT,
                target: mainPageWell,
                targetSelector: MAIN_PAGE_TARGET,
                visible: true
            };
        }
 
        return {
            placement: placement,
            target: document.querySelector(selector),
            targetSelector: selector,
            visible: true
        };
    }
 
    function normalizeNumber(value, fallback) {
        var n = parseFloat(value);
        return Number.isFinite(n) ? n : fallback;
    }
 
    function normalizeBool(value, fallback) {
        if (value === true || value === 'true' || value === '1' || value === 1) return true;
        if (value === false || value === 'false' || value === '0' || value === 0) return false;
        return fallback;
    }
 
    function normalizeSrc(src) {
        src = String(src || '').trim();
        if (!src) return '';
        if (/^(?:https?:)?\/\//i.test(src) || src.charAt(0) === '/' || src.indexOf('data:') === 0 || src.indexOf('blob:') === 0) return src;
        return '/index.php/Special:Redirect/file/' + encodeURIComponent(src);
    }
 
 
    function normalizeAssetType(entry) {
        var type = String(entry && entry.assetType || '').trim().toLowerCase();
        var ref = String(entry && (entry.asset || entry.src) || '').trim();
 
        if (type === 'clbi-pixel-json' || type === 'pixel-rle' || type === 'pixel-json') return 'pixel-json';
        if (!type && /\.json(?:[?#].*)?$/i.test(ref)) return 'pixel-json';
        return type || 'image';
    }
 
    function isPixelJsonDecoration(entry) {
        return normalizeAssetType(entry) === 'pixel-json';
    }
 
    function getPixelJsonRef(entry) {
        return String(entry && (entry.asset || entry.src) || '').trim();
    }
 
    function normalizePixelJsonUrl(ref) {
        ref = String(ref || '').trim();
        if (!ref) return '';
        if (/^(?:https?:)?\/\//i.test(ref) || ref.charAt(0) === '/' || ref.indexOf('data:') === 0 || ref.indexOf('blob:') === 0) return ref;
        if (/^(?:file|파일):/i.test(ref)) return '/index.php/Special:Redirect/file/' + encodeURIComponent(ref.replace(/^(?:file|파일):/i, ''));
        if (mw && mw.util && typeof mw.util.getUrl === 'function') {
            if (ref.indexOf(':') !== -1) {
                return mw.util.getUrl(ref, { action: 'raw', ctype: 'application/json' });
            }
            return mw.util.getUrl('MediaWiki:' + ref, { action: 'raw', ctype: 'application/json' });
        }
        return ref;
    }
 
    function parsePixelColor(value) {
        var text;
        var m;
        if (Array.isArray(value)) {
            return [
                Math.max(0, Math.min(255, Number(value[0]) || 0)),
                Math.max(0, Math.min(255, Number(value[1]) || 0)),
                Math.max(0, Math.min(255, Number(value[2]) || 0)),
                value.length > 3 ? Math.max(0, Math.min(255, Number(value[3]) || 0)) : 255
            ];
        }
        text = String(value || '').trim();
        m = text.match(/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);
        if (!m) return [0, 0, 0, 0];
        text = m[1];
        if (text.length === 3 || text.length === 4) {
            return [
                parseInt(text.charAt(0) + text.charAt(0), 16),
                parseInt(text.charAt(1) + text.charAt(1), 16),
                parseInt(text.charAt(2) + text.charAt(2), 16),
                text.length === 4 ? parseInt(text.charAt(3) + text.charAt(3), 16) : 255
            ];
        }
        return [
            parseInt(text.slice(0, 2), 16),
            parseInt(text.slice(2, 4), 16),
            parseInt(text.slice(4, 6), 16),
            text.length === 8 ? parseInt(text.slice(6, 8), 16) : 255
        ];
    }
 
 
    function decodePixelRle36(value) {
        var text = String(value || '').trim();
        var parts;
        var runs = [];
        var i;
        var x;
        var y;
        var len;
        var colorIndex;
 
        if (!text) return runs;
        parts = text.split(',');
        for (i = 0; i + 3 < parts.length; i += 4) {
            x = parseInt(parts[i], 36);
            y = parseInt(parts[i + 1], 36);
            len = parseInt(parts[i + 2], 36);
            colorIndex = parseInt(parts[i + 3], 36);
            if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(len) || !Number.isFinite(colorIndex)) continue;
            runs.push([x, y, len, colorIndex]);
        }
        return runs;
    }
 
    function normalizePixelAsset(doc) {
        var encoding = String(doc && (doc.encoding || doc.e) || '').trim().toLowerCase();
        var width = Math.round(Number(doc && (doc.width || doc.w)) || 0);
        var height = Math.round(Number(doc && (doc.height || doc.h)) || 0);
        var paletteSource = Array.isArray(doc && doc.palette) ? doc.palette : (Array.isArray(doc && doc.p) ? doc.p : []);
        var palette = paletteSource.map(parsePixelColor);
        var runs;
 
        /*
        CLBI Pixel Forge v0.2.3 compact format:
        - MediaWiki 단일 문서 크기 제한을 피하기 위해 사람이 읽기 쉬운 [[x,y,len,c], ...] 배열 대신
          base36 토큰 문자열을 쓴다.
        - 형식은 x,y,len,colorIndex를 4개 토큰 단위로 반복한 rle36이다.
        - 복원 후 좌표계는 기존 runs 배열과 완전히 같으며, 최종 CSS px에 1:1로 찍는다.
        */
        if ((encoding === 'rle36' || encoding === 'clbi-rle36') && typeof (doc && doc.r) === 'string') {
            runs = decodePixelRle36(doc.r);
        } else {
            runs = Array.isArray(doc && doc.runs) ? doc.runs : [];
        }
 
        if (!width || !height || width < 1 || height < 1) throw new Error('invalid pixel decoration size');
        if (width > 8192 || height > 8192) throw new Error('pixel decoration too large');
        return {
            type: String(doc && (doc.type || doc.t) || 'clbi-pixel-decoration'),
            version: Number(doc && (doc.version || doc.v)) || 1,
            encoding: encoding || 'runs',
            width: width,
            height: height,
            palette: palette,
            runs: runs
        };
    }
 
    function fetchPixelAsset(ref) {
        var url = normalizePixelJsonUrl(ref);
        var cached;
        if (!url) return Promise.reject(new Error('pixel json ref is empty'));
        cached = pixelAssetCache[url];
        if (cached) return cached.promise;
        cached = {
            promise: fetch(url, { credentials: 'same-origin', cache: 'force-cache' })
                .then(function (response) {
                    if (!response.ok) throw new Error('HTTP ' + response.status);
                    return response.json();
                })
                .then(normalizePixelAsset)
        };
        pixelAssetCache[url] = cached;
        return cached.promise;
    }
 
    function drawPixelAssetToCanvas(canvas, asset) {
        var ctx;
        var image;
        var data;
        var i;
        var run;
        var x;
        var y;
        var len;
        var color;
        var colorIndex;
        var p;
        var k;
 
        canvas.width = asset.width;
        canvas.height = asset.height;
        ctx = canvas.getContext('2d');
        ctx.imageSmoothingEnabled = false;
        image = ctx.createImageData(asset.width, asset.height);
        data = image.data;
 
        for (i = 0; i < asset.runs.length; i += 1) {
            run = asset.runs[i];
            if (!Array.isArray(run) || run.length < 4) continue;
            x = Math.round(Number(run[0]) || 0);
            y = Math.round(Number(run[1]) || 0);
            len = Math.round(Number(run[2]) || 0);
            colorIndex = Math.round(Number(run[3]) || 0);
            color = asset.palette[colorIndex];
            if (!color || len <= 0 || y < 0 || y >= asset.height || x >= asset.width) continue;
            if (x < 0) {
                len += x;
                x = 0;
            }
            len = Math.min(len, asset.width - x);
            for (k = 0; k < len; k += 1) {
                p = ((y * asset.width) + x + k) * 4;
                data[p] = color[0];
                data[p + 1] = color[1];
                data[p + 2] = color[2];
                data[p + 3] = color[3];
            }
        }
 
        ctx.putImageData(image, 0, 0);
    }
 
    function preparePixelCanvas(ref) {
        var url = normalizePixelJsonUrl(ref);
        var cached;
        if (!url) return Promise.reject(new Error('pixel json ref is empty'));
        cached = pixelCanvasCache[url];
        if (cached) return cached.promise;
        cached = {};
        cached.promise = fetchPixelAsset(ref).then(function (asset) {
            var canvas = document.createElement('canvas');
            drawPixelAssetToCanvas(canvas, asset);
            canvas.style.imageRendering = 'pixelated';
            canvas.setAttribute('data-decoration-asset-size', asset.width + 'x' + asset.height);
            cached.canvas = canvas;
            cached.width = asset.width;
            cached.height = asset.height;
            return canvas;
        });
        pixelCanvasCache[url] = cached;
        return cached.promise;
    }
 
    function getPreparedPixelCanvasSync(ref) {
        var url = normalizePixelJsonUrl(ref);
        var cached = url ? pixelCanvasCache[url] : null;
        return cached && cached.canvas ? cached.canvas : null;
    }
 
    function queryDecorationTarget(selector) {
        selector = String(selector || '').trim();
        if (!selector) return null;
        try {
            return document.querySelector(selector);
        } catch (err) {
            return null;
        }
    }
 
    function usesCanonicalMainPageCoordinates(entry, actualTarget) {
        var placement = String(entry && entry.placement || '').trim();
        var selector = String(entry && entry.target || '').trim();
        var declaredTarget;
 
        if (placement === MAIN_PAGE_PLACEMENT) return true;
        if (!actualTarget || !selector) return false;
 
        declaredTarget = queryDecorationTarget(selector);
        return declaredTarget === actualTarget;
    }
 
    function getDecorationLocalPosition(entry, actualTarget) {
        var x = normalizeNumber(entry && entry.x, 0);
        var y = normalizeNumber(entry && entry.y, 0);
        var sourceX = x;
        var sourceY = y;
        var sourceSelector;
        var sourceTarget;
        var sourceRect;
        var actualRect;
        var sourceOriginX;
        var sourceOriginY;
        var actualOriginX;
        var actualOriginY;
 
        /*
        대문 데코 좌표 보존
        -----------------------------------------
        저장된 x/y는 기존 entry.target 좌표계를 기준으로 만들어졌다.
        데코를 main-body-well 안으로 옮길 때 x/y를 그대로 적용하면
        더 아래에서 시작하는 새 좌표계 때문에 장식이 바닥으로 밀린다.
 
        실제 화면상의 위치는 유지하고 부모만 우물로 바꾼다.
        기존 기준면의 padding-box 원점과 새 우물의 padding-box 원점 차이를
        정수 px로 더해 새 로컬 좌표를 만든다.
        */
        if (
            currentPageKey() === '대문' &&
            actualTarget &&
            actualTarget.classList &&
            actualTarget.classList.contains('main-body-well') &&
            !usesCanonicalMainPageCoordinates(entry, actualTarget)
        ) {
            sourceSelector = String(entry && entry.target || '').trim() ||
                '.liberty-content-main';
            sourceTarget = queryDecorationTarget(sourceSelector) ||
                document.querySelector('.liberty-content-main') ||
                document.querySelector('.main-portal');
 
            if (sourceTarget && sourceTarget !== actualTarget) {
                sourceRect = sourceTarget.getBoundingClientRect();
                actualRect = actualTarget.getBoundingClientRect();
 
                sourceOriginX = sourceRect.left + normalizeNumber(sourceTarget.clientLeft, 0);
                sourceOriginY = sourceRect.top + normalizeNumber(sourceTarget.clientTop, 0);
                actualOriginX = actualRect.left + normalizeNumber(actualTarget.clientLeft, 0);
                actualOriginY = actualRect.top + normalizeNumber(actualTarget.clientTop, 0);
 
                x += Math.round(sourceOriginX - actualOriginX);
                y += Math.round(sourceOriginY - actualOriginY);
            }
        }
 
        return {
            x: Math.round(x),
            y: Math.round(y),
            sourceX: Math.round(sourceX),
            sourceY: Math.round(sourceY),
            sourceSelector: sourceSelector || ''
        };
    }
 
    function applyDecorationBaseStyle(node, entry, actualTarget) {
        var position = getDecorationLocalPosition(entry, actualTarget);
 
        node.style.left = position.x + 'px';
        node.style.top = position.y + 'px';
        node.style.opacity = String(normalizeNumber(entry.opacity, 1));
        node.style.zIndex = String(Math.round(normalizeNumber(entry.zIndex, 0)));
        node.style.pointerEvents = String(entry.pointerEvents || 'none');
 
        if (position.sourceSelector) {
            node.setAttribute('data-decoration-coordinate-source', position.sourceSelector);
            node.setAttribute('data-decoration-source-x', String(position.sourceX));
            node.setAttribute('data-decoration-source-y', String(position.sourceY));
            node.setAttribute('data-decoration-local-x', String(position.x));
            node.setAttribute('data-decoration-local-y', String(position.y));
        }
 
        if (entry.blendMode) node.style.mixBlendMode = String(entry.blendMode);
        if (entry.filter) node.style.filter = String(entry.filter);
        if (entry.transform) node.style.transform = String(entry.transform);
    }
 
    function isDecorationNodeActiveForNationsState(node) {
        var era = node ? String(node.getAttribute('data-decoration-era') || '').trim() : '';
        var continent = node ? String(node.getAttribute('data-decoration-continent') || '').trim() : '';
        if (era && era !== getActiveNationsEra()) return false;
        if (continent && continent !== getActiveNationsContinent()) return false;
        return true;
    }
 
    function setDecorationNodeVisibility(node, visible) {
        if (!node) return;
        visible = visible !== false;
        /* aria-hidden stays true because wiki decorations are purely visual. */
        if (node.hidden !== !visible) node.hidden = !visible;
        if (node.style.display !== (visible ? '' : 'none')) node.style.display = visible ? '' : 'none';
        node.setAttribute('data-decoration-visible', visible ? '1' : '0');
    }
 
    function updateDecorationVisibility(root) {
        var scope = root && root.querySelectorAll ? root : document;
        var count = 0;
        Array.prototype.forEach.call(scope.querySelectorAll('[' + RENDERED_ATTR + '="1"]'), function (node) {
            setDecorationNodeVisibility(node, isDecorationNodeActiveForNationsState(node));
            count += 1;
        });
        return count;
    }
 
    function hasRenderedDecorations(root) {
        var scope = root && root.querySelector ? root : document;
        return !!(scope && scope.querySelector && scope.querySelector('[' + RENDERED_ATTR + '="1"]'));
    }
 
    function applyPixelJsonDecoration(entry, target, visible) {
        var ref = getPixelJsonRef(entry);
        var template;
        var canvas;
        var ctx;
        if (!ref) return false;
 
        function makeCanvasFromTemplate(source) {
            var out = document.createElement('canvas');
            var outCtx;
            out.className = 'wiki-decoration wiki-decoration-pixel-json';
            out.setAttribute(RENDERED_ATTR, '1');
            out.setAttribute('aria-hidden', 'true');
            out.setAttribute('data-decoration-id', String(entry.id || ''));
            out.setAttribute('data-decoration-asset-type', 'pixel-json');
            if (entry.placement) out.setAttribute('data-decoration-placement', String(entry.placement));
            if (entry.era) out.setAttribute('data-decoration-era', String(entry.era));
            if (entry.continent) out.setAttribute('data-decoration-continent', String(entry.continent));
            out.width = source.width;
            out.height = source.height;
            out.style.imageRendering = 'pixelated';
            out.style.width = source.width + 'px';
            out.style.height = source.height + 'px';
            out.setAttribute('data-decoration-asset-size', source.width + 'x' + source.height);
            outCtx = out.getContext('2d');
            outCtx.imageSmoothingEnabled = false;
            outCtx.drawImage(source, 0, 0);
            applyDecorationBaseStyle(out, entry, target);
            setDecorationNodeVisibility(out, visible);
            return out;
        }
 
        template = getPreparedPixelCanvasSync(ref);
        if (template) {
            target.appendChild(makeCanvasFromTemplate(template));
            return true;
        }
 
        /* Fallback path only.  A full entry pack should prepare the template before the
          normal UI is released, so users should not see a blank decoration canvas. */
        preparePixelCanvas(ref).then(function (source) {
            if (!target || !target.parentNode || !source) return;
            target.appendChild(makeCanvasFromTemplate(source));
        }).catch(function () {});
 
        return true;
    }
 
    function preloadPixelAssetsForRegistry(registry) {
        var promises = [];
        decorationList(registry).forEach(function (entry) {
            var ref;
            if (!entry || !matchesPage(entry) || !isPixelJsonDecoration(entry)) return;
            ref = getPixelJsonRef(entry);
            if (!ref) return;
            promises.push(preparePixelCanvas(ref).catch(function () { return null; }));
        });
        return Promise.all(promises);
    }
 
    function decorationList(registry) {
        if (!registry || typeof registry !== 'object') return [];
        if (Array.isArray(registry)) return registry;
        if (Array.isArray(registry.decorations)) return registry.decorations;
        return [];
    }
 
    function matchesPage(entry) {
        var page = currentPageKey();
        var underscored = page.replace(/ /g, '_');
        var pages = entry && entry.pages;
        var target = entry && entry.page;
        var i;
 
        if (normalizeBool(entry && entry.global, false)) return true;
        if (String(entry && entry.placement || '').trim() === 'boot-gate' || String(entry && entry.placement || '').trim() === 'loading-screen') {
            return true;
        }
        if (normalizePageName(target).toLowerCase() === '__boot__' || normalizePageName(target).toLowerCase() === 'loading-screen') return true;
        if (!target && !pages) return true;
 
        if (Array.isArray(pages)) {
            for (i = 0; i < pages.length; i += 1) {
                if (normalizePageName(pages[i]) === page || String(pages[i] || '') === underscored) return true;
            }
        }
 
        target = normalizePageName(target);
        return target === page || target === underscored;
    }
 
    function clearRendered(root) {
        var scope = root && root.querySelectorAll ? root : document;
        Array.prototype.forEach.call(scope.querySelectorAll('[' + RENDERED_ATTR + '="1"]'), function (node) {
            if (node.parentNode) node.parentNode.removeChild(node);
        });
    }
 
    function ensureHost(target) {
        var style;
        if (!target) return;
        target.setAttribute(HOST_ATTR, '1');
        style = window.getComputedStyle ? window.getComputedStyle(target) : null;
        if (style && style.position === 'static') target.style.position = 'relative';
    }
 
    function applyDecoration(entry) {
        var resolved;
        var target;
        var src;
        var img;
        var width;
        var height;
 
        if (!entry || typeof entry !== 'object' || normalizeBool(entry.enabled, true) === false) return false;
        resolved = resolveDecorationPlacement(entry);
        if (!resolved) return false;
        target = resolved.target;
        if (!target) return false;
 
        ensureHost(target);
 
        if (isPixelJsonDecoration(entry)) {
            return applyPixelJsonDecoration(entry, target, resolved.visible !== false);
        }
 
        src = normalizeSrc(entry.src);
        if (!src) return false;
 
        img = document.createElement('img');
        img.className = 'wiki-decoration';
        img.setAttribute(RENDERED_ATTR, '1');
        img.setAttribute('aria-hidden', 'true');
        img.setAttribute('alt', '');
        img.setAttribute('decoding', 'async');
        img.setAttribute('loading', 'eager');
        img.setAttribute('data-decoration-id', String(entry.id || ''));
        if (entry.placement) img.setAttribute('data-decoration-placement', String(entry.placement));
        if (entry.era) img.setAttribute('data-decoration-era', String(entry.era));
        if (entry.continent) img.setAttribute('data-decoration-continent', String(entry.continent));
        img.src = src;
 
        applyDecorationBaseStyle(img, entry, target);
        width = normalizeNumber(entry.width, NaN);
        height = normalizeNumber(entry.height, NaN);
        if (Number.isFinite(width) && width > 0) img.style.width = width + 'px';
        if (Number.isFinite(height) && height > 0) img.style.height = height + 'px';
        if (entry.objectFit) img.style.objectFit = String(entry.objectFit);
        setDecorationNodeVisibility(img, resolved.visible !== false);
 
        target.appendChild(img);
        return true;
    }
 
    function mainPageLayoutSignature() {
        var source = document.querySelector('.liberty-content-main');
        var well = ensureMainPageBodyWell();
        var sourceRect;
        var wellRect;
 
        if (!source || !well) return '';
        sourceRect = source.getBoundingClientRect();
        wellRect = well.getBoundingClientRect();
 
        return [
            Math.round((wellRect.left + normalizeNumber(well.clientLeft, 0)) - (sourceRect.left + normalizeNumber(source.clientLeft, 0))),
            Math.round((wellRect.top + normalizeNumber(well.clientTop, 0)) - (sourceRect.top + normalizeNumber(source.clientTop, 0))),
            Math.round(wellRect.width),
            Math.round(wellRect.height)
        ].join('|');
    }
 
    function isMainPageDecorationLayoutReady() {
        var portal = document.querySelector('.main-portal');
        var panel = portal && portal.querySelector('.main-body-panel');
        var topMount = portal && portal.querySelector('[data-component="category-nav"]');
 
        if (!portal || !panel || !ensureMainPageBodyWell()) return false;
        if (!document.body || !document.body.classList.contains('clbi-main-page')) return false;
        if (topMount && !topMount.querySelector('.portal-category-nav')) return false;
        return true;
    }
 
    function waitForMainPageDecorationLayout() {
        var started;
        var previous = '';
        var stableFrames = 0;
 
        if (currentPageKey() !== '대문') return Promise.resolve(true);
        started = Date.now();
 
        return new Promise(function (resolve) {
            function check() {
                var signature = mainPageLayoutSignature();
 
                if (signature && signature === previous) stableFrames += 1;
                else stableFrames = 0;
                previous = signature;
 
                if ((isMainPageDecorationLayoutReady() && stableFrames >= 2) || Date.now() - started >= 1200) {
                    resolve(true);
                    return;
                }
 
                if (window.requestAnimationFrame) window.requestAnimationFrame(check);
                else window.setTimeout(check, 16);
            }
 
            check();
        });
    }
 
    function rebaseLegacyMainPageDecorations() {
        var well;
 
        if (currentPageKey() !== '대문') return;
        well = ensureMainPageBodyWell();
        if (!well) return;
 
        document.querySelectorAll('[' + RENDERED_ATTR + '="1"][data-decoration-coordinate-source]').forEach(function (node) {
            var position = getDecorationLocalPosition({
                target: node.getAttribute('data-decoration-coordinate-source') || '.liberty-content-main',
                x: normalizeNumber(node.getAttribute('data-decoration-source-x'), 0),
                y: normalizeNumber(node.getAttribute('data-decoration-source-y'), 0)
            }, well);
 
            node.style.left = position.x + 'px';
            node.style.top = position.y + 'px';
            node.setAttribute('data-decoration-local-x', String(position.x));
            node.setAttribute('data-decoration-local-y', String(position.y));
        });
    }
 
    function scheduleMainPageDecorationRebase() {
        if (scheduledMainPageRebase) return;
        scheduledMainPageRebase = window.requestAnimationFrame ? window.requestAnimationFrame(function () {
            scheduledMainPageRebase = 0;
            rebaseLegacyMainPageDecorations();
        }) : window.setTimeout(function () {
            scheduledMainPageRebase = 0;
            rebaseLegacyMainPageDecorations();
        }, 0);
    }
 
    function bindMainPagePlacementRefresh() {
        var portal = document.querySelector('.main-portal');
        var nodes;
 
        if (currentPageKey() !== '대문' || !portal) {
            if (mainPagePlacementObserver) mainPagePlacementObserver.disconnect();
            if (mainPagePlacementMutationObserver) mainPagePlacementMutationObserver.disconnect();
            observedMainPagePortal = null;
            return;
        }
 
        if (observedMainPagePortal !== portal) {
            if (mainPagePlacementObserver) mainPagePlacementObserver.disconnect();
            if (mainPagePlacementMutationObserver) mainPagePlacementMutationObserver.disconnect();
            observedMainPagePortal = portal;
 
            if (typeof ResizeObserver === 'function') {
                mainPagePlacementObserver = new ResizeObserver(scheduleMainPageDecorationRebase);
                nodes = [
                    document.querySelector('.liberty-content-main'),
                    portal,
                    portal.querySelector('[data-component="category-nav"]'),
                    portal.querySelector('.main-body-panel'),
                    portal.querySelector('.main-body-well')
                ];
                nodes.forEach(function (node) {
                    if (node) mainPagePlacementObserver.observe(node);
                });
            }
 
            /*
            장식 좌표는 크기 변화에만 의존한다. portal subtree DOM 변경을 감시하면
            프레임 SVG와 선언문 애니메이션이 장식 재배치를 반복 호출한다.
            ResizeObserver와 명시적 렌더 시점만 사용한다.
            */
            mainPagePlacementMutationObserver = null;
        }
 
        scheduleMainPageDecorationRebase();
    }
 
    function renderForCurrentLayout(registry, token) {
        if (currentPageKey() !== '대문') {
            if (token === runtimeToken) render(registry);
            return Promise.resolve(registry);
        }
 
        return waitForMainPageDecorationLayout().then(function () {
            if (token === runtimeToken) render(registry);
            return registry;
        });
    }
 
    function render(registry) {
        var token = runtimeToken;
        lastRegistry = registry || { decorations: [] };
        lastRenderedPageKey = currentPageKey();
        bindNationsPlacementRefresh();
        clearRendered(document);
        decorationList(lastRegistry).forEach(function (entry) {
            if (token === runtimeToken && matchesPage(entry)) applyDecoration(entry);
        });
        bindMainPagePlacementRefresh();
    }
 
    function renderPrepared() {
        var registry = getPreparedRegistrySync() || lastRegistry;
        var token = runtimeToken;
        if (!registry) return false;
        renderForCurrentLayout(registry, token);
        return true;
    }
 
    function syncDecorationState() {
        if (lastRenderedPageKey === currentPageKey() && hasRenderedDecorations(document)) {
            updateDecorationVisibility(document);
            return true;
        }
        if (lastRegistry) {
            renderForCurrentLayout(lastRegistry, runtimeToken);
            return true;
        }
        return renderPrepared();
    }
 
    function scheduleRenderFromCache() {
        if (scheduledRender) return;
        scheduledRender = window.requestAnimationFrame ? window.requestAnimationFrame(function () {
            scheduledRender = 0;
            if (!syncDecorationState()) reload();
        }) : window.setTimeout(function () {
            scheduledRender = 0;
            if (!syncDecorationState()) reload();
        }, 0);
    }
 
    function scheduleDecorationVisibilityUpdate() {
        if (scheduledRender) return;
        scheduledRender = window.requestAnimationFrame ? window.requestAnimationFrame(function () {
            scheduledRender = 0;
            if (lastRenderedPageKey !== currentPageKey() || !hasRenderedDecorations(document)) {
                if (!syncDecorationState()) reload();
                return;
            }
            updateDecorationVisibility(document);
        }) : window.setTimeout(function () {
            scheduledRender = 0;
            if (lastRenderedPageKey !== currentPageKey() || !hasRenderedDecorations(document)) {
                if (!syncDecorationState()) reload();
                return;
            }
            updateDecorationVisibility(document);
        }, 0);
    }
 
    function bindNationsPlacementRefresh() {
        var stack = document.querySelector('.clbi-nations-panel-stack');
 
        if (!stack || observedNationsStack === stack) return;
        observedNationsStack = stack;
 
        if (nationsPlacementObserver) {
            nationsPlacementObserver.disconnect();
        }
 
        if (typeof MutationObserver === 'function') {
            nationsPlacementObserver = new MutationObserver(scheduleDecorationVisibilityUpdate);
            nationsPlacementObserver.observe(stack, {
                subtree: true,
                attributes: true,
                attributeFilter: ['class', 'hidden', 'aria-selected', 'data-current-era', 'data-nations-current-era', 'data-era-year']
            });
        }
    }
 
    function getPreparedRegistrySync() {
        var registry = null;
        var url;
        try {
            if (window.EntryStore && typeof window.EntryStore.getJsonSync === 'function') {
                registry = window.EntryStore.getJsonSync(REGISTRY_TITLE);
                if (!registry && mw && mw.util && typeof mw.util.getUrl === 'function') {
                    url = mw.util.getUrl(REGISTRY_TITLE, { action: 'raw', ctype: 'application/json' });
                    registry = window.EntryStore.getJsonSync(url);
                }
            }
        } catch (err) {}
        return registry && typeof registry === 'object' ? registry : null;
    }
 
    function fetchRegistry() {
        var url;
        var prepared = getPreparedRegistrySync();
        if (prepared) return Promise.resolve(prepared);
        if (!mw || !mw.util || typeof fetch !== 'function') return Promise.resolve({ decorations: [] });
        url = mw.util.getUrl(REGISTRY_TITLE, {
            action: 'raw',
            ctype: 'application/json'
        });
        return fetch(url, { credentials: 'same-origin', cache: 'force-cache' })
            .then(function (response) {
                if (!response.ok) throw new Error('HTTP ' + response.status);
                return response.text();
            })
            .then(function (text) {
                if (!text || !text.trim()) return { decorations: [] };
                return JSON.parse(text);
            })
            .catch(function () {
                return { decorations: [] };
            });
    }
 
    function reload() {
        var token;
        runtimeToken += 1;
        token = runtimeToken;
        return fetchRegistry().then(function (registry) {
            return preloadPixelAssetsForRegistry(registry).then(function () {
                return renderForCurrentLayout(registry, token);
            });
        });
    }
 
    document.addEventListener('click', function (event) {
        var target = event.target && event.target.closest ? event.target.closest('.clbi-nations-tabpanel-tab[data-continent], [data-nations-era-move]') : null;
        if (target) window.setTimeout(scheduleDecorationVisibilityUpdate, 0);
    }, true);
 
    function decorationDiagnostics() {
        return {
            build: '20260713-main-body-well-coordinate-003',
            hasRegistry: !!lastRegistry,
            entries: decorationList(lastRegistry).length,
            rendered: document.querySelectorAll('[' + RENDERED_ATTR + '="1"]').length,
            preparedRegistry: !!getPreparedRegistrySync(),
            pixelAssets: Object.keys(pixelAssetCache || {}).length,
            pixelCanvases: Object.keys(pixelCanvasCache || {}).length,
            visibilityOnlySync: true,
            mainPageCoordinateSurface: MAIN_PAGE_TARGET,
            mainPagePlacementObserved: !!observedMainPagePortal,
            lastRenderedPage: lastRenderedPageKey,
            visibleRendered: document.querySelectorAll('[' + RENDERED_ATTR + '="1"][data-decoration-visible="1"]').length,
            scheduled: !!scheduledRender
        };
    }
 
    window.Decorations = window.Decorations || {};
    window.Decorations.reload = reload;
    window.Decorations.render = render;
    window.Decorations.renderPrepared = renderPrepared;
    window.Decorations.sync = syncDecorationState;
    window.Decorations.updateVisibility = updateDecorationVisibility;
    window.Decorations.diagnostics = decorationDiagnostics;
    window.Decorations.clear = clearRendered;
    window.Decorations.apply = applyDecoration;
    window.Decorations.pageKey = currentPageKey;
    window.Decorations.loadPixelAsset = fetchPixelAsset;
    window.Decorations.preparePixelCanvas = preparePixelCanvas;
    window.Decorations.getPreparedPixelCanvasSync = getPreparedPixelCanvasSync;
    window.Decorations.drawPixelAssetToCanvas = drawPixelAssetToCanvas;
 
    window.CLBI_DECORATIONS = window.CLBI_DECORATIONS || {};
    window.CLBI_DECORATIONS.reload = reload;
    window.CLBI_DECORATIONS.render = render;
    window.CLBI_DECORATIONS.renderPrepared = renderPrepared;
    window.CLBI_DECORATIONS.sync = syncDecorationState;
    window.CLBI_DECORATIONS.updateVisibility = updateDecorationVisibility;
    window.CLBI_DECORATIONS.diagnostics = decorationDiagnostics;
    window.CLBI_DECORATIONS.clear = clearRendered;
    window.CLBI_DECORATIONS.apply = applyDecoration;
    window.CLBI_DECORATIONS.pageKey = currentPageKey;
    window.CLBI_DECORATIONS.loadPixelAsset = fetchPixelAsset;
    window.CLBI_DECORATIONS.preparePixelCanvas = preparePixelCanvas;
    window.CLBI_DECORATIONS.getPreparedPixelCanvasSync = getPreparedPixelCanvasSync;
    window.CLBI_DECORATIONS.drawPixelAssetToCanvas = drawPixelAssetToCanvas;
 
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', reload);
    } else {
        reload();
    }
 
    if (mw && mw.hook) {
        mw.hook('wikipage.content').add(function () {
            reload();
        });
    }
})(mediaWiki);
 
/* =========================================
  Unified Shortcuts loader
  ========================================= */
(function () {
    'use strict';
 
    if (!window.mw || !mw.loader) return;
    loadClbiRawScript('MediaWiki:Nation_List_Manager.js');
    loadClbiRawScript('MediaWiki:History_Event_Manager.js');
    loadClbiRawScript('MediaWiki:Shortcuts.js');
})();
 
/* =========================================
  Main page manifesto bitmap renderer
  Integrated build: no extra raw-script page, no image/data-URL decoding.
  New shared systems do not use the legacy CLBI prefix.
  ========================================= */
(function (window, document, mw) {
    'use strict';
 
    /*
    Retired compatibility block
    -----------------------------------------
    선언문은 실제 HTML과 ManifestoIntro의 실선 요소만 사용한다.
    이 구식 렌더러는 제목·본문과 완성형 구분선을 canvas에 한 번에 그려
    새 애니메이션의 선 뒤에 트랙이 나타날 수 있었다.
 
    기존 Common.js를 장기 캐시한 뒤 새 파일로 넘어오는 경우를 위해
    남아 있는 canvas와 상태만 제거하고 즉시 종료한다. 새 공개 이름에는
    프로젝트 접두사를 사용하지 않는 규칙을 유지한다.
    */
    function removeRetiredBitmap() {
        Array.prototype.forEach.call(
            document.querySelectorAll('.main-portal .main-manifesto-bitmap'),
            function (canvas) {
                if (canvas.parentNode) canvas.parentNode.removeChild(canvas);
            }
        );
 
        Array.prototype.forEach.call(
            document.querySelectorAll('.main-portal .main-manifesto-inner'),
            function (inner) {
                inner.classList.remove('is-bitmap-ready');
                [
                    'data-bitmap-width',
                    'data-bitmap-optical-shift-x',
                    'data-bitmap-state',
                    'data-bitmap-error'
                ].forEach(function (name) {
                    inner.removeAttribute(name);
                });
            }
        );
    }
 
    removeRetiredBitmap();
 
    try {
        if (mw && mw.hook) {
            mw.hook('wikipage.content').add(removeRetiredBitmap);
        }
    } catch (ignoreRetiredBitmapHook) {}
 
    window.MainPageBitmap = {
        version:'retired-20260713-divider-no-track-001',
        recalculate:removeRetiredBitmap,
        status:function () {
            return {
                integrated:false,
                state:'retired',
                canvas:!!document.querySelector('.main-portal .main-manifesto-bitmap')
            };
        }
    };
 
    return;
 
    var VERSION = '20260712-bitmap18-inline-002';
    var SELECTOR = '.main-portal .main-manifesto-inner';
    var CELL_W = 24;
    var CELL_H = 24;
    var GLYPHS = {"진":[19,0,0,0,0,0,12288,24576,24576,25472,25584,25056,25072,25568,26160,26136,24576,9088,8960,768,256,32512,15872,0,0],"창":[19,0,0,0,0,0,6144,12512,12480,12800,13280,78328,258272,12768,14128,13848,4360,3840,7040,12672,4480,8064,3840,0,0],"바":[19,0,0,0,0,0,6144,12288,12288,12672,12672,14080,13056,13064,258456,127472,12784,12504,12408,12312,12288,12288,4096,0,0],"다":[19,0,0,0,0,0,6144,12288,12288,12288,13056,12792,12400,12320,258096,128528,14328,13048,12304,12288,12288,12288,4096,0,0],"는":[19,0,0,0,0,0,0,96,192,192,14528,16064,960,0,130048,118780,56,448,448,128,128,16256,7936,0,0],"왕":[19,0,0,0,0,0,12288,28768,25568,25456,25392,25392,254944,24960,16064,10236,12344,7680,14080,12672,12672,16128,7936,0,0],"과":[19,0,0,0,0,0,12288,28672,24576,26560,26352,26112,26112,26208,255680,254912,29248,32736,25084,8192,8192,8192,8192,0,0],"노":[19,0,0,0,0,0,0,0,0,96,192,192,4288,15552,16320,7040,7168,3072,50688,131064,124,0,0,0,0],"예":[19,0,0,0,0,0,24576,60416,22528,22528,22544,24048,24504,23320,23320,24504,23024,22528,22528,18432,16384,16384,24576,0,0],"를":[19,0,0,0,0,0,7168,16320,6144,8128,448,15552,1984,122880,262140,16636,8128,8128,3840,8064,1792,960,65408,4096,0],"같":[19,0,0,0,0,0,6144,12288,12288,13248,13304,110976,127168,12384,12344,4104,3584,0,8064,1920,256,14720,8064,0,0],"은":[19,0,0,0,0,0,384,3968,6528,6336,6272,3968,1792,32768,130944,115708,16,448,448,128,128,16256,7936,0,0],"깊":[19,0,0,0,0,0,12288,24576,24576,26496,25592,25472,25024,24800,24624,8216,12288,16256,4864,15872,7680,31232,32640,256,0],"이":[19,0,0,0,0,0,12288,24576,24576,24576,24592,25072,25584,25368,25368,25496,25072,24640,24576,24576,24576,8192,8192,0,0],"로":[19,0,0,0,0,0,0,0,15360,16320,6272,7168,8128,384,14528,16320,7040,3072,50688,131064,124,0,0,0,0],"삼":[19,0,0,0,0,0,6144,12288,12352,12736,12480,78064,258272,13296,14136,13324,4096,16256,16256,4224,4480,8064,8064,0,0],"켰":[19,0,0,0,0,0,12288,24576,26112,26600,29560,32656,25072,31992,26720,8224,8216,13056,15104,5056,15232,28544,58992,0,0],"고":[19,0,0,0,0,0,0,0,0,7680,16352,12416,12288,12288,12544,13056,6912,4864,49920,131064,124,0,0,0,0],",":[8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,12,12,8,0,0,0],"겨":[19,0,0,0,0,0,12288,24576,24576,24576,25344,26616,32560,31104,24768,31840,31792,24600,24584,24576,24576,24576,8192,0,0],"울":[19,0,0,0,0,0,1792,8064,6528,6272,7552,3840,114688,262140,18428,1536,16320,8128,3840,8064,1920,896,65280,0,0],"사":[19,0,0,0,0,0,6144,12288,12288,12352,12480,12480,12480,12400,258272,127920,14104,13828,13312,12288,12288,12288,4096,0,0],"람":[19,0,0,0,0,0,6144,12288,12288,13296,13240,78208,258552,12304,14224,13296,4096,15744,16256,4288,4480,8064,8064,0,0],"짐":[19,0,0,0,0,0,12288,24576,24576,25472,25584,24992,25072,26592,26160,9756,0,32512,32640,12672,12672,16128,16128,0,0],"승":[19,0,0,0,0,0,512,3584,1536,1792,8064,29056,24800,32768,130816,115708,272,3840,7040,4224,6272,8064,3840,0,0],"의":[19,0,0,0,0,0,28672,57344,24608,25536,26592,26160,26160,26464,25568,24576,24576,32704,25596,24576,24576,24576,8192,0,0],"살":[19,0,0,0,0,0,6144,12288,12352,12736,12480,110832,127456,13232,13848,5132,8064,8064,3840,8064,1792,896,65024,0,0],"을":[19,0,0,0,0,0,1792,8064,6528,6272,7552,3840,32768,130944,115708,0,16320,8128,3840,8064,1920,896,65280,0,0],"빛":[19,0,0,0,0,0,12288,24576,25344,25344,26376,25496,25592,25584,25552,25088,7168,12288,32640,6400,7680,32256,25472,0,0],"으":[19,0,0,0,0,0,0,0,128,3968,8064,4544,4288,6336,7616,3968,0,0,57344,131068,56,0,0,0,0],"얼":[19,0,0,0,0,0,12288,24576,24592,24816,25008,32536,31512,25016,25072,8192,16256,16256,7680,16128,3584,1792,130560,0,0],"렸":[19,0,0,0,0,0,12288,24576,24576,25584,32568,27008,31224,31792,26544,9200,8192,13056,15104,4928,15232,28544,58976,0,0],".":[8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,12,12,0,0,0,0],"그":[19,0,0,0,0,0,0,0,0,7168,16352,12672,12288,12288,12288,12288,6144,4096,57344,131068,56,0,0,0,0],"들":[19,0,0,0,0,0,6144,16320,896,384,14528,16320,960,130048,118780,120,16320,8128,3840,8064,1920,896,65280,0,0],"돌":[19,0,0,0,0,0,6144,16320,896,384,14528,16320,8128,130048,253948,16504,16320,8128,3840,8064,1920,896,65280,0,0],"벽":[19,0,0,0,0,0,12288,24576,24832,25344,32520,31512,25560,32632,25584,9104,8192,31744,32640,8192,8192,8192,8192,0,0],"세":[19,0,0,0,0,0,24576,60416,22528,22528,22720,22720,22752,24432,22752,22960,23320,23300,22528,18432,16384,16384,24576,0,0],"우":[19,0,0,0,0,0,0,384,7936,6528,12480,6336,7552,3968,0,131008,116732,1552,1536,1536,1536,1536,512,0,0],"땅":[19,0,0,0,0,0,12288,28672,24576,28560,9200,74160,254128,30936,16376,12280,12544,7936,13184,12672,12672,8064,3840,0,0],"찢":[19,0,0,0,0,0,12288,24576,24704,26616,28656,26560,25456,28656,28056,26848,8192,32512,16128,7680,15872,25344,16768,0,0],"어":[19,0,0,0,0,0,12288,24576,24576,24576,24592,24816,25520,32536,27416,25496,25072,24640,24576,24576,24576,8192,8192,0,0],"길":[19,0,0,0,0,0,12288,24576,24576,26496,25592,25472,24768,24672,24624,8216,16256,16128,7680,16128,3584,1792,130560,0,0],"냈":[19,0,0,0,0,0,8192,58368,19456,27672,27704,31792,31792,32560,28656,27120,8704,13824,14080,13248,15232,28544,50272,0,0],"며":[19,0,0,0,0,0,12288,24576,24576,24576,25472,26600,32536,25368,25400,32560,25584,25056,24576,24576,24576,24576,8192,0,0],"쇠":[19,0,0,0,0,0,28672,57344,24704,24960,24960,25056,25536,26208,27888,24960,24960,32704,25596,24576,24576,24576,8192,0,0],"에":[19,0,0,0,0,0,24576,60416,22528,22528,22544,23024,23480,24344,24344,22968,23024,22528,22528,18432,16384,16384,24576,0,0],"제":[19,0,0,0,0,0,24576,60416,22528,22528,23488,23032,22976,24512,24184,23024,23344,23320,23052,18432,16384,16384,24576,0,0],"름":[19,0,0,0,0,0,6144,16320,6272,8128,960,14528,16320,384,130560,116732,56,15872,16320,4288,4544,7552,8064,0,0],"새":[19,0,0,0,0,0,24576,60416,23552,19456,27840,27840,31968,31856,23776,23984,20248,20228,16384,16384,16384,16384,24576,0,0],"겼":[19,0,0,0,0,0,12288,24576,24576,26496,30712,32640,25024,31968,26672,8216,8200,15104,15104,6976,15232,28608,58992,0,0],"감":[19,0,0,0,0,0,6144,12288,12288,13184,13304,78208,258240,12384,12336,4120,4096,16256,16320,4224,4480,8064,8064,0,0],"옥":[19,0,0,0,0,0,1792,7936,6528,6272,6528,8064,3584,1536,130816,116732,56,16128,15296,4096,4096,4096,4096,0,0],"되":[19,0,0,0,0,0,28672,57344,25088,26608,25072,24672,25632,26416,26608,25456,24960,32704,25596,24576,24576,24576,8192,0,0],"군":[19,0,0,0,0,0,0,7680,16352,12288,12288,12288,6144,126976,262140,18172,1536,1728,1472,192,192,16256,8064,0,0],"대":[19,0,0,0,0,0,24576,60416,23552,19456,28032,28144,31856,31776,23600,24344,20440,19960,16400,16384,16384,16384,24576,0,0],"나":[19,0,0,0,0,0,6144,12288,12288,12288,12296,12312,12336,12304,259600,128784,14256,12528,12320,12288,12288,12288,4096,0,0],"르":[19,0,0,0,0,0,0,0,6144,16320,6336,7168,8128,448,12480,16320,3968,0,57344,131068,56,0,0,0,0],"오":[19,0,0,0,0,0,0,0,256,7936,15232,12672,12416,12672,8064,7936,3072,1024,49664,131064,124,0,0,0,0],"래":[19,0,0,0,0,0,24576,60416,23552,19456,28144,27064,32128,32248,23664,23568,20240,20464,16880,16384,16384,16384,24576,0,0],"된":[19,0,0,0,0,0,28672,57344,26368,25584,24800,25696,28656,26608,29440,32736,25080,24832,25344,768,768,65280,15872,0,0],"원":[19,0,0,0,0,0,28672,57440,25536,26464,26160,26160,29664,32640,26592,26620,25360,25024,25536,768,768,65280,15872,0,0],"한":[19,0,0,0,0,0,6144,28704,12512,12800,14328,12784,258528,13088,12592,12784,12512,12416,4544,384,128,16256,7936,0,0],"함":[19,0,0,0,0,0,6144,12512,12480,12800,14328,78032,258528,13104,12720,12784,4192,15744,16256,4288,4480,8064,8064,0,0],"께":[19,0,0,0,0,0,24576,55296,55296,55296,55488,57336,57280,57184,57184,55600,55704,55500,55392,49152,49152,16384,16384,0,0],"음":[19,0,0,0,0,0,1920,8064,6528,6336,6336,3968,1792,32768,131040,16892,0,16128,16320,4288,4544,7552,8064,0,0],"손":[19,0,0,0,0,0,512,1536,1536,1920,7936,14720,26304,1584,130560,249852,120,448,448,128,128,16256,7936,0,0],"넘":[19,0,0,0,0,0,12288,24576,24576,24600,31792,31792,24624,28208,26608,8416,0,32512,32640,12672,12672,16256,15616,0,0],"갔":[19,0,0,0,0,0,6144,12288,12288,13184,13304,78208,258240,12384,12336,12312,4352,15104,6912,6528,7616,30656,25136,0,0],"\n":[8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"줄":[19,0,0,0,0,0,6144,16320,3520,3840,15296,12480,41056,130976,116732,1536,16320,8128,3840,8064,1920,896,65280,0,0],"처":[19,0,0,0,0,0,12288,24576,24800,25024,25344,26592,25072,32448,27616,25392,25360,24840,24832,24960,24960,8320,8192,0,0],"부":[19,0,0,0,0,0,6144,12288,28768,14400,15552,13248,8128,7872,0,131008,116732,1552,1536,1536,1536,1536,512,0,0],"터":[19,0,0,0,0,0,12288,24576,24576,25056,24768,25344,25584,31984,31840,25648,28568,26360,24624,24576,24576,8192,8192,0,0],"목":[19,0,0,0,0,0,14336,32512,15328,6336,3264,16064,7296,3072,130816,116732,56,16128,15296,4096,4096,4096,4096,0,0],"둘":[19,0,0,0,0,0,6144,16320,896,384,14528,16320,960,130944,116732,1592,16320,8128,3840,8064,1920,896,65280,0,0],"레":[19,0,0,0,0,0,24576,60416,22528,22528,23024,22968,22912,24568,22640,22544,23312,23536,23024,18432,16384,16384,24576,0,0],"있":[19,0,0,0,0,0,12288,24576,24576,24816,25072,25400,25368,25368,25072,8416,8192,15104,15104,7104,14720,28608,26224,0,0],"었":[19,0,0,0,0,0,12288,24576,24576,24816,25072,32568,32536,25496,25072,8416,8192,15104,15104,7104,14720,28608,26224,0,0],"끝":[19,0,0,0,0,0,0,14720,16368,13152,12672,12672,4480,130560,116732,56,3840,3584,8128,1920,384,16320,4032,0,0],"속":[19,0,0,0,0,0,512,3584,1536,1792,7936,12672,26336,1568,130560,116732,56,16128,15296,4096,4096,4096,4096,0,0],"뿌":[19,0,0,0,0,0,4096,30720,14080,15904,16352,13280,16320,14208,4608,130944,126972,1552,1536,1536,1536,1536,512,0,0],"리":[19,0,0,0,0,0,12288,24576,24576,24576,25568,25528,24960,25040,24688,25648,26160,26608,25056,24576,24576,8192,8192,0,0],"와":[19,0,0,0,0,0,12288,28672,24608,25568,25456,26160,26416,25584,254432,254336,28864,32736,25084,8192,8192,8192,8192,0,0],"빨":[19,0,0,0,0,0,12288,28672,26112,26176,26304,255944,255992,10200,10224,1728,16256,16256,7936,7936,1792,896,65024,0,0],"굶":[19,0,0,0,0,0,0,16128,13248,12288,12288,6144,118784,262140,18428,1536,14080,16368,13792,14272,14272,16352,16352,0,0],"주":[19,0,0,0,0,0,0,14336,16320,3264,1792,7936,12736,24672,32,131008,116732,1552,1536,1536,1536,1536,512,0,0],"림":[19,0,0,0,0,0,12288,24576,24576,25584,25400,25472,25072,24624,26544,9200,8192,15616,32640,12672,12672,16256,16128,0,0],"매":[19,0,0,0,0,0,24576,60416,23552,19456,28544,28644,32156,32024,23832,23992,19952,19504,16384,16384,16384,16384,24576,0,0],"였":[19,0,0,0,0,0,12288,24576,24576,24816,32752,32568,25368,32664,25072,8416,8192,15104,15104,7104,14720,28608,26224,0,0],"른":[19,0,0,0,0,0,4096,16320,6336,7744,4032,14528,16320,896,126976,253948,120,64,448,128,128,16256,7936,0,0],"아":[19,0,0,0,0,0,6144,12288,12288,12288,12304,12528,12720,13080,258840,127896,12784,12352,12288,12288,12288,12288,4096,0,0],"직":[19,0,0,0,0,0,12288,24576,24576,25472,25584,24992,25072,25568,26160,9752,0,31744,32640,8192,8192,12288,12288,0,0],"태":[19,0,0,0,0,0,24576,60416,23552,19680,27840,28032,32240,31856,23600,24336,20440,20472,16432,16384,16384,16384,24576,0,0],"지":[19,0,0,0,0,0,12288,24576,24576,24576,26496,25584,24992,24768,24816,25568,26160,27672,25612,24576,24576,24576,8192,0,0],"않":[19,0,0,0,0,0,6144,12288,12304,12528,12784,111384,258840,13208,12784,4160,7168,6240,32352,15456,13408,14176,8160,0,0],"자":[19,0,0,0,0,0,6144,12288,12288,12288,13184,13304,12720,12480,258296,127984,14128,13848,13324,12288,12288,12288,4096,0,0],"졌":[19,0,0,0,0,0,12288,24576,24576,25472,32752,31136,32240,32736,26160,9756,8704,13056,15104,4928,15232,28544,50784,0,0],"앞":[19,0,0,0,0,0,6144,12288,12304,12528,12784,111384,258840,13208,12784,4160,6144,8128,2432,7936,2816,15616,16320,128,0],"갈":[19,0,0,0,0,0,6144,12288,12288,13248,13304,127360,127168,12384,12344,4104,16256,8064,3840,8064,1792,896,65280,0,0],"때":[19,0,0,0,0,0,24576,52224,55296,55296,57096,56312,63920,63632,63704,56536,57336,57336,49216,49152,49152,16384,16384,0,0],"마":[19,0,0,0,0,0,6144,12288,12288,12288,13184,13284,13084,13080,258840,127792,12784,12464,12288,12288,12288,12288,4096,0,0],"듭":[19,0,0,0,0,0,6144,16320,1984,384,12480,16064,3008,32768,131008,115708,14336,12352,12480,14720,16256,8064,7808,0,0],"파":[19,0,0,0,0,0,6144,12288,12288,12288,13248,12792,12688,13296,258528,127392,16352,12412,12288,12288,12288,12288,4096,0,0],"각":[19,0,0,0,0,0,6144,12288,12288,13184,13304,12672,258240,12384,12336,4120,4096,16128,13248,12288,4096,4096,4096,0,0],"쥔":[19,0,0,0,0,0,28672,57856,26608,25584,25024,26592,28208,27664,28544,28668,25360,24960,25536,768,768,65280,15872,0,0],"당":[19,0,0,0,0,0,6144,12288,12288,13248,12536,77920,258096,15888,14328,12920,4352,7936,7040,12672,4480,8064,3840,0,0],"기":[19,0,0,0,0,0,12288,24576,24576,24576,25344,26616,25392,24960,24768,24672,24624,24600,24584,24576,24576,24576,8192,0,0],"면":[19,0,0,0,0,0,12288,24576,24576,26496,26604,32536,25368,32560,31728,25072,24576,25344,8960,768,768,32512,15872,0,0],"풀":[19,0,0,0,0,0,12288,16352,7296,8064,3328,32704,41440,131008,116732,1536,16320,8128,3840,8064,1920,896,65280,0,0],"려":[19,0,0,0,0,0,12288,24576,24576,24576,25568,32696,31104,25040,31856,27696,26160,26608,25056,24576,24576,8192,8192,0,0],"날":[19,0,0,0,0,0,6144,12288,12288,12312,12344,110640,128560,14256,13296,4192,8064,8064,3840,8064,1792,896,65024,0,0],"것":[19,0,0,0,0,0,12288,24576,24576,26496,25592,24960,32704,26848,24624,24600,11272,3072,1792,3584,15104,29056,24800,0,0],"라":[19,0,0,0,0,0,6144,12288,12288,12288,13280,12728,12672,12792,258168,127504,13840,14320,12784,12288,12288,12288,4096,0,0],"여":[19,0,0,0,0,0,12288,24576,24576,24576,24592,24816,32688,25368,25368,32664,25072,24640,24576,24576,24576,8192,8192,0,0],"므":[19,0,0,0,0,0,0,0,4096,31744,32736,6624,3264,1728,16064,7360,0,0,57344,131068,56,0,0,0,0],"번":[19,0,0,0,0,0,12288,24576,24576,25344,26376,26392,32728,25464,25584,25552,24576,25344,8960,768,768,32512,15872,0,0],"도":[19,0,0,0,0,0,0,0,0,15360,4064,960,384,14528,16064,7136,7360,3072,50688,131064,124,0,0,0,0],"느":[19,0,0,0,0,0,0,0,0,32,192,192,192,14528,16064,7104,0,0,57344,131068,56,0,0,0,0],"슨":[19,0,0,0,0,0,512,1536,1536,1920,7936,14720,24768,48,130048,118780,56,448,448,128,128,16256,7936,0,0],"해":[19,0,0,0,0,0,24576,60416,23552,19680,27968,28664,32240,32224,23984,23984,19952,19568,16384,16384,16384,16384,24576,0,0],"았":[19,0,0,0,0,0,6144,12288,12288,12528,12784,78616,258840,13208,12784,12512,4352,15104,6912,6528,7616,30656,25136,0,0],"침":[19,0,0,0,0,0,12288,24768,25024,25088,26592,25584,24800,25568,26416,9232,8,15616,32640,12672,12672,16256,16128,0,0],"내":[19,0,0,0,0,0,24576,58368,19456,19456,27656,27672,31792,31792,31760,24368,20464,19952,16384,16384,24576,24576,8192,0,0],"멎":[19,0,0,0,0,0,12288,24576,24576,26496,25576,32536,31512,25392,25072,8224,8192,32640,6912,3584,15872,25344,16768,0,0],"서":[19,0,0,0,0,0,12288,24576,24576,24640,24768,25024,24768,32496,24800,25520,26392,26124,25600,24576,24576,8192,8192,0,0],"긴":[19,0,0,0,0,0,12288,24576,24576,26368,25592,25520,25024,24768,24688,24632,24584,25472,8960,768,768,32512,15872,0,0],"붙":[19,0,0,0,0,0,6144,12288,14432,16064,13248,7872,38912,130816,116732,1552,3840,3584,8064,1920,384,15808,4032,0,0],"잡":[19,0,0,0,0,0,6144,12288,12288,13184,13304,111040,258288,13280,13872,5660,4096,12352,12416,14720,16256,8064,7296,0,0],"피":[19,0,0,0,0,0,12288,24576,24576,24576,26496,25592,25392,25568,25440,24992,28640,26744,24576,24576,24576,24576,8192,0,0],"가":[19,0,0,0,0,0,6144,12288,12288,12288,13056,13304,12728,12736,127168,258144,12336,12312,12300,12288,12288,12288,4096,0,0],"굴":[19,0,0,0,0,0,0,16128,13248,12288,12288,6144,126976,262140,18172,1536,16320,8128,3840,8064,1920,896,65280,0,0],"보":[19,0,0,0,0,0,0,0,6144,12288,28768,14528,16064,13248,16320,7360,3072,1024,50688,131064,124,0,0,0,0],"하":[19,0,0,0,0,0,6144,12288,12320,12512,12800,14332,12792,12512,259040,127792,12720,12528,12288,12288,12288,12288,4096,0,0],"입":[19,0,0,0,0,0,12288,24576,24576,24816,25584,25368,25368,25496,25072,8256,4096,28800,24960,14720,16128,16128,15616,0,0],"말":[19,0,0,0,0,0,6144,12288,12288,13184,13308,111384,127768,13240,12784,4096,8064,8064,3840,8064,1792,896,65024,0,0],"했":[19,0,0,0,0,0,24576,58368,23776,19776,28664,27888,32224,23984,19888,18672,96,13824,15872,13184,15232,28544,50272,0,0],"조":[19,0,0,0,0,0,0,0,0,15360,8128,3072,1792,16128,28864,25184,1568,1536,50688,131064,124,0,0,0,0],"올":[19,0,0,0,0,0,1792,8064,6528,6528,8064,3840,1536,128768,253948,16504,16320,8128,3840,8064,1920,896,65280,0,0],"수":[19,0,0,0,0,0,0,1536,3072,1792,1792,6912,29056,24800,32,131008,116732,1552,1536,1536,1536,1536,512,0,0],"록":[19,0,0,0,0,0,6144,16320,6272,8128,960,14528,16320,3968,128512,253948,120,15872,16320,4096,4096,4096,6144,0,0],"열":[19,0,0,0,0,0,12288,24576,24592,24816,32688,31512,25368,32696,25072,8192,16256,16256,7680,16128,3584,1792,130560,0,0],"단":[19,0,0,0,0,0,6144,28672,12288,13184,12792,12400,258096,13872,14232,14328,12336,12672,4480,384,384,16256,7936,0,0],"질":[19,0,0,0,0,0,12288,24576,24576,26496,25584,24992,25072,26464,26160,9240,16128,16128,7680,16128,3584,1792,130560,0,0],"히":[19,0,0,0,0,0,12288,24576,24576,25024,26112,26616,25584,25024,25440,25392,25392,25056,24576,24576,24576,8192,8192,0,0],"운":[19,0,0,0,0,0,384,3968,6528,6336,6272,3968,1792,32768,131040,17916,3072,1984,1472,128,192,16256,7936,0,0],"데":[19,0,0,0,0,0,24576,60416,22528,22528,22912,23024,22640,24352,22576,23320,23512,23032,22544,18432,16384,16384,24576,0,0],"끌":[19,0,0,0,0,0,0,14720,16368,13152,12672,12672,4480,130560,116732,56,16320,8128,3840,8064,1920,896,65280,0,0],"린":[19,0,0,0,0,0,12288,24576,24576,25568,25464,24960,25592,24624,26416,26608,24672,8320,9088,256,256,32512,15872,0,0],"게":[19,0,0,0,0,0,24576,60416,22528,22528,23424,23544,22960,24000,24512,22624,22576,22552,22536,18432,16384,16384,24576,0,0],"누":[19,0,0,0,0,0,0,96,192,192,192,15552,16320,960,0,131008,116732,1552,1536,1536,1536,1536,512,0,0],"인":[19,0,0,0,0,0,12288,24576,24576,24624,25072,25400,25368,25368,25072,24800,24576,9088,8960,256,256,32512,15872,0,0],"쳐":[19,0,0,0,0,0,12288,24576,24800,25024,25344,26592,32752,31936,25568,32560,25360,24840,24832,24960,24960,8320,8192,0,0],"문":[19,0,0,0,0,0,12288,15872,15328,6336,3264,7872,7360,32768,131040,17916,3072,1984,1472,128,192,16256,7936,0,0],"몸":[19,0,0,0,0,0,14336,32512,15328,6336,3264,16064,7296,3072,130816,116732,56,16128,16320,4288,4544,7552,8064,0,0],"식":[19,0,0,0,0,0,12288,24576,24768,24960,25024,24816,24800,25568,26160,9244,0,31744,32640,8192,8192,12288,12288,0,0],"억":[19,0,0,0,0,0,12288,24576,24576,24816,25072,32536,32536,25368,25072,8416,0,31744,32640,12288,12288,12288,12288,0,0],"전":[19,0,0,0,0,0,12288,24576,24576,25472,25592,24992,31984,25568,26160,26136,24576,9088,8960,768,256,32512,15872,0,0],"품":[19,0,0,0,0,0,12288,16352,7360,8064,7040,16128,26592,127040,253948,18040,1536,16128,16320,4288,4544,7552,8064,0,0],"발":[19,0,0,0,0,0,6144,12288,12672,13056,14092,111512,127992,13176,13272,4096,8064,8064,3840,8064,1792,896,65024,0,0],"머":[19,0,0,0,0,0,12288,24576,24576,24576,25472,25576,25368,32536,27448,25392,25584,25056,24576,24576,24576,24576,8192,0,0],"두":[19,0,0,0,0,0,0,14336,8128,960,384,12480,16064,5056,192,131008,116732,1552,1536,1536,1536,1536,512,0,0],"닐":[19,0,0,0,0,0,12288,24576,24576,24600,24624,24624,27696,28464,26608,8288,16256,16256,7680,16128,3584,1792,130560,0,0],"격":[19,0,0,0,0,0,12288,24576,24576,26496,26616,32640,25024,31968,26672,8216,8200,32256,26496,8192,8192,8192,8192,0,0],"없":[19,0,0,0,0,0,12288,24576,24592,24816,25072,32536,31512,25496,25072,8256,8192,13824,15936,4928,15296,28608,51008,0,0],"니":[19,0,0,0,0,0,12288,24576,24576,24576,24584,24624,24624,24624,25648,28208,26544,25328,24576,24576,24576,8192,8192,0,0],"산":[19,0,0,0,0,0,6144,28672,12352,12480,12480,12496,258272,13280,14128,13852,12288,12672,4480,384,384,16256,7936,0,0],"복":[19,0,0,0,0,0,14336,12288,28736,15552,14272,16320,7808,3072,130560,249852,120,15872,16320,4096,4096,4096,6144,0,0],"종":[19,0,0,0,0,0,6144,16320,3520,1792,7936,12736,26208,1568,130816,116732,280,3840,7040,4224,6272,8064,3840,0,0],"죽":[19,0,0,0,0,0,6144,16320,3520,1792,7936,12736,24672,122912,262140,18172,1536,16128,15296,4096,4096,4096,4096,0,0],"망":[19,0,0,0,0,0,6144,12288,12288,13248,13308,78620,258840,13112,12784,12336,4352,7936,7040,12672,4480,8064,3840,0,0],"베":[19,0,0,0,0,0,24576,60416,22528,22912,22912,24448,24448,24456,24536,23024,23024,22776,22648,18456,16384,16384,24576,0,0],"막":[19,0,0,0,0,0,6144,12288,12288,13248,13308,13084,258840,13080,12784,12464,4096,15872,16320,12288,4096,4096,4096,0,0],"무":[19,0,0,0,0,0,0,30720,32608,15296,6336,3520,16320,15488,0,131008,116732,1552,1536,1536,1536,1536,512,0,0],"릎":[19,0,0,0,0,0,6144,16320,6272,8128,960,14528,8128,0,130560,116732,56,16320,3456,8064,3840,16128,14272,0,0],"꿇":[19,0,0,0,0,0,0,14720,16368,12640,12672,12672,118912,262140,18428,1536,7936,7152,32736,14784,11712,16352,7648,0,0],"까":[19,0,0,0,0,0,12288,28672,24576,24576,24768,10232,10176,9824,254752,254768,8600,8388,8288,8192,8192,8192,12288,0,0],"놓":[19,0,0,0,0,0,0,224,192,12480,15552,8128,7552,130048,253948,16760,1792,15872,16320,3584,6912,3328,1792,0,0],"러":[19,0,0,0,0,0,12288,24576,24576,24576,25568,25528,29056,32720,24688,25648,26160,26608,25056,24576,24576,8192,8192,0,0],"재":[19,0,0,0,0,0,24576,60416,23552,19456,28608,28152,32192,31936,23672,24048,20272,20248,16908,16384,16384,16384,24576,0,0],"받":[19,0,0,0,0,0,6144,12288,12672,13056,14092,78744,259064,13176,13304,12672,0,7936,3584,768,24960,32640,1920,0,0],"묵":[19,0,0,0,0,0,14336,32512,15328,6336,3264,16064,3200,130048,118780,1592,1536,16128,15296,4096,4096,4096,4096,0,0],"스":[19,0,0,0,0,0,0,0,512,1536,3584,1920,1792,7936,12672,24800,0,0,57344,131068,56,0,0,0,0],"릴":[19,0,0,0,0,0,12288,24576,24832,25592,25360,25536,25072,25136,26608,8432,14464,16256,7936,16128,3840,1792,130560,0,0],"계":[19,0,0,0,0,0,24576,60416,22528,22528,23424,23544,24496,24256,22720,24416,22576,22552,22536,18432,16384,16384,24576,0,0],"구":[19,0,0,0,0,0,0,6144,16352,12736,12288,12288,12288,6144,4096,131056,67324,1536,1536,1536,1536,1536,512,0,0],"물":[19,0,0,0,0,0,14336,32544,15328,3264,7872,16064,32768,131040,18428,1536,16320,8128,3840,8064,1920,896,65280,0,0],"못":[19,0,0,0,0,0,14336,32512,15328,7360,3776,16064,7296,3072,130816,116732,1048,3584,1536,1792,7936,12480,8304,0,0],"시":[19,0,0,0,0,0,12288,24576,24576,24640,24768,25024,24768,24816,24800,25520,26424,26124,25600,24576,24576,8192,8192,0,0],"육":[19,0,0,0,0,0,1792,8064,6528,6336,6528,3968,1536,130048,118780,6584,6528,16256,15296,4096,4096,4096,4096,0,0],"신":[19,0,0,0,0,0,12288,24576,24640,25024,25024,24768,24800,25568,26416,25628,24576,9088,8960,768,256,32512,15872,0,0],"일":[19,0,0,0,0,0,12288,24576,24592,24816,25584,25368,25368,25528,25072,8192,16256,16256,7680,16128,3584,1792,130560,0,0],"모":[19,0,0,0,0,0,0,0,14336,32256,16352,6368,3264,7872,16064,6144,2048,1024,50688,131064,124,0,0,0,0],"행":[19,0,0,0,0,0,24576,58368,23776,19776,20472,27888,32224,32176,23984,19696,25184,15872,30208,25344,25344,16128,7680,0,0],"절":[19,0,0,0,0,0,12288,24576,24576,25472,25584,32160,32752,26464,26160,9752,16128,16128,7680,16128,3584,1792,130560,0,0],"멸":[19,0,0,0,0,0,12288,24576,24576,26496,32760,31512,25400,32688,25072,8224,16128,16128,7680,16128,3584,1792,130560,0,0],"끊":[19,0,0,0,0,0,0,14592,16368,13280,12672,12672,12672,114688,262140,16636,7168,6240,32352,15456,13408,16224,7648,0,0],"순":[19,0,0,0,0,0,512,3584,1536,1792,8064,29056,24800,32768,131008,116732,3072,1984,1472,128,192,16256,7936,0,0],"간":[19,0,0,0,0,0,6144,28672,12288,13184,13304,12688,258240,12384,12336,12312,12296,12672,4480,384,384,16256,7936,0,0]};
    var BODY_SCALE = 1;
    var TITLE_SCALE = 2;
    var BODY_TRACKING = -2;
    var TITLE_TRACKING = 0;
    var SPACE_ADVANCE = Math.round(CELL_H * 0.5);
    var BODY_LINE_HEIGHT = CELL_H + 8;
    var PARAGRAPH_GAP = 20;
    var DIVIDER_Y = 52;
    var BODY_TOP = 68;
    var BODY_COLOR = '#d8d8d8';
    var TITLE_COLOR = '#ffffff';
    var DIVIDER_COLOR = '#555555';
    var resizeTimer = 0;
    var observed = typeof WeakSet === 'function' ? new WeakSet() : null;
    var resizeObserver = typeof ResizeObserver === 'function' ? new ResizeObserver(function (entries) {
        entries.forEach(function (entry) { schedule(entry.target, false); });
    }) : null;
 
    function glyphFor(character) {
        return Object.prototype.hasOwnProperty.call(GLYPHS, character) ? GLYPHS[character] : null;
    }
 
    function measureText(text, scale, tracking) {
        var width = 0;
        var glyphCount = 0;
        Array.from(String(text || '')).forEach(function (character) {
            var glyph;
            if (character === ' ') {
                width += SPACE_ADVANCE * scale;
                return;
            }
            glyph = glyphFor(character);
            if (!glyph) return;
            width += glyph[0] * scale;
            width += tracking * scale;
            glyphCount += 1;
        });
        if (glyphCount && tracking) width -= tracking * scale;
        return Math.max(0, Math.round(width));
    }
 
    function breakLongToken(token, maxWidth) {
        var pieces = [];
        var current = '';
        Array.from(token).forEach(function (character) {
            var candidate = current + character;
            if (current && measureText(candidate, BODY_SCALE, BODY_TRACKING) > maxWidth) {
                pieces.push(current);
                current = character;
            } else {
                current = candidate;
            }
        });
        if (current) pieces.push(current);
        return pieces;
    }
 
    function wrapParagraph(text, maxWidth) {
        var words = String(text || '').trim().split(/\s+/).filter(Boolean);
        var lines = [];
        var current = '';
 
        words.forEach(function (word) {
            var candidate = current ? current + ' ' + word : word;
            var pieces;
            if (measureText(candidate, BODY_SCALE, BODY_TRACKING) <= maxWidth) {
                current = candidate;
                return;
            }
            if (current) {
                lines.push(current);
                current = '';
            }
            if (measureText(word, BODY_SCALE, BODY_TRACKING) <= maxWidth) {
                current = word;
                return;
            }
            pieces = breakLongToken(word, maxWidth);
            pieces.forEach(function (piece, index) {
                if (index === pieces.length - 1) current = piece;
                else lines.push(piece);
            });
        });
        if (current) lines.push(current);
        return lines.length ? lines : [''];
    }
 
    function calculateOpticalShift(lines, width) {
        var weightedCenter = 0;
        var totalWeight = 0;
        var maxLineWidth = 0;
        var shift;
        lines.forEach(function (line) {
            var lineWidth = line.width;
            var weight = Math.max(1, lineWidth) * BODY_LINE_HEIGHT;
            weightedCenter += (lineWidth / 2) * weight;
            totalWeight += weight;
            maxLineWidth = Math.max(maxLineWidth, lineWidth);
        });
        if (!totalWeight) return 0;
        shift = Math.round((width / 2) - (weightedCenter / totalWeight));
        return Math.max(0, Math.min(Math.max(0, width - maxLineWidth), shift));
    }
 
    function drawGlyph(context, glyph, x, y, scale) {
        var py;
        var px;
        var row;
        for (py = 0; py < CELL_H; py += 1) {
            row = glyph[py + 1] || 0;
            if (!row) continue;
            for (px = 0; px < CELL_W; px += 1) {
                if (row & (1 << px)) {
                    context.fillRect(
                        Math.round(x + px * scale),
                        Math.round(y + py * scale),
                        scale,
                        scale
                    );
                }
            }
        }
    }
 
    function drawText(context, text, x, y, scale, tracking, color) {
        context.fillStyle = color;
        Array.from(String(text || '')).forEach(function (character) {
            var glyph;
            if (character === ' ') {
                x += SPACE_ADVANCE * scale;
                return;
            }
            glyph = glyphFor(character);
            if (!glyph) return;
            drawGlyph(context, glyph, x, y, scale);
            x += (glyph[0] + tracking) * scale;
        });
    }
 
    function sourceContent(inner) {
        var titleNode = inner.querySelector('.main-manifesto-title');
        var paragraphs = [];
        Array.prototype.forEach.call(inner.children || [], function (child) {
            if (child && child.tagName === 'P') {
                var value = String(child.textContent || '').trim();
                if (value) paragraphs.push(value);
            }
        });
        return {
            title: titleNode ? String(titleNode.textContent || '').trim() : '',
            paragraphs: paragraphs
        };
    }
 
    function ensureCanvas(inner) {
        var canvas = inner.querySelector('.main-manifesto-bitmap');
        if (!canvas) {
            canvas = document.createElement('canvas');
            canvas.className = 'main-manifesto-bitmap';
            canvas.setAttribute('aria-hidden', 'true');
            canvas.setAttribute('data-bitmap-version', VERSION);
            inner.insertBefore(canvas, inner.firstChild);
        }
        return canvas;
    }
 
    function render(inner, force) {
        var width;
        var source;
        var paragraphs;
        var flatLines = [];
        var titleWidth;
        var height;
        var canvas;
        var context;
        var y;
        var opticalShift;
 
        if (!inner || !inner.isConnected) return;
        width = Math.max(1, Math.floor(inner.clientWidth || inner.getBoundingClientRect().width || 0));
        if (width <= 1) {
            window.setTimeout(function () { schedule(inner, true); }, 60);
            return;
        }
        if (!force && Number(inner.getAttribute('data-bitmap-width')) === width && inner.classList.contains('is-bitmap-ready')) return;
 
        source = sourceContent(inner);
        if (!source.title || !source.paragraphs.length) {
            fail(inner, new Error('Manifesto source nodes were not found.'));
            return;
        }
 
        paragraphs = source.paragraphs.map(function (paragraph) {
            return wrapParagraph(paragraph, width).map(function (line) {
                var item = { text:line, width:measureText(line, BODY_SCALE, BODY_TRACKING) };
                flatLines.push(item);
                return item;
            });
        });
 
        titleWidth = measureText(source.title, TITLE_SCALE, TITLE_TRACKING);
        height = BODY_TOP;
        paragraphs.forEach(function (lines, index) {
            height += lines.length * BODY_LINE_HEIGHT;
            if (index < paragraphs.length - 1) height += PARAGRAPH_GAP;
        });
        height = Math.max(height, DIVIDER_Y + 2);
 
        canvas = ensureCanvas(inner);
        canvas.width = width;
        canvas.height = Math.ceil(height);
        canvas.style.width = width + 'px';
        canvas.style.height = Math.ceil(height) + 'px';
        context = canvas.getContext('2d', { alpha:true });
        if (!context) {
            fail(inner, new Error('Canvas 2D context is unavailable.'));
            return;
        }
        context.imageSmoothingEnabled = false;
        context.clearRect(0, 0, canvas.width, canvas.height);
 
        drawText(
            context,
            source.title,
            Math.round((width - titleWidth) / 2),
            0,
            TITLE_SCALE,
            TITLE_TRACKING,
            TITLE_COLOR
        );
 
        /* 완성형 구분선은 폐기했다. 실선 애니메이션은 ManifestoIntro만 담당한다. */
 
        opticalShift = calculateOpticalShift(flatLines, width);
        y = BODY_TOP;
        paragraphs.forEach(function (lines, paragraphIndex) {
            lines.forEach(function (line) {
                drawText(context, line.text, opticalShift, y, BODY_SCALE, BODY_TRACKING, BODY_COLOR);
                y += BODY_LINE_HEIGHT;
            });
            if (paragraphIndex < paragraphs.length - 1) y += PARAGRAPH_GAP;
        });
 
        inner.setAttribute('data-bitmap-width', String(width));
        inner.setAttribute('data-bitmap-optical-shift-x', String(opticalShift));
        inner.setAttribute('data-bitmap-state', 'ready');
        inner.classList.add('is-bitmap-ready');
    }
 
    function fail(inner, error) {
        if (!inner) return;
        inner.classList.remove('is-bitmap-ready');
        inner.setAttribute('data-bitmap-state', 'failed');
        inner.setAttribute('data-bitmap-error', String(error && error.message ? error.message : error));
        try { console.error('[MainPageBitmap]', error); } catch (ignore) {}
    }
 
    function schedule(inner, force) {
        if (!inner) return;
        window.requestAnimationFrame(function () {
            try { render(inner, force); }
            catch (error) { fail(inner, error); }
        });
    }
 
    function mount(root) {
        var scope = root && root.querySelectorAll ? root : document;
        var nodes = [];
        if (scope.matches && scope.matches(SELECTOR)) nodes.push(scope);
        nodes = nodes.concat(Array.prototype.slice.call(scope.querySelectorAll(SELECTOR)));
        nodes.forEach(function (inner) {
            if (resizeObserver && (!observed || !observed.has(inner))) {
                resizeObserver.observe(inner);
                if (observed) observed.add(inner);
            }
            schedule(inner, true);
        });
    }
 
    function recalculate() {
        Array.prototype.forEach.call(document.querySelectorAll(SELECTOR), function (inner) {
            schedule(inner, true);
        });
    }
 
    function boot() {
        mount(document);
        window.setTimeout(function () { mount(document); }, 120);
        window.setTimeout(function () { mount(document); }, 500);
    }
 
    if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot, { once:true });
    else boot();
 
    window.addEventListener('resize', function () {
        window.clearTimeout(resizeTimer);
        resizeTimer = window.setTimeout(recalculate, 100);
    }, { passive:true });
 
    try {
        if (mw && mw.hook) {
            mw.hook('wikipage.content').add(function (content) {
                mount(content && content[0] ? content[0] : document);
            });
        }
    } catch (ignoreHook) {}
 
    window.MainPageBitmap = {
        version:VERSION,
        recalculate:recalculate,
        status:function () {
            var inner = document.querySelector(SELECTOR);
            return inner ? {
                integrated:true,
                state:inner.getAttribute('data-bitmap-state') || 'pending',
                error:inner.getAttribute('data-bitmap-error') || '',
                width:inner.getAttribute('data-bitmap-width') || '',
                opticalShiftX:inner.getAttribute('data-bitmap-optical-shift-x') || '',
                canvas:!!inner.querySelector('.main-manifesto-bitmap')
            } : { integrated:true, state:'not-mounted' };
        }
    };


/* =========================================
    window.MainPageManifesto = window.MainPageManifesto || {};
  Unified Shortcuts loader
     window.MainPageManifesto.recalculate = recalculate;
  ========================================= */
})(window, document, window.mw);
(function () {
    'use strict';
 
    if (!window.mw || !mw.loader) return;
     loadClbiRawScript('MediaWiki:Nation_List_Manager.js');
    loadClbiRawScript('MediaWiki:History_Event_Manager.js');
    loadClbiRawScript('MediaWiki:Shortcuts.js');
})();

2026년 7월 21일 (화) 12:29 기준 최신판

mw.loader.load('https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.js');

/* Raw MediaWiki script cache key.
   This is not a semantic version. It only prevents stale raw JS during active editing. */
window.CLBI_RAW_LOAD_BUST = 'portal-frame-section-fit-20260721-008';

/*
Raw script loads are tracked so the site boot gate can wait for real subsystem scripts
before releasing the normal surface.  The old prefixed load-bust variable remains for
compatibility only; new loader state uses unprefixed EntryScriptLoads/EntryRawScriptPromises.
*/
window.EntryScriptLoads = window.EntryScriptLoads || [];
window.EntryRawScriptPromises = window.EntryRawScriptPromises || {};
function buildEntryRawScriptUrl(key) {
    var url = '/index.php?title=' + encodeURIComponent(key) + '&action=raw&ctype=text/javascript';
    var token;
    var sep;

    try {
        if (window.RevisionManifest && typeof window.RevisionManifest.addRevisionParam === 'function') {
            url = window.RevisionManifest.addRevisionParam(url, key);
        }
        if (/[?&]_entryRev=/.test(url)) return url;
        token = window.RevisionManifest && typeof window.RevisionManifest.manifestToken === 'function' ? window.RevisionManifest.manifestToken('raw-script-fallback') : window.CLBI_RAW_LOAD_BUST;
    } catch (err) {
        token = window.CLBI_RAW_LOAD_BUST;
    }

    sep = url.indexOf('?') === -1 ? '?' : '&';
    return url + sep + 'v=' + encodeURIComponent(String(token || 'entry-raw'));
}

function loadClbiRawScript(title) {
    var key = String(title || '').trim();
    var promise;

    if (!key) return Promise.resolve(false);
    if (window.EntryRawScriptPromises[key]) return window.EntryRawScriptPromises[key];

    promise = Promise.resolve()
        .then(function () {
            if (window.RevisionManifest && typeof window.RevisionManifest.ensureLoaded === 'function') {
                return window.RevisionManifest.ensureLoaded();
            }
            return null;
        })
        .catch(function () { return null; })
        .then(function () {
            return new Promise(function (resolve) {
                var script = document.createElement('script');
                script.src = buildEntryRawScriptUrl(key);
                script.async = true;
                script.setAttribute('data-entry-raw-script', key);
                script.onload = function () { resolve({ title: key, ok: true, src: script.src }); };
                script.onerror = function () { resolve({ title: key, ok: false, src: script.src }); };
                (document.head || document.documentElement).appendChild(script);
            });
        });

    window.EntryRawScriptPromises[key] = promise;
    window.EntryScriptLoads.push(promise);
    return promise;
}


/* =========================================
Main-page fresh assets with fallback
========================================= */

/*
Common.css의 MainPage.css import는 안전망으로 그대로 유지한다.
대문에서는 새로고침마다 timestamp가 붙은 CSS/JS를 추가로 불러와
브라우저·프록시의 오래된 raw 응답을 우회한다.

이 보조 로더가 실패해도 기존 정적 import와 기존 화면은 남는다.
*/
window.MainPageFreshAssets = window.MainPageFreshAssets || (function (window, document, mw) {
    'use strict';

    var sessionToken = String(Date.now());
    var PORTAL_FRAME_BUILD = '20260721-portal-frame-section-fit-008';
    var ASSET_LOAD_TIMEOUT_MS = 5000;
    var scriptPromises = {};
    var styleNode = null;

    function isMainPage() {
        var page = '';
        try {
            page = String(mw && mw.config ? mw.config.get('wgPageName') || '' : '');
        } catch (err) {}
        return page.replace(/_/g, ' ') === '대문';
    }

    function rawUrl(title, type) {
        var ctype = type === 'style' ? 'text/css' : 'text/javascript';
        return '/index.php?title=' + encodeURIComponent(title) +
            '&action=raw&ctype=' + encodeURIComponent(ctype) +
            '&_mainPageFresh=' + encodeURIComponent(sessionToken);
    }

    function loadStyle() {
        if (!isMainPage()) return Promise.resolve(false);

        if (styleNode && styleNode.parentNode) {
            return Promise.resolve(true);
        }

        return new Promise(function (resolve) {
            var link = document.createElement('link');
            var settled = false;
            var timeout = 0;

            function settle(ok) {
                if (settled) return;
                settled = true;
                window.clearTimeout(timeout);
                resolve(ok);
            }

            link.rel = 'stylesheet';
            link.href = rawUrl('MediaWiki:MainPage.css', 'style');
            link.setAttribute('data-main-page-fresh-style', sessionToken);
            link.onload = function () {
                styleNode = link;
                settle(true);
            };
            link.onerror = function () {
                /* Common.css의 정적 import가 그대로 남아 있으므로 화면은 유지된다. */
                settle(false);
            };
            timeout = window.setTimeout(function () { settle(false); }, ASSET_LOAD_TIMEOUT_MS);
            (document.head || document.documentElement).appendChild(link);
        });
    }

    function loadScript(title) {
        var key = String(title || '').trim();

        if (!key || !isMainPage()) return Promise.resolve(false);
        if (scriptPromises[key]) return scriptPromises[key];

        scriptPromises[key] = new Promise(function (resolve) {
            var script = document.createElement('script');
            var settled = false;
            var timeout = 0;

            function settle(ok) {
                if (settled) return;
                settled = true;
                window.clearTimeout(timeout);
                resolve(ok);
            }

            script.src = rawUrl(key, 'script');
            script.async = false;
            script.setAttribute('data-main-page-fresh-script', key);
            script.onload = function () { settle(true); };
            script.onerror = function () { settle(false); };
            timeout = window.setTimeout(function () {
                if (script.parentNode) script.parentNode.removeChild(script);
                settle(false);
            }, ASSET_LOAD_TIMEOUT_MS);
            (document.head || document.documentElement).appendChild(script);
        });

        return scriptPromises[key];
    }

    function validatePortalFrameSet() {
        var modules = [
            ['PortalFrame', window.PortalFrame],
            ['CategoryNav', window.CategoryNav],
            ['CategoryPillar', window.CategoryPillar],
            ['PortalSectionNav', window.PortalSectionNav],
            ['BottomGuideNav', window.BottomGuideNav]
        ];
        var mismatches = modules.filter(function (entry) {
            var module = entry[1];
            var version = module && (module.frameVersion || module.version);
            return version !== PORTAL_FRAME_BUILD;
        });

        document.documentElement.toggleAttribute(
            'data-portal-frame-build-mismatch',
            mismatches.length > 0
        );
        document.documentElement.setAttribute('data-portal-frame-build', PORTAL_FRAME_BUILD);

        if (mismatches.length && window.console && typeof window.console.error === 'function') {
            window.console.error(
                '[PortalFrame] 원자적 배포 세트의 버전이 일치하지 않습니다:',
                mismatches.map(function (entry) { return entry[0]; }).join(', ')
            );
        }
        return mismatches.length === 0;
    }

    function ensure() {
        if (!isMainPage()) return Promise.resolve(false);

        return loadStyle()
            .then(function () {
                return loadScript('MediaWiki:CategoryNav.js');
            })
            .then(function () {
                return loadScript('MediaWiki:CategoryPillar.js');
            })
            .then(function () {
                return loadScript('MediaWiki:PortalSectionNav.js');
            })
            .then(function () {
                return loadScript('MediaWiki:BottomGuideNav.js');
            })
            .then(function () {
                validatePortalFrameSet();
                if (window.CategoryNav && typeof window.CategoryNav.renderAll === 'function') {
                    window.CategoryNav.renderAll(document);
                }
                if (window.CategoryPillar && typeof window.CategoryPillar.renderAll === 'function') {
                    window.CategoryPillar.renderAll(document);
                }
                if (window.PortalSectionNav && typeof window.PortalSectionNav.renderAll === 'function') {
                    window.PortalSectionNav.renderAll(document);
                }
                if (window.BottomGuideNav && typeof window.BottomGuideNav.render === 'function') {
                    window.BottomGuideNav.render();
                }
                return true;
            });
    }

    function status() {
        return {
            mainPage: isMainPage(),
            token: sessionToken,
            style: !!document.querySelector('link[data-main-page-fresh-style]'),
            category: !!document.querySelector(
                'script[data-main-page-fresh-script="MediaWiki:CategoryNav.js"]'
            ),
            pillar: !!document.querySelector(
                'script[data-main-page-fresh-script="MediaWiki:CategoryPillar.js"]'
            ),
            section: !!document.querySelector(
                'script[data-main-page-fresh-script="MediaWiki:PortalSectionNav.js"]'
            ),
            guide: !!document.querySelector(
                'script[data-main-page-fresh-script="MediaWiki:BottomGuideNav.js"]'
            ),
            frameBuild: PORTAL_FRAME_BUILD,
            frameConsistent: validatePortalFrameSet()
        };
    }

    if (mw && mw.hook) {
        mw.hook('wikipage.content').add(function () {
            ensure();
        });
    }

    window.setTimeout(ensure, 0);

    return {
        ensure: ensure,
        status: status
    };
}(window, document, window.mw));


/* =========================================
   Account access page marker
   =========================================
   New shared systems use unprefixed names.  The server body class differs
   between skins/locales, so the canonical special-page name is normalized
   once and exposed as a stable page-state class for the login surface.
*/
(function markAccountLoginPage(window, document) {
    'use strict';

    var canonical = '';
    var pageName = '';
    var isLoginPage = false;

    try {
        canonical = String(window.mw && mw.config ? mw.config.get('wgCanonicalSpecialPageName') || '' : '').toLowerCase();
        pageName = String(window.mw && mw.config ? mw.config.get('wgPageName') || '' : '').replace(/_/g, ' ').toLowerCase();
    } catch (err) {}

    isLoginPage = canonical === 'userlogin' || /^(?:special|특수):(?:userlogin|로그인)$/.test(pageName);
    if (!isLoginPage) return;

    document.documentElement.classList.add('account-login-page-root');

    function isCreateAccountTarget(link) {
        var href = '';
        var title = '';
        var text = '';
        var sample = '';

        if (!link) return false;
        href = String(link.getAttribute('href') || '');
        title = String(link.getAttribute('title') || '');
        text = String(link.textContent || '');
        try { href = decodeURIComponent(href); } catch (err) {}
        sample = (href + ' ' + title + ' ' + text).replace(/_/g, ' ').toLowerCase();
        return /(?:special|특수)\s*[:%]\s*(?:createaccount|계정\s*(?:만들기|생성))|createaccount|계정\s*(?:만들기|생성)/i.test(sample);
    }

    function suppressCreateAccountSurface(root) {
        var scope = root && root.querySelectorAll ? root : document;
        var fixedSelectors = [
            '.mw-createacct-benefits-container',
            '.mw-createacct-benefits-list',
            '.mw-createaccount-cta',
            '.mw-createaccount-join',
            '#mw-createaccount-join',
            '.mw-userlogin-create'
        ];

        fixedSelectors.forEach(function (selector) {
            Array.prototype.forEach.call(scope.querySelectorAll(selector), function (node) {
                node.style.setProperty('display', 'none', 'important');
                node.setAttribute('aria-hidden', 'true');
            });
        });

        Array.prototype.forEach.call(scope.querySelectorAll('a[href]'), function (link) {
            var container;
            if (!isCreateAccountTarget(link)) return;

            link.style.setProperty('display', 'none', 'important');
            link.setAttribute('aria-hidden', 'true');
            link.setAttribute('tabindex', '-1');

            container = link.closest('.mw-ui-vform-field, .oo-ui-fieldLayout, .mw-userlogin-create, p, li');
            if (container && container.querySelectorAll('a').length === 1) {
                container.style.setProperty('display', 'none', 'important');
                container.setAttribute('aria-hidden', 'true');
            }
        });
    }

    function applyMarker() {
        if (!document.body) return;
        document.body.classList.add('account-login-page');
        suppressCreateAccountSurface(document);
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', applyMarker, { once: true });
    } else {
        applyMarker();
    }

    try {
        if (window.mw && mw.hook) {
            mw.hook('wikipage.content').add(function (content) {
                suppressCreateAccountSurface(content && content[0] ? content[0] : document);
            });
        }
    } catch (err) {}
})(window, document);

/* =========================================
   Boot gate prelude
   =========================================
   This tiny prelude runs before the full EntryStore/EntryLoader/BootGate implementation.
   Its job is only to guarantee that the user sees the separate loading surface before the
   normal wiki shell can paint.  The full BootGate later adopts the same DOM node and keeps
   it open until the real full-entry readiness contract is satisfied.

   Maintenance rule:
   - Do not move first-screen hiding into a late subsystem callback.  If the boot gate is
     meant to protect the first impression, the surface must be activated before sidebars,
     navbars, document wells, nations panels, or other entry surfaces can visibly fill in.
   - New names remain unprefixed.  Existing prefixed names elsewhere are legacy aliases only.
*/
(function installBootGatePrelude(window, document) {
    'use strict';

    var SCREEN_ID = 'boot-gate-screen';
    var STYLE_ID = 'boot-gate-prelude-style';
    var START_TIME = Date.now ? Date.now() : new Date().getTime();
    function hasQueryFlag(name, value) {
        var search = String(window.location && window.location.search || '');
        var re = new RegExp('[?&]' + name + '=([^&]+)');
        var match = search.match(re);
        return !!(match && decodeURIComponent(match[1]) === value);
    }

    function getMwConfig(name, fallback) {
        try {
            if (window.mw && window.mw.config && typeof window.mw.config.get === 'function') {
                var value = window.mw.config.get(name);
                return value == null ? fallback : value;
            }
        } catch (err) {}
        return fallback;
    }

    function normalizePageName(value) {
        return String(value || '').split('?')[0].replace(/^\/index\.php\//, '').replace(/_/g, ' ').trim();
    }

    function isDeveloperOrEditingPage() {
        var ns = Number(getMwConfig('wgNamespaceNumber', NaN));
        var action = String(getMwConfig('wgAction', 'view') || 'view').toLowerCase();
        var model = String(getMwConfig('wgPageContentModel', '') || '').toLowerCase();
        var name = normalizePageName(getMwConfig('wgPageName', '') || window.location.pathname || '');
        var systemNamespaces = {
            '-1': true, '4': true, '5': true, '6': true, '7': true, '8': true, '9': true,
            '10': true, '11': true, '12': true, '13': true, '14': true, '15': true,
            '828': true, '829': true
        };

        /*
         * Developer/system pages must stay practical.  Editing MediaWiki:, File:,
         * Project:, Template:, Module:, Category:, or any non-view action already forces
         * a full page load in MediaWiki, so showing the entry boot screen there only slows
         * maintenance work and does not improve the public first impression.
         */
        if (hasQueryFlag('bootGatePreview', '1')) return false;
        if (action && action !== 'view') return true;
        if (systemNamespaces[String(ns)]) return true;
        if (model === 'css' || model === 'javascript' || model === 'json' || model === 'sanitized-css') return true;
        if (/\.(?:css|js|json)$/i.test(name)) return true;
        if (/^(?:mediawiki|미디어위키|file|파일|project|프로젝트|template|틀|module|모듈|category|분류|special|특수):/i.test(name)) return true;
        return false;
    }

    function isAnonymousUser() {
        var userName = getMwConfig('wgUserName', null);
        var userId = Number(getMwConfig('wgUserId', 0) || 0);
        return !userName && !userId;
    }

    function isAuthenticationPage() {
        var canonical = String(getMwConfig('wgCanonicalSpecialPageName', '') || '').toLowerCase();
        var name = normalizePageName(getMwConfig('wgPageName', '') || window.location.pathname || '').toLowerCase();
        var allowed = {
            userlogin: true,
            passwordreset: true,
            resetpass: true,
            confirmemail: true
        };

        if (allowed[canonical]) return true;
        return /^(?:special|특수):(?:userlogin|로그인|passwordreset|비밀번호 ?재설정|resetpass|confirmemail)/i.test(name);
    }

    var anonymousUser = isAnonymousUser();
    var disabled = isAuthenticationPage() || (!anonymousUser && (hasQueryFlag('bootGate', '0') || isDeveloperOrEditingPage()));

    function injectStyle() {
        var style;
        if (disabled || document.getElementById(STYLE_ID)) return;
        style = document.createElement('style');
        style.id = STYLE_ID;
        style.textContent = [
            'html.boot-gate-active,body.boot-gate-active{overflow:hidden!important;}',
            'html.boot-gate-active body{background:#080808!important;}',
            'html.boot-gate-active body>:not(#boot-gate-screen){visibility:hidden!important;pointer-events:none!important;}',
            'html.boot-gate-active #boot-gate-screen,html.boot-gate-active #boot-gate-screen *{visibility:visible!important;}',
            '#boot-gate-screen{position:fixed!important;inset:0!important;z-index:2147483000!important;display:flex!important;align-items:center!important;justify-content:center!important;background:#080808!important;color:#d8d8d8!important;opacity:1;pointer-events:auto!important;}',
            '#boot-gate-screen .boot-gate-decoration-layer{position:absolute;inset:0;z-index:1;pointer-events:none;overflow:hidden;}',
            '#boot-gate-screen .boot-gate-panel{position:relative;z-index:2;}',
            '#boot-gate-screen .boot-gate-close{display:none;position:absolute;right:7px;top:6px;z-index:3;height:18px;min-width:18px;border:1px solid #000;background:#141414;color:#ddd;font-size:11px;line-height:16px;padding:0 5px;cursor:pointer;}',
            '#boot-gate-screen.is-preview{inset:auto!important;left:18px!important;top:18px!important;width:min(720px,calc(100vw - 380px))!important;height:360px!important;z-index:99990!important;overflow:hidden!important;border:1px solid #000!important;box-shadow:0 10px 28px rgba(0,0,0,.55)!important;pointer-events:none!important;}',
            '#boot-gate-screen.is-preview .boot-gate-panel,#boot-gate-screen.is-preview .boot-gate-close{pointer-events:auto!important;}',
            '#boot-gate-screen.is-preview .boot-gate-close{display:block;}'
        ].join('');
        (document.head || document.documentElement).appendChild(style);
    }

    function activate() {
        if (disabled) return;
        injectStyle();
        if (document.documentElement) document.documentElement.classList.add('boot-gate-active');
        if (document.body) document.body.classList.add('boot-gate-active');
    }

    function makeNode() {
        var node;
        var panel;
        var title;
        var status;
        var meter;
        var fill;
        var progress;
        var detail;
        var decoLayer;
        var close;

        if (disabled || !document.body) return null;
        activate();

        node = document.getElementById(SCREEN_ID);
        if (node) return node;

        node = document.createElement('div');
        node.id = SCREEN_ID;
        node.className = 'boot-gate-screen is-active';
        node.setAttribute('role', 'status');
        node.setAttribute('aria-live', 'polite');
        node.setAttribute('data-boot-gate-prelude', '1');

        panel = document.createElement('div');
        panel.className = 'boot-gate-panel';

        title = document.createElement('div');
        title.className = 'boot-gate-title';
        title.textContent = 'ARCHIVE INITIALIZATION';

        status = document.createElement('div');
        status.className = 'boot-gate-status';
        status.textContent = 'Preparing site entry systems';

        meter = document.createElement('div');
        meter.className = 'boot-gate-meter';
        fill = document.createElement('div');
        fill.className = 'boot-gate-meter-fill';
        meter.appendChild(fill);

        progress = document.createElement('div');
        progress.className = 'boot-gate-progress';
        progress.textContent = '0%';

        detail = document.createElement('div');
        detail.className = 'boot-gate-detail';
        detail.textContent = 'boot gate prelude';

        close = document.createElement('button');
        close.type = 'button';
        close.className = 'boot-gate-close';
        close.setAttribute('aria-label', 'Close boot preview');
        close.textContent = '×';
        close.addEventListener('click', function () { release(node); });

        decoLayer = document.createElement('div');
        decoLayer.className = 'boot-gate-decoration-layer';
        decoLayer.setAttribute('data-decoration-target', 'boot-gate');
        decoLayer.setAttribute('aria-hidden', 'true');

        panel.appendChild(title);
        panel.appendChild(status);
        panel.appendChild(meter);
        panel.appendChild(progress);
        panel.appendChild(detail);
        node.appendChild(decoLayer);
        node.appendChild(panel);
        node.appendChild(close);

        document.body.insertBefore(node, document.body.firstChild || null);
        return node;
    }

    function onBody(callback) {
        if (document.body) {
            callback();
            return;
        }
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', callback, { once: true });
        }
        window.setTimeout(function tick() {
            if (document.body) return callback();
            window.setTimeout(tick, 10);
        }, 0);
    }

    function release(node) {
        node = node || document.getElementById(SCREEN_ID);
        if (node) {
            node.classList.add('is-complete');
            node.classList.remove('is-active');
            window.setTimeout(function () {
                if (node.parentNode) node.parentNode.removeChild(node);
            }, 240);
        }
        window.setTimeout(function () {
            if (document.documentElement) document.documentElement.classList.remove('boot-gate-active');
            if (document.body) document.body.classList.remove('boot-gate-active');
        }, 250);
    }

    activate();
    onBody(function () {
        activate();
        makeNode();
    });

    window.__BootGatePrelude = {
        startTime: START_TIME,
        activate: activate,
        ensure: makeNode,
        release: release,
        node: function () { return document.getElementById(SCREEN_ID); },
        disabled: disabled
    };
})(window, document);

/* =========================================
   Site boot gate and entry artifact contract
   =========================================
   This is the initial-load full/half entry artifact system.

   Purpose:
   - The loading screen is not decorative. It exists only during the first site entry in a
     tab, before the user is allowed into the normal wiki surface.
   - A "full" entry must mean that the first view of that system can appear without an
     additional visible data load. For the nations system, the 1950 entry is full only when
     its nation list/link-map data and first-view pixel decorations are ready in this tab.
   - A "half" entry is a predictive warm state for the next likely path. It may fetch and
     parse data, but may skip expensive final work such as image/canvas preparation until it
     is promoted to full.
   - This principle is a site-wide design priority, like SPA continuity. New viewers,
     document systems, and information panels should define their entry full/half packs
     before exposing a first screen that can visibly fill in later.
   - SPA navigation is a consumer phase, not a blocking phase.  Do not add BootGate holds
     to SPA route changes.  If a route needs seamless first paint, prepare its artifacts
     during the initial boot pack and have the subsystem consume EntryStore synchronously
     before inserting or painting visible DOM.

   Naming rule:
   - New public APIs, globals, classes, functions, files, and components must not use a
     project prefix. Old prefixed globals are legacy compatibility surfaces only.
   - New code should use names such as BootGate, EntryLoader, EntryStore, and boot-gate-*.
*/
(function (window, document, mw) {
    'use strict';

    var MANIFEST_TITLE = 'MediaWiki:EntryManifest.json';
    var BUILD_ID = '20260711-existing-account-login-001';
    var deferredEntryWarmups = [];
    var READY_KEY = 'boot-gate-ready-version';
    var DISMISS_PARAM = 'bootGate';
    var bootStarted = false;
    var bootPromise = null;
    var bootNode = null;
    var bootStatusNode = null;
    var bootProgressNode = null;
    var bootDetailNode = null;
    var bootFillNode = null;
    var bootStartTime = 0;
    var earlyBootStyleInjected = false;
    var loginGateLocked = false;
    var loginGateActionNode = null;

    function hasQueryFlag(name, value) {
        var search = String(window.location && window.location.search || '');
        var re = new RegExp('[?&]' + name + '=([^&]+)');
        var match = search.match(re);
        return !!(match && decodeURIComponent(match[1]) === value);
    }

    function readConfig(name, fallback) {
        try {
            if (mw && mw.config && typeof mw.config.get === 'function') {
                var value = mw.config.get(name);
                return value == null ? fallback : value;
            }
        } catch (err) {}
        return fallback;
    }

    function normalizeBootPageName(value) {
        return String(value || '').split('?')[0].replace(/^\/index\.php\//, '').replace(/_/g, ' ').trim();
    }

    function isCreateAccountPage() {
        var canonical = String(readConfig('wgCanonicalSpecialPageName', '') || '').toLowerCase();
        var name = normalizeBootPageName(readConfig('wgPageName', '') || window.location.pathname || '').toLowerCase();
        return canonical === 'createaccount' || /^(?:special|특수):(?:createaccount|계정 ?(?:만들기|생성))/i.test(name);
    }

    function isAnonymousUser() {
        var userName = readConfig('wgUserName', null);
        var userId = Number(readConfig('wgUserId', 0) || 0);
        return !userName && !userId;
    }

    function isAuthenticationPage() {
        var canonical = String(readConfig('wgCanonicalSpecialPageName', '') || '').toLowerCase();
        var name = normalizeBootPageName(readConfig('wgPageName', '') || window.location.pathname || '').toLowerCase();
        var allowed = {
            userlogin: true,
            passwordreset: true,
            resetpass: true,
            confirmemail: true
        };

        if (allowed[canonical]) return true;
        return /^(?:special|특수):(?:userlogin|로그인|passwordreset|비밀번호 ?재설정|resetpass|confirmemail)/i.test(name);
    }

    function requiresLoginGate() {
        return isAnonymousUser() && !isAuthenticationPage();
    }

    function isBootExcludedPage() {
        var ns = Number(readConfig('wgNamespaceNumber', NaN));
        var action = String(readConfig('wgAction', 'view') || 'view').toLowerCase();
        var model = String(readConfig('wgPageContentModel', '') || '').toLowerCase();
        var name = normalizeBootPageName(readConfig('wgPageName', '') || window.location.pathname || '');
        var systemNamespaces = {
            '-1': true, '4': true, '5': true, '6': true, '7': true, '8': true, '9': true,
            '10': true, '11': true, '12': true, '13': true, '14': true, '15': true,
            '828': true, '829': true
        };

        /*
         * The public boot gate is for normal reading surfaces.  Developer/system
         * namespaces and edit/diff/history actions already reload outside SPA, so
         * blocking them would turn every maintenance save into another entry boot.
         */
        if (hasQueryFlag('bootGatePreview', '1')) return false;
        if (action && action !== 'view') return true;
        if (systemNamespaces[String(ns)]) return true;
        if (model === 'css' || model === 'javascript' || model === 'json' || model === 'sanitized-css') return true;
        if (/\.(?:css|js|json)$/i.test(name)) return true;
        if (/^(?:mediawiki|미디어위키|file|파일|project|프로젝트|template|틀|module|모듈|category|분류|special|특수):/i.test(name)) return true;
        return false;
    }

    var LOGIN_REQUIRED = requiresLoginGate();
    var BOOT_EXCLUDED_PAGE = isBootExcludedPage() && !LOGIN_REQUIRED;

    function injectEarlyBootStyle() {
        var style;
        if (earlyBootStyleInjected || !document.documentElement) return;
        earlyBootStyleInjected = true;
        style = document.createElement('style');
        style.id = 'boot-gate-early-style';
        style.textContent = [
            'html.boot-gate-active, body.boot-gate-active{overflow:hidden!important;}',
            'html.boot-gate-active body{background:#080808!important;}',
            'html.boot-gate-active body> :not(#boot-gate-screen){visibility:hidden!important;pointer-events:none!important;}',
            'html.boot-gate-active #boot-gate-screen,html.boot-gate-active #boot-gate-screen *{visibility:visible!important;}'
        ].join('');
        (document.head || document.documentElement).appendChild(style);
    }

    function activateBootSurface() {
        injectEarlyBootStyle();
        if (document.documentElement) document.documentElement.classList.add('boot-gate-active');
        if (document.body) document.body.classList.add('boot-gate-active');
    }

    if (!BOOT_EXCLUDED_PAGE) activateBootSurface();
    else if (window.__BootGatePrelude && window.__BootGatePrelude.release) window.__BootGatePrelude.release();

    var defaultManifest = {
        version: '20260710-globe-vhs-restore-entry-001',
        boot: {
            minDisplayMs: 950,
            cachedMinDisplayMs: 350,
            maxBlockingMs: 15000
        },
        initial: {
            full: [
                {
                    id: 'decorations-registry',
                    label: 'DECORATION REGISTRY',
                    type: 'decorations',
                    ref: 'MediaWiki:Decorations.json',
                    page: '시대',
                    era: '1950',
                    preparePixels: true
                },
                {
                    id: 'nations-1950-entry',
                    label: '1950 ERA ENTRY',
                    type: 'nations-era',
                    era: '1950',
                    level: 'full'
                }
            ],
            half: [
                {
                    id: 'nations-1960-half',
                    label: '1960 ERA HALF',
                    type: 'nations-era',
                    era: '1960',
                    level: 'half'
                }
            ]
        }
    };

    function now() {
        return Date.now ? Date.now() : new Date().getTime();
    }


    var BootPerf = window.BootPerf = window.BootPerf || (function () {
        var t0 = now();
        var entries = [];
        var active = {};
        var seq = 0;

        function cloneMeta(meta) {
            var out = {};
            Object.keys(meta || {}).forEach(function (key) {
                var value = meta[key];
                if (value == null) return;
                if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') out[key] = value;
                else {
                    try { out[key] = JSON.parse(JSON.stringify(value)); }
                    catch (err) { out[key] = String(value); }
                }
            });
            return out;
        }

        function start(name, meta) {
            var id = String(++seq);
            active[id] = { id: id, name: String(name || 'entry'), start: now(), meta: cloneMeta(meta) };
            return id;
        }

        function end(id, meta) {
            var item = active[id];
            var ended = now();
            if (!item) return null;
            delete active[id];
            item.end = ended;
            item.ms = ended - item.start;
            item.offset = item.start - t0;
            item.meta = Object.assign({}, item.meta || {}, cloneMeta(meta));
            entries.push(item);
            return item;
        }

        function instant(name, meta) {
            var t = now();
            entries.push({ id: String(++seq), name: String(name || 'mark'), start: t, end: t, ms: 0, offset: t - t0, meta: cloneMeta(meta) });
        }

        function measure(name, meta, fn) {
            var id = start(name, meta);
            try {
                return Promise.resolve(fn()).then(function (value) {
                    end(id, { ok: true });
                    return value;
                }, function (err) {
                    end(id, { ok: false, error: err && (err.message || String(err)) });
                    throw err;
                });
            } catch (err) {
                end(id, { ok: false, error: err && (err.message || String(err)) });
                return Promise.reject(err);
            }
        }

        function rows() {
            return entries.slice().sort(function (a, b) { return a.start - b.start; }).map(function (item) {
                return {
                    offset: item.offset,
                    ms: item.ms,
                    name: item.name,
                    meta: item.meta || {}
                };
            });
        }

        function summary() {
            var list = rows();
            var total = list.reduce(function (max, item) { return Math.max(max, item.offset + item.ms); }, 0);
            return {
                build: BUILD_ID,
                startedAt: t0,
                totalMs: total,
                entries: list,
                active: Object.keys(active).map(function (id) { return active[id]; })
            };
        }

        function print() {
            var list = rows();
            if (!window.console || !console.log) return summary();
            try {
                console.groupCollapsed('[BootPerf] entry loading timeline · ' + BUILD_ID);
                if (console.table) console.table(list.map(function (item) {
                    return {
                        offset: item.offset + 'ms',
                        duration: item.ms + 'ms',
                        name: item.name,
                        detail: JSON.stringify(item.meta || {})
                    };
                }));
                else list.forEach(function (item) { console.log(item.offset + 'ms', item.ms + 'ms', item.name, item.meta || {}); });
                console.groupEnd();
            } catch (err) {}
            return summary();
        }

        return {
            start: start,
            end: end,
            mark: instant,
            measure: measure,
            rows: rows,
            summary: summary,
            print: print
        };
    }());


    var InteractionPerf = window.InteractionPerf = window.InteractionPerf || (function () {
        var BUILD = '20260710-interaction-perf-instrument-001';
        var t0 = (window.performance && performance.now ? performance.now() : now());
        var entries = [];
        var active = {};
        var seq = 0;
        var maxEntries = 1600;

        function perfNow() {
            return window.performance && performance.now ? performance.now() : now();
        }

        function cloneMeta(meta) {
            var out = {};
            Object.keys(meta || {}).forEach(function (key) {
                var value = meta[key];
                if (value == null) return;
                if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') out[key] = value;
                else {
                    try { out[key] = JSON.parse(JSON.stringify(value)); }
                    catch (err) { out[key] = String(value); }
                }
            });
            return out;
        }

        function push(entry) {
            entries.push(entry);
            if (entries.length > maxEntries) entries.splice(0, entries.length - maxEntries);
            return entry;
        }

        function start(name, meta) {
            var id = String(++seq);
            active[id] = { id: id, name: String(name || 'interaction'), start: perfNow(), meta: cloneMeta(meta) };
            return id;
        }

        function end(id, meta) {
            var item = active[id];
            var ended = perfNow();
            if (!item) return null;
            delete active[id];
            item.end = ended;
            item.ms = Math.round((ended - item.start) * 100) / 100;
            item.offset = Math.round((item.start - t0) * 100) / 100;
            item.meta = Object.assign({}, item.meta || {}, cloneMeta(meta));
            return push(item);
        }

        function mark(name, meta) {
            var t = perfNow();
            return push({ id: String(++seq), name: String(name || 'mark'), start: t, end: t, ms: 0, offset: Math.round((t - t0) * 100) / 100, meta: cloneMeta(meta) });
        }

        function measureSync(name, meta, fn) {
            var id = start(name, meta);
            try {
                var value = fn();
                end(id, { ok: true });
                return value;
            } catch (err) {
                end(id, { ok: false, error: err && (err.message || String(err)) || String(err) });
                throw err;
            }
        }

        function measureAsync(name, meta, fn) {
            var id = start(name, meta);
            try {
                return Promise.resolve(fn()).then(function (value) {
                    end(id, { ok: true });
                    return value;
                }, function (err) {
                    end(id, { ok: false, error: err && (err.message || String(err)) || String(err) });
                    throw err;
                });
            } catch (err) {
                end(id, { ok: false, error: err && (err.message || String(err)) || String(err) });
                return Promise.reject(err);
            }
        }

        function summary() {
            return {
                build: BUILD,
                startedAt: t0,
                totalMs: Math.round((perfNow() - t0) * 100) / 100,
                entries: entries.slice().sort(function (a, b) {
                    if (a.offset !== b.offset) return a.offset - b.offset;
                    return b.ms - a.ms;
                }),
                active: Object.keys(active).map(function (id) {
                    var item = active[id];
                    return { offset: Math.round((item.start - t0) * 100) / 100, ms: Math.round((perfNow() - item.start) * 100) / 100, name: item.name, meta: item.meta || {} };
                })
            };
        }

        function table() {
            var data = summary().entries.map(function (entry) {
                return { offset: entry.offset, ms: entry.ms, name: entry.name, meta: entry.meta };
            });
            if (window.console && console.table) console.table(data);
            return data;
        }

        try {
            if (window.PerformanceObserver && !window.CLBI_InteractionLongTaskObserverBound) {
                window.CLBI_InteractionLongTaskObserverBound = true;
                new PerformanceObserver(function (list) {
                    list.getEntries().forEach(function (entry) {
                        mark('browser long task', {
                            ms: Math.round(entry.duration * 100) / 100,
                            start: Math.round(entry.startTime * 100) / 100,
                            attribution: entry.attribution && entry.attribution.length ? entry.attribution.length : 0
                        });
                    });
                }).observe({ entryTypes: ['longtask'] });
            }
        } catch (ignoreLongTaskObserver) {}

        return {
            build: BUILD,
            start: start,
            end: end,
            mark: mark,
            measureSync: measureSync,
            measureAsync: measureAsync,
            summary: summary,
            table: table
        };
    }());

    function toArray(value) {
        return Array.prototype.slice.call(value || []);
    }

    function unique(list) {
        var seen = {};
        var out = [];
        (list || []).forEach(function (item) {
            item = String(item || '').trim();
            if (!item || seen[item]) return;
            seen[item] = true;
            out.push(item);
        });
        return out;
    }

    function hasBootParam(value) {
        var search = String(window.location && window.location.search || '');
        var re = new RegExp('[?&]' + DISMISS_PARAM + '=([^&]+)');
        var match = search.match(re);
        return match && decodeURIComponent(match[1]) === value;
    }

    function normalizeTitle(value) {
        return String(value || '')
            .split('#')[0]
            .replace(/_/g, ' ')
            .trim();
    }

    function extractTitleFromUrl(value) {
        var text = String(value || '');
        var match = text.match(/[?&]title=([^&]+)/i);
        if (match) return normalizeTitle(decodeURIComponent(match[1].replace(/\+/g, ' ')));
        return '';
    }

    function normalizeRefKey(ref) {
        var text = String(ref || '').trim();
        var title;
        if (!text) return '';
        title = extractTitleFromUrl(text);
        if (title) return 'title:' + title.toLowerCase();
        if (text.indexOf('/') === -1 && text.indexOf(':') !== -1) return 'title:' + normalizeTitle(text).toLowerCase();
        return 'url:' + text;
    }

    function rawUrlForRef(ref, ctype) {
        var text = String(ref || '').trim();
        var title;
        if (!text) return '';
        if (/^(?:https?:)?\/\//i.test(text) || text.charAt(0) === '/') return text;
        title = normalizeTitle(text.indexOf(':') !== -1 ? text : ('MediaWiki:' + text));
        if (mw && mw.util && typeof mw.util.getUrl === 'function') {
            return mw.util.getUrl(title, { action: 'raw', ctype: ctype || 'application/json' });
        }
        return '/index.php?title=' + encodeURIComponent(title) + '&action=raw&ctype=' + encodeURIComponent(ctype || 'application/json');
    }

    function getApiEndpoint() {
        return (mw && mw.util && typeof mw.util.wikiScript === 'function') ? mw.util.wikiScript('api') : '/api.php';
    }

    function fetchApi(params) {
        var body = new URLSearchParams();
        Object.keys(params || {}).forEach(function (key) {
            body.append(key, params[key]);
        });
        return fetch(getApiEndpoint(), {
            method: 'POST',
            credentials: 'same-origin',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
            body: body.toString()
        }).then(function (res) {
            if (!res.ok) throw new Error('HTTP ' + res.status);
            return res.json();
        });
    }


    /* =========================================
       Revision manifest and persistent entry cache
       =========================================
       The first boot still prepares current-tab artifacts, but freshness is not guessed from
       filenames or old localStorage flags.  The client reads a tiny server-side current-state
       manifest, compares page revisions / file sha1 values, and only keeps cached raw resources
       whose revision token still matches the server.  The manifest is a latest-state table, not
       an append-only client log.
    */
    var REVISION_MANIFEST_ACTION = 'entryrevisionmanifest';
    var REVISION_MANIFEST_LOCAL_KEY = 'entry-revision-manifest-current-v1';
    var REVISION_MANIFEST_PRUNE_LOCAL_KEY = 'entry-revision-manifest-last-client-prune-v1';
    var ENTRY_CACHE_NAME = 'entry-cache-v1';
    var ENTRY_CACHE_INDEX_KEY = 'entry-cache-index-v1';
    var ENTRY_CACHE_REQUEST_PREFIX = '/__entry-cache__/';
    var ENTRY_CACHE_PACK_KEY = 'entry-cache-pack-state-v1';

    function hasCacheStorage() {
        return !!(window.caches && typeof window.caches.open === 'function');
    }

    function safeJsonParse(text, fallback) {
        try { return JSON.parse(text); } catch (err) { return fallback; }
    }

    function readLocalJson(key, fallback) {
        try {
            var text = window.localStorage ? window.localStorage.getItem(key) : null;
            return text ? safeJsonParse(text, fallback) : fallback;
        } catch (err) {
            return fallback;
        }
    }

    function writeLocalJson(key, value) {
        try {
            if (window.localStorage) window.localStorage.setItem(key, JSON.stringify(value));
        } catch (err) {}
    }

    function normalizeManifestTitle(value) {
        var text = String(value || '').trim();
        var match;
        var i;
        if (!text) return '';
        for (i = 0; i < 3; i += 1) {
            try {
                if (/%[0-9a-f]{2}/i.test(text)) text = decodeURIComponent(text);
            } catch (err) { break; }
        }
        match = text.match(/[?&]title=([^&#]+)/i);
        if (match) text = match[1];
        text = text.replace(/^https?:\/\/[^/]+/i, '')
            .replace(/^\/+/, '')
            .replace(/^index\.php\/?/i, '')
            .replace(/^wiki\/?/i, '')
            .trim();
        match = text.match(/(?:^|\/)(?:(?:Special|특수)\s*[:/]\s*)?(?:Redirect|넘겨주기)\s*\/\s*file\s*\/([^?#]+)(?:[?#].*)?$/i);
        if (match) text = 'File:' + match[1];
        text = text.split('#')[0].replace(/_/g, ' ').replace(/\s+/g, ' ').trim();
        text = text.replace(/^(?:파일|Image|이미지)\s*:/i, 'File:');
        if (/^(?:mediawiki|template|module|manage|file)\s*:/i.test(text)) {
            text = text.replace(/^([^:]+)\s*:\s*/, function (_, ns) { return ns.charAt(0).toUpperCase() + ns.slice(1).toLowerCase() + ':'; });
        }
        if (/^File:/i.test(text)) text = 'File:' + text.slice(text.indexOf(':') + 1).trim();
        if (/^Mediawiki:/i.test(text)) text = 'MediaWiki:' + text.slice(text.indexOf(':') + 1).trim();
        return text;
    }

    function resourceToken(resource) {
        if (!resource || typeof resource !== 'object') return '';
        return String(resource.revision || resource.sha1 || resource.hash || resource.timestamp || resource.updatedAt || resource.url || '').trim();
    }

    function createEntryCache() {
        var index = readLocalJson(ENTRY_CACHE_INDEX_KEY, { entries: {} }) || { entries: {} };
        var packs = readLocalJson(ENTRY_CACHE_PACK_KEY, { packs: {} }) || { packs: {} };
        var objectUrls = {};
        var stats = {
            textHits: 0,
            blobHits: 0,
            misses: 0,
            networkStores: 0,
            stores: 0,
            deletes: 0
        };

        function ensureIndex() {
            if (!index || typeof index !== 'object') index = { entries: {} };
            if (!index.entries || typeof index.entries !== 'object') index.entries = {};
        }

        function compactIndexForLocalStorage() {
            var entries;
            var next = {};
            ensureIndex();
            entries = index.entries || {};
            Object.keys(entries).forEach(function (key) {
                var entry = entries[key] || {};
                var kind = String(entry.kind || 'raw').toLowerCase();
                /*
                 * CacheStorage already owns image/blob bodies.  Keeping one localStorage
                 * metadata row per flag/blob competes with MediaWiki ResourceLoader's own
                 * localStorage module store and can trigger QuotaExceededError before our
                 * code even runs on the next page load.  Text/json/file URL rows stay indexed
                 * because they are small and useful for invalidation diagnostics.
                 */
                if (kind === 'image' || kind === 'blob') return;
                next[key] = entry;
            });
            index.entries = next;
        }

        function ensurePacks() {
            if (!packs || typeof packs !== 'object') packs = { packs: {} };
            if (!packs.packs || typeof packs.packs !== 'object') packs.packs = {};
        }

        function saveIndex() {
            ensureIndex();
            compactIndexForLocalStorage();
            writeLocalJson(ENTRY_CACHE_INDEX_KEY, index);
        }

        function savePacks() {
            ensurePacks();
            writeLocalJson(ENTRY_CACHE_PACK_KEY, packs);
        }

        function requestForKey(key) {
            return new Request(ENTRY_CACHE_REQUEST_PREFIX + encodeURIComponent(String(key || '')), { credentials: 'same-origin' });
        }

        function openCache() {
            if (!hasCacheStorage()) return Promise.resolve(null);
            return window.caches.open(ENTRY_CACHE_NAME).catch(function () { return null; });
        }

        function cacheEntry(key, meta) {
            key = String(key || '');
            ensureIndex();
            index.entries[key] = Object.assign({}, index.entries[key] || {}, {
                key: key,
                resourceKey: String(meta && meta.resourceKey || ''),
                token: String(meta && meta.token || ''),
                kind: String(meta && meta.kind || 'raw'),
                contentType: String(meta && meta.contentType || ''),
                size: Number(meta && meta.size || 0) || null,
                createdAt: index.entries[key] && index.entries[key].createdAt ? index.entries[key].createdAt : now(),
                updatedAt: now(),
                lastHitAt: index.entries[key] && index.entries[key].lastHitAt ? index.entries[key].lastHitAt : null,
                hits: Number(index.entries[key] && index.entries[key].hits || 0)
            });
            saveIndex();
        }

        function markHit(key, field) {
            key = String(key || '');
            ensureIndex();
            if (index.entries[key]) {
                index.entries[key].hits = Number(index.entries[key].hits || 0) + 1;
                index.entries[key].lastHitAt = now();
                saveIndex();
            }
            if (field && stats[field] != null) stats[field] += 1;
        }

        function getResponse(key) {
            key = String(key || '');
            if (!key || !hasCacheStorage()) return Promise.resolve(null);
            return openCache().then(function (cache) {
                if (!cache) return null;
                return cache.match(requestForKey(key)).then(function (res) {
                    if (!res) {
                        stats.misses += 1;
                        return null;
                    }
                    return res;
                });
            }).catch(function () { return null; });
        }

        function putResponse(key, response, meta) {
            key = String(key || '');
            if (!key || !response || !hasCacheStorage()) return Promise.resolve(false);
            meta = meta || {};
            return openCache().then(function (cache) {
                var cloned;
                var headers;
                var bodyPromise;
                if (!cache) return false;
                cloned = response.clone();
                bodyPromise = cloned.blob().catch(function () { return null; });
                return bodyPromise.then(function (blob) {
                    if (!blob) return false;
                    headers = new Headers(response.headers || {});
                    if (!headers.get('Content-Type')) headers.set('Content-Type', meta.contentType || blob.type || 'application/octet-stream');
                    headers.set('X-Entry-Cache-Key', key);
                    headers.set('X-Entry-Resource-Key', String(meta.resourceKey || ''));
                    headers.set('X-Entry-Revision-Token', String(meta.token || ''));
                    headers.set('X-Entry-Cached-At', String(now()));
                    return cache.put(requestForKey(key), new Response(blob, { status: 200, headers: headers })).then(function () {
                        stats.stores += 1;
                        cacheEntry(key, {
                            resourceKey: meta.resourceKey,
                            token: meta.token,
                            kind: meta.kind || 'blob',
                            contentType: headers.get('Content-Type') || blob.type || '',
                            size: blob.size
                        });
                        return true;
                    });
                });
            }).catch(function () { return false; });
        }

        function getText(key) {
            return getResponse(key).then(function (res) {
                if (!res) return null;
                markHit(key, 'textHits');
                return res.text();
            }).catch(function () { return null; });
        }

        function putText(key, text, meta) {
            key = String(key || '');
            if (!key || !hasCacheStorage()) return Promise.resolve(false);
            meta = meta || {};
            return openCache().then(function (cache) {
                var headers;
                var body = String(text || '');
                if (!cache) return false;
                headers = new Headers({
                    'Content-Type': meta.contentType || 'text/plain; charset=UTF-8',
                    'X-Entry-Cache-Key': key,
                    'X-Entry-Resource-Key': String(meta.resourceKey || ''),
                    'X-Entry-Revision-Token': String(meta.token || ''),
                    'X-Entry-Cached-At': String(now())
                });
                return cache.put(requestForKey(key), new Response(body, { status: 200, headers: headers })).then(function () {
                    stats.stores += 1;
                    cacheEntry(key, {
                        resourceKey: meta.resourceKey,
                        token: meta.token,
                        kind: meta.kind || 'text',
                        contentType: headers.get('Content-Type'),
                        size: body.length
                    });
                    return true;
                });
            }).catch(function () { return false; });
        }

        function getBlobUrl(key) {
            key = String(key || '');
            if (!key) return Promise.resolve('');
            if (objectUrls[key]) {
                markHit(key, 'blobHits');
                return Promise.resolve(objectUrls[key]);
            }
            return getResponse(key).then(function (res) {
                if (!res) return '';
                return res.blob().then(function (blob) {
                    if (!blob || !blob.size) return '';
                    objectUrls[key] = URL.createObjectURL(blob);
                    markHit(key, 'blobHits');
                    return objectUrls[key];
                });
            }).catch(function () { return ''; });
        }

        function fetchBlobUrl(url, key, meta, options) {
            url = String(url || '').trim();
            key = String(key || '').trim();
            if (!url || !key) return Promise.resolve('');
            return getBlobUrl(key).then(function (cachedUrl) {
                if (cachedUrl) return cachedUrl;
                return fetch(url, {
                    credentials: 'same-origin',
                    cache: options && options.noStore ? 'no-store' : 'force-cache'
                }).then(function (res) {
                    if (!res.ok) throw new Error('HTTP ' + res.status);
                    stats.networkStores += 1;
                    return putResponse(key, res, Object.assign({}, meta || {}, { kind: meta && meta.kind ? meta.kind : 'blob' })).then(function () {
                        return getBlobUrl(key);
                    });
                }).catch(function () {
                    return '';
                });
            });
        }

        function deleteKey(key) {
            key = String(key || '');
            if (!key || !hasCacheStorage()) return Promise.resolve(false);
            if (objectUrls[key]) {
                try { URL.revokeObjectURL(objectUrls[key]); } catch (err) {}
                delete objectUrls[key];
            }
            return openCache().then(function (cache) {
                if (!cache) return false;
                return cache.delete(requestForKey(key)).then(function (ok) {
                    ensureIndex();
                    if (index.entries && index.entries[key]) {
                        delete index.entries[key];
                        stats.deletes += 1;
                        saveIndex();
                    }
                    return ok;
                });
            }).catch(function () { return false; });
        }

        function invalidateResources(resourceKeys) {
            var map = {};
            var entries;
            var keys = [];
            ensureIndex();
            entries = index.entries || {};
            (resourceKeys || []).forEach(function (resourceKey) {
                resourceKey = String(resourceKey || '').toLowerCase();
                if (resourceKey) map[resourceKey] = true;
            });
            Object.keys(entries).forEach(function (cacheKey) {
                var resourceKey = String(entries[cacheKey] && entries[cacheKey].resourceKey || '').toLowerCase();
                if (map[resourceKey]) keys.push(cacheKey);
            });
            return Promise.all(keys.map(deleteKey)).then(function () { return keys.length; });
        }

        function prune(maxAgeDays) {
            var days = Math.max(1, Number(maxAgeDays) || 7);
            var cutoff = now() - days * 24 * 60 * 60 * 1000;
            var entries;
            var keys;
            ensureIndex();
            entries = index.entries || {};
            keys = Object.keys(entries).filter(function (key) {
                return Number(entries[key] && entries[key].createdAt || 0) < cutoff;
            });
            window.localStorage && window.localStorage.setItem(REVISION_MANIFEST_PRUNE_LOCAL_KEY, String(now()));
            return Promise.all(keys.map(deleteKey)).then(function () { return keys.length; });
        }

        function reset() {
            Object.keys(objectUrls).forEach(function (key) {
                try { URL.revokeObjectURL(objectUrls[key]); } catch (err) {}
            });
            objectUrls = {};
            index = { entries: {} };
            packs = { packs: {} };
            saveIndex();
            savePacks();
            if (!hasCacheStorage()) return Promise.resolve(false);
            return window.caches.delete(ENTRY_CACHE_NAME).catch(function () { return false; });
        }

        function packReady(key, token) {
            key = String(key || '');
            token = String(token || '');
            ensurePacks();
            if (!key || !token) return false;
            return !!(packs.packs[key] && String(packs.packs[key].token || '') === token && packs.packs[key].ready);
        }

        function setPackReady(key, token, meta) {
            key = String(key || '');
            token = String(token || '');
            if (!key || !token) return false;
            ensurePacks();
            packs.packs[key] = Object.assign({}, meta || {}, {
                key: key,
                token: token,
                ready: true,
                updatedAt: now()
            });
            savePacks();
            return true;
        }

        function packInfo() {
            ensurePacks();
            return Object.assign({}, packs.packs || {});
        }

        function info() {
            var lastClientPrune = 0;
            var entries;
            var byKind = {};
            try { lastClientPrune = Number(window.localStorage && window.localStorage.getItem(REVISION_MANIFEST_PRUNE_LOCAL_KEY) || 0); } catch (err) {}
            ensureIndex();
            ensurePacks();
            entries = index.entries || {};
            Object.keys(entries).forEach(function (key) {
                var kind = String(entries[key] && entries[key].kind || 'raw');
                byKind[kind] = (byKind[kind] || 0) + 1;
            });
            return {
                supported: hasCacheStorage(),
                name: ENTRY_CACHE_NAME,
                entries: Object.keys(entries).length,
                byKind: byKind,
                packs: Object.keys(packs.packs || {}).length,
                lastClientPruneAt: lastClientPrune || null,
                stats: Object.assign({}, stats)
            };
        }

        /* Trim legacy image/blob metadata rows produced by older builds. */
        try { saveIndex(); } catch (err) {}

        return {
            getResponse: getResponse,
            putResponse: putResponse,
            getText: getText,
            putText: putText,
            getBlobUrl: getBlobUrl,
            fetchBlobUrl: fetchBlobUrl,
            invalidateResources: invalidateResources,
            prune: prune,
            reset: reset,
            packReady: packReady,
            setPackReady: setPackReady,
            packInfo: packInfo,
            info: info
        };
    }

    window.EntryCache = window.EntryCache || createEntryCache();

    function createRevisionManifestService() {
        var current = null;
        var previous = readLocalJson(REVISION_MANIFEST_LOCAL_KEY, null);
        var loadPromise = null;
        var changedResources = [];

        function unwrap(payload) {
            return payload && (payload.entryrevisionmanifest || payload.revisionManifest || payload) || null;
        }

        function resourcesOf(manifest) {
            return manifest && manifest.resources && typeof manifest.resources === 'object' ? manifest.resources : {};
        }

        function compactRevisionManifest(manifest) {
            var out;
            var resources;
            if (!manifest || typeof manifest !== 'object') return null;
            out = {
                manifestVersion: manifest.manifestVersion || manifest.version || '',
                version: manifest.version || manifest.manifestVersion || '',
                generatedAt: manifest.generatedAt || '',
                pruneDays: manifest.pruneDays,
                clientPruneDays: manifest.clientPruneDays,
                resources: {}
            };
            resources = resourcesOf(manifest);
            Object.keys(resources).forEach(function (title) {
                var src = resources[title];
                var dst;
                if (!src || typeof src !== 'object') return;
                dst = {};
                ['revision', 'sha1', 'hash', 'timestamp', 'updatedAt', 'url'].forEach(function (key) {
                    if (src[key] !== undefined && src[key] !== null && String(src[key]) !== '') dst[key] = src[key];
                });
                out.resources[title] = dst;
            });
            return out;
        }

        function buildLookup(manifest) {
            var lookup = {};
            Object.keys(resourcesOf(manifest)).forEach(function (title) {
                lookup[normalizeManifestTitle(title).toLowerCase()] = resourcesOf(manifest)[title];
            });
            return lookup;
        }

        function computeChanged(prev, next) {
            var prevLookup = buildLookup(prev);
            var nextLookup = buildLookup(next);
            var out = [];
            Object.keys(nextLookup).forEach(function (key) {
                if (resourceToken(prevLookup[key]) !== resourceToken(nextLookup[key])) out.push(key);
            });
            Object.keys(prevLookup).forEach(function (key) {
                if (!nextLookup[key]) out.push(key);
            });
            return unique(out);
        }

        function load(options) {
            if (loadPromise && !(options && options.force)) return loadPromise;
            loadPromise = fetchApi({
                action: REVISION_MANIFEST_ACTION,
                format: 'json',
                formatversion: '2'
            }).then(function (payload) {
                var manifest = unwrap(payload);
                if (!manifest || !manifest.resources) throw new Error('invalid revision manifest');
                current = compactRevisionManifest(manifest) || manifest;
                changedResources = computeChanged(previous, current);
                if (changedResources.length && window.EntryCache && typeof window.EntryCache.invalidateResources === 'function') {
                    window.EntryCache.invalidateResources(changedResources);
                }
                writeLocalJson(REVISION_MANIFEST_LOCAL_KEY, current);
                previous = current;
                maybePrune();
                return current;
            }).catch(function () {
                current = previous || null;
                return current;
            });
            return loadPromise;
        }

        function ensureLoaded() {
            return current ? Promise.resolve(current) : load();
        }

        function resourceForRef(ref) {
            var title = normalizeManifestTitle(ref);
            var lookup;
            if (!title || !current) return null;
            lookup = buildLookup(current);
            return lookup[title.toLowerCase()] || null;
        }

        function tokenForRef(ref) {
            return resourceToken(resourceForRef(ref));
        }

        function resourceKeyForRef(ref) {
            var title = normalizeManifestTitle(ref);
            return title ? title.toLowerCase() : '';
        }

        function cacheKeyForRef(ref, type) {
            var resourceKey = resourceKeyForRef(ref);
            var token = tokenForRef(ref);
            if (!resourceKey || !token) return '';
            return String(type || 'raw') + ':' + resourceKey + '@' + token;
        }

        function manifestToken(extra) {
            var base = current && (current.manifestVersion || current.version || current.generatedAt || '') || '';
            return String(base || 'no-manifest') + (extra ? (':' + String(extra)) : '');
        }

        function tokenFromUrl(url) {
            var text = String(url || '');
            var match = text.match(/[?&](?:_entryFileRev|_entryAsset|_entryRev)=([^&]+)/);
            if (!match) return '';
            try { return decodeURIComponent(match[1]); } catch (err) { return match[1]; }
        }

        function cacheKeyForUrl(url, type) {
            var text = String(url || '').trim();
            var token = tokenFromUrl(text) || manifestToken('url');
            var normalized;
            if (!text) return '';
            try {
                normalized = new URL(text, window.location.href);
                text = normalized.pathname + (normalized.search || '');
            } catch (err) {}
            text = text.replace(/[?&](?:_entryFileRev|_entryAsset|_entryRev)=[^&]*/g, '').replace(/[?&]$/, '');
            try { text = decodeURI(text); } catch (err2) {}
            return String(type || 'blob') + ':url:' + text.toLowerCase() + '@' + token;
        }

        function addRevisionParam(url, ref) {
            var token = tokenForRef(ref);
            var text = String(url || '').trim();
            var sep;
            if (!text || !token || /[?&]_entryRev=/.test(text)) return text;
            sep = text.indexOf('?') === -1 ? '?' : '&';
            return text + sep + '_entryRev=' + encodeURIComponent(token);
        }

        function maybePrune() {
            var days = current && Number(current.pruneDays || current.clientPruneDays) || 7;
            var last = 0;
            var due;
            try { last = Number(window.localStorage && window.localStorage.getItem(REVISION_MANIFEST_PRUNE_LOCAL_KEY) || 0); } catch (err) {}
            due = !last || (now() - last >= days * 24 * 60 * 60 * 1000);
            if (due && window.EntryCache && typeof window.EntryCache.prune === 'function') {
                window.EntryCache.prune(days);
            }
        }

        function countdown() {
            var days = current && Number(current.pruneDays || current.clientPruneDays) || 7;
            var last = 0;
            var next;
            var remain;
            try { last = Number(window.localStorage && window.localStorage.getItem(REVISION_MANIFEST_PRUNE_LOCAL_KEY) || 0); } catch (err) {}
            if (!last) return { days: days, lastClientPruneAt: null, nextClientPruneAt: null, remainingMs: 0, remainingDays: 0, due: true };
            next = last + days * 24 * 60 * 60 * 1000;
            remain = Math.max(0, next - now());
            return {
                days: days,
                lastClientPruneAt: last,
                nextClientPruneAt: next,
                remainingMs: remain,
                remainingDays: Math.ceil(remain / (24 * 60 * 60 * 1000)),
                due: remain <= 0
            };
        }

        function status() {
            return {
                available: !!current,
                manifestVersion: current && (current.manifestVersion || current.version || ''),
                generatedAt: current && current.generatedAt || '',
                changedResources: changedResources.slice(0, 50),
                changedCount: changedResources.length,
                prune: countdown(),
                cache: window.EntryCache && typeof window.EntryCache.info === 'function' ? window.EntryCache.info() : null
            };
        }

        return {
            load: load,
            ensureLoaded: ensureLoaded,
            current: function () { return current; },
            resourceForRef: resourceForRef,
            tokenForRef: tokenForRef,
            cacheKeyForRef: cacheKeyForRef,
            cacheKeyForUrl: cacheKeyForUrl,
            manifestToken: manifestToken,
            resourceKeyForRef: resourceKeyForRef,
            addRevisionParam: addRevisionParam,
            maybePrune: maybePrune,
            countdown: countdown,
            status: status
        };
    }

    window.RevisionManifest = window.RevisionManifest || createRevisionManifestService();

    function createEntryStore() {
        var jsonCache = {};
        var flagUrlCache = {};
        var fileUrlCache = {};
        var imageReadyCache = {};
        var imageObjectCache = {};
        var imageDisplayUrlCache = {};
        var imagePromiseCache = {};
        var rawPromiseCache = {};
        var textCache = {};
        var textPromiseCache = {};

        function fetchJsonRef(ref, options) {
            var key = normalizeRefKey(ref);
            var cacheKey;
            var promiseKey;
            var url;
            var resourceKey;
            var token;
            if (!key) return Promise.reject(new Error('empty json ref'));
            cacheKey = window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForRef === 'function' ? window.RevisionManifest.cacheKeyForRef(ref, 'json') : '';
            promiseKey = cacheKey ? (key + '@' + cacheKey) : key;
            if (jsonCache[promiseKey]) return Promise.resolve(jsonCache[promiseKey].data);
            if (rawPromiseCache[promiseKey]) return rawPromiseCache[promiseKey];
            url = rawUrlForRef(ref, 'application/json');
            if (window.RevisionManifest && typeof window.RevisionManifest.addRevisionParam === 'function') {
                url = window.RevisionManifest.addRevisionParam(url, ref);
            }
            resourceKey = window.RevisionManifest && typeof window.RevisionManifest.resourceKeyForRef === 'function' ? window.RevisionManifest.resourceKeyForRef(ref) : key;
            token = window.RevisionManifest && typeof window.RevisionManifest.tokenForRef === 'function' ? window.RevisionManifest.tokenForRef(ref) : '';
            if (cacheKey && !(options && options.noStore) && window.EntryCache && typeof window.EntryCache.getText === 'function') {
                rawPromiseCache[promiseKey] = window.EntryCache.getText(cacheKey).then(function (cachedText) {
                    if (cachedText !== null && cachedText !== undefined) {
                        var cachedData = cachedText && cachedText.trim() ? JSON.parse(cachedText) : {};
                        jsonCache[promiseKey] = { key: promiseKey, ref: ref, url: url, data: cachedData, loadedAt: now(), persistent: true };
                        jsonCache[key] = jsonCache[promiseKey];
                        return cachedData;
                    }
                    return fetch(url, {
                        credentials: 'same-origin',
                        cache: 'force-cache'
                    }).then(function (res) {
                        if (!res.ok) throw new Error('HTTP ' + res.status);
                        return res.text();
                    }).then(function (text) {
                        var data = text && text.trim() ? JSON.parse(text) : {};
                        jsonCache[promiseKey] = { key: promiseKey, ref: ref, url: url, data: data, loadedAt: now() };
                        jsonCache[key] = jsonCache[promiseKey];
                        window.EntryCache.putText(cacheKey, text, { resourceKey: resourceKey, token: token });
                        return data;
                    });
                });
                return rawPromiseCache[promiseKey];
            }
            rawPromiseCache[promiseKey] = fetch(url, {
                credentials: 'same-origin',
                cache: options && options.noStore ? 'no-store' : 'force-cache'
            }).then(function (res) {
                if (!res.ok) throw new Error('HTTP ' + res.status);
                return res.text();
            }).then(function (text) {
                var data = text && text.trim() ? JSON.parse(text) : {};
                jsonCache[promiseKey] = { key: promiseKey, ref: ref, url: url, data: data, loadedAt: now() };
                jsonCache[key] = jsonCache[promiseKey];
                return data;
            });
            return rawPromiseCache[promiseKey];
        }

        function getJsonSync(ref) {
            var key = normalizeRefKey(ref);
            return key && jsonCache[key] ? jsonCache[key].data : null;
        }

        function setJsonRef(ref, data) {
            var key = normalizeRefKey(ref);
            if (!key) return;
            jsonCache[key] = { key: key, ref: ref, url: rawUrlForRef(ref, 'application/json'), data: data, loadedAt: now() };
        }

        function normalizeFile(value) {
            return String(value || '')
                .replace(/^(?:file|파일):/i, '')
                .trim();
        }

        function fileKey(value) {
            return normalizeFile(value).replace(/_/g, ' ').replace(/\s+/g, ' ').toLowerCase();
        }

        function setFlagUrl(file, url) {
            var key = fileKey(file);
            if (!key) return;
            flagUrlCache[key] = String(url || '');
        }

        function getFlagUrl(file) {
            var key = fileKey(file);
            return key ? (flagUrlCache[key] || '') : '';
        }

        function resolveFlagUrls(files) {
            var clean = unique((files || []).map(normalizeFile).filter(Boolean));

            function cacheKeyForFile(file) {
                return window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForRef === 'function' ? window.RevisionManifest.cacheKeyForRef('File:' + file, 'flagurl') : '';
            }

            function resourceKeyForFile(file) {
                return window.RevisionManifest && typeof window.RevisionManifest.resourceKeyForRef === 'function' ? window.RevisionManifest.resourceKeyForRef('File:' + file) : ('file:' + fileKey(file));
            }

            function tokenForFile(file) {
                return window.RevisionManifest && typeof window.RevisionManifest.tokenForRef === 'function' ? window.RevisionManifest.tokenForRef('File:' + file) : '';
            }

            function hydrateCachedFlagUrl(file) {
                var key = fileKey(file);
                var cacheKey = cacheKeyForFile(file);
                if (!key || flagUrlCache[key] !== undefined || !cacheKey || !window.EntryCache || typeof window.EntryCache.getText !== 'function') {
                    return Promise.resolve(false);
                }
                return window.EntryCache.getText(cacheKey).then(function (cachedUrl) {
                    if (cachedUrl !== null && cachedUrl !== undefined) {
                        flagUrlCache[key] = String(cachedUrl || '');
                        return true;
                    }
                    return false;
                }).catch(function () { return false; });
            }

            return Promise.all(clean.map(hydrateCachedFlagUrl)).then(function () {
                var pending = clean.filter(function (file) {
                    return getFlagUrl(file) === '' && flagUrlCache[fileKey(file)] === undefined;
                });
                var chunks = [];

                while (pending.length) chunks.push(pending.splice(0, 20));
                if (!chunks.length) return flagUrlCache;

                return Promise.all(chunks.map(function (chunk) {
                    var titleToKey = {};
                    var keyToFile = {};
                    var titles = [];
                    chunk.forEach(function (file) {
                        var key = fileKey(file);
                        if (!key) return;
                        titleToKey[fileKey('File:' + file)] = key;
                        titleToKey[fileKey('파일:' + file)] = key;
                        keyToFile[key] = file;
                        titles.push('File:' + file);
                        titles.push('파일:' + file);
                    });
                    return fetchApi({
                        action: 'query',
                        format: 'json',
                        formatversion: '2',
                        redirects: '1',
                        prop: 'imageinfo',
                        iiprop: 'url|sha1|timestamp|size',
                        iiurlwidth: '16',
                        titles: titles.join('|')
                    }).then(function (json) {
                        var pages = (json && json.query && json.query.pages) || [];
                        var seen = {};
                        pages.forEach(function (page) {
                            var key = titleToKey[fileKey(page && page.title)] || fileKey(page && page.title);
                            var file = keyToFile[key] || (page && page.title || '').replace(/^(?:File|파일):/i, '');
                            var imageinfo = page && page.imageinfo && page.imageinfo[0];
                            var url;
                            var rev;
                            var sep;
                            var cacheKey;
                            if (!key) return;
                            seen[key] = true;
                            url = imageinfo && (imageinfo.thumburl || imageinfo.url) ? (imageinfo.thumburl || imageinfo.url) : '';
                            if (url) {
                                rev = imageinfo && (imageinfo.sha1 || imageinfo.timestamp || imageinfo.size) ? (imageinfo.sha1 || imageinfo.timestamp || imageinfo.size) : '';
                                if (rev && !/[?&]_entryFileRev=/.test(url)) {
                                    sep = url.indexOf('?') === -1 ? '?' : '&';
                                    url += sep + '_entryFileRev=' + encodeURIComponent(String(rev));
                                }
                            }
                            flagUrlCache[key] = url;
                            cacheKey = cacheKeyForFile(file);
                            if (cacheKey && window.EntryCache && typeof window.EntryCache.putText === 'function') {
                                window.EntryCache.putText(cacheKey, url || '', {
                                    resourceKey: resourceKeyForFile(file),
                                    token: tokenForFile(file),
                                    kind: 'flagurl',
                                    contentType: 'text/plain; charset=UTF-8'
                                });
                            }
                        });
                        chunk.forEach(function (file) {
                            var key = fileKey(file);
                            if (key && !seen[key] && flagUrlCache[key] === undefined) flagUrlCache[key] = '';
                        });
                    }).catch(function () {
                        chunk.forEach(function (file) {
                            var key = fileKey(file);
                            if (key && flagUrlCache[key] === undefined) flagUrlCache[key] = '';
                        });
                    });
                })).then(function () { return flagUrlCache; });
            });
        }

        function normalizeGenericFileTitle(value) {
            var text = String(value || '').trim();
            var match;
            var i;

            if (!text) return '';
            for (i = 0; i < 4; i += 1) {
                try {
                    if (/%[0-9a-f]{2}/i.test(text)) text = decodeURIComponent(text);
                } catch (err) {
                    break;
                }
            }
            match = text.match(/[?&]title=([^&#]+)/i);
            if (match) text = match[1];
            text = text.replace(/^https?:\/\/[^/]+/i, '').replace(/^\/+/, '').replace(/^index\.php\/?/i, '').replace(/^wiki\/?/i, '').trim();
            match = text.match(/(?:^|\/)(?:(?:Special|특수)\s*[:/]\s*)?(?:Redirect|넘겨주기)\s*\/\s*file\s*\/(.+)$/i);
            if (match) text = match[1];
            text = text.replace(/^(?:File|파일|Image|이미지)\s*:/i, '').replace(/^:+/, '').trim();
            return text;
        }

        function isFileRef(value) {
            var text = String(value || '').trim();
            return /^(?:file|파일)\s*:/i.test(text) || /(?:^|\/)(?:(?:Special|특수)\s*[:/]\s*)?(?:Redirect|넘겨주기)\s*\/\s*file\s*\//i.test(text);
        }

        function fileUrlKey(value) {
            return normalizeGenericFileTitle(value).replace(/_/g, ' ').replace(/\s+/g, ' ').toLowerCase();
        }

        function stableDirectImageUrl(url) {
            var text = String(url || '').trim();
            var separator;
            var bust;
            if (!text) return '';
            if (/[?&]_entryAsset=/.test(text) || /[?&]_=/.test(text)) return text;
            bust = String(BUILD_ID || 'entry');
            separator = text.indexOf('?') === -1 ? '?' : '&';
            return text + separator + '_entryAsset=' + encodeURIComponent(bust);
        }

        function resolveFileUrl(ref) {
            var original = String(ref || '').trim();
            var file;
            var key;
            var cacheKey;
            var resourceKey;
            var token;
            if (!original) return Promise.resolve('');
            if (!isFileRef(original)) return Promise.resolve(stableDirectImageUrl(original));
            file = normalizeGenericFileTitle(original);
            key = fileUrlKey(file);
            if (!file || !key) return Promise.resolve(stableDirectImageUrl(original));
            if (fileUrlCache[key]) return Promise.resolve(fileUrlCache[key]);
            cacheKey = window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForRef === 'function' ? window.RevisionManifest.cacheKeyForRef('File:' + file, 'fileurl') : '';
            resourceKey = window.RevisionManifest && typeof window.RevisionManifest.resourceKeyForRef === 'function' ? window.RevisionManifest.resourceKeyForRef('File:' + file) : ('file:' + key);
            token = window.RevisionManifest && typeof window.RevisionManifest.tokenForRef === 'function' ? window.RevisionManifest.tokenForRef('File:' + file) : '';
            if (cacheKey && window.EntryCache && typeof window.EntryCache.getText === 'function') {
                return window.EntryCache.getText(cacheKey).then(function (cachedUrl) {
                    if (cachedUrl !== null && cachedUrl !== undefined) {
                        fileUrlCache[key] = String(cachedUrl || '');
                        return fileUrlCache[key];
                    }
                    return fetchApi({
                        action: 'query',
                        format: 'json',
                        formatversion: '2',
                        redirects: '1',
                        prop: 'imageinfo',
                        iiprop: 'url|sha1|timestamp|size|mime',
                        titles: 'File:' + file
                    }).then(function (json) {
                        var pages = (json && json.query && json.query.pages) || [];
                        var info = pages[0] && pages[0].imageinfo && pages[0].imageinfo[0] ? pages[0].imageinfo[0] : null;
                        var url = info && info.url ? info.url : original;
                        var rev = info && (info.sha1 || info.timestamp || info.size) ? (info.sha1 || info.timestamp || info.size) : String(BUILD_ID || 'entry-file');
                        var separator = url.indexOf('?') === -1 ? '?' : '&';
                        var resolved = url + separator + '_entryFileRev=' + encodeURIComponent(String(rev));
                        fileUrlCache[key] = resolved;
                        window.EntryCache.putText(cacheKey, resolved, { resourceKey: resourceKey, token: token, kind: 'fileurl', contentType: 'text/plain; charset=UTF-8' });
                        return resolved;
                    });
                }).catch(function () {
                    return stableDirectImageUrl(original);
                });
            }
            return fetchApi({
                action: 'query',
                format: 'json',
                formatversion: '2',
                redirects: '1',
                prop: 'imageinfo',
                iiprop: 'url|sha1|timestamp|size|mime',
                titles: 'File:' + file
            }).then(function (json) {
                var pages = (json && json.query && json.query.pages) || [];
                var info = pages[0] && pages[0].imageinfo && pages[0].imageinfo[0] ? pages[0].imageinfo[0] : null;
                var url = info && info.url ? info.url : original;
                var rev = info && (info.sha1 || info.timestamp || info.size) ? (info.sha1 || info.timestamp || info.size) : String(BUILD_ID || 'entry-file');
                var separator = url.indexOf('?') === -1 ? '?' : '&';
                var resolved = url + separator + '_entryFileRev=' + encodeURIComponent(String(rev));
                fileUrlCache[key] = resolved;
                return resolved;
            }).catch(function () {
                return stableDirectImageUrl(original);
            });
        }

        function preloadImageUrl(url, options) {
            var key = String(url || '').trim();
            var cacheKey;
            var sourcePromise;
            var persistent = !(options && options.persistent === false);
            if (!key) return Promise.resolve(false);
            if (imageReadyCache[key]) return Promise.resolve(true);
            if (imagePromiseCache[key]) return imagePromiseCache[key];

            cacheKey = persistent && window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForUrl === 'function' ? window.RevisionManifest.cacheKeyForUrl(key, 'image') : '';
            sourcePromise = Promise.resolve('');
            if (cacheKey && window.EntryCache && typeof window.EntryCache.fetchBlobUrl === 'function') {
                sourcePromise = window.EntryCache.fetchBlobUrl(key, cacheKey, {
                    resourceKey: '',
                    token: '',
                    kind: 'image'
                }).catch(function () { return ''; });
            }

            imagePromiseCache[key] = sourcePromise.then(function (cachedObjectUrl) {
                return new Promise(function (resolve) {
                    var img = new Image();
                    var settled = false;
                    var src = cachedObjectUrl || key;
                    function finish(ok) {
                        if (settled) return;
                        settled = true;
                        if (ok) {
                            imageReadyCache[key] = true;
                            imageReadyCache[src] = true;
                            imageObjectCache[key] = img;
                            imageObjectCache[src] = img;
                            imageDisplayUrlCache[key] = src;
                            imageDisplayUrlCache[src] = src;
                        }
                        resolve(!!ok);
                    }
                    img.onload = function () {
                        if (img.decode) {
                            img.decode().then(function () { finish(true); }).catch(function () { finish(true); });
                        } else {
                            finish(true);
                        }
                    };
                    img.onerror = function () {
                        if (src !== key) {
                            src = key;
                            img.src = key;
                            return;
                        }
                        finish(false);
                    };
                    img.decoding = 'async';
                    img.loading = 'eager';
                    img.src = src;
                    if (img.complete && img.naturalWidth) {
                        if (img.decode) img.decode().then(function () { finish(true); }).catch(function () { finish(true); });
                        else finish(true);
                    }
                });
            });
            return imagePromiseCache[key];
        }

        function preloadImages(urls, options) {
            var list = unique((urls || []).filter(Boolean));
            var limit = options && Number(options.limit);
            var concurrency = Math.max(1, Math.min(48, Number(options && options.concurrency) || 24));
            var index = 0;
            var ok = 0;
            var fail = 0;
            if (Number.isFinite(limit) && limit > 0) list = list.slice(0, limit);
            if (!list.length) return Promise.resolve({ total: 0, ok: 0, fail: 0 });
            return new Promise(function (resolve) {
                function pump() {
                    while (index < list.length && concurrency > 0) {
                        (function (url) {
                            concurrency -= 1;
                            preloadImageUrl(url, options || {}).then(function (result) {
                                if (result) ok += 1;
                                else fail += 1;
                            }).catch(function () {
                                fail += 1;
                            }).then(function () {
                                concurrency += 1;
                                if (index >= list.length && ok + fail >= list.length) resolve({ total: list.length, ok: ok, fail: fail });
                                else pump();
                            });
                        })(list[index++]);
                    }
                }
                pump();
            });
        }

        function isImageReady(url) {
            var key = String(url || '').trim();
            return !!(key && imageReadyCache[key]);
        }

        function getImageElement(url) {
            var key = String(url || '').trim();
            return key ? (imageObjectCache[key] || null) : null;
        }

        function getImageDisplayUrl(url) {
            var key = String(url || '').trim();
            return key ? (imageDisplayUrlCache[key] || key) : '';
        }

        function normalizeUrlKey(url) {
            var text = String(url || '').trim();
            var a;
            if (!text) return '';
            try {
                a = document.createElement('a');
                a.href = text;
                text = a.pathname + (a.search || '');
            } catch (err) {}
            try {
                text = decodeURI(text);
            } catch (err2) {}
            text = text.replace(/([?&])_=[^&]*/g, '$1').replace(/[?&]$/, '');
            text = text.replace(/_/g, '_');
            return text;
        }

        function fetchTextUrl(url, options) {
            var key = normalizeUrlKey(url);
            var cacheKey;
            var resourceRef;
            var resourceKey;
            var token;
            if (!key) return Promise.reject(new Error('empty text url'));
            if (textCache[key]) return Promise.resolve(textCache[key].text);
            if (textPromiseCache[key]) return textPromiseCache[key];
            resourceRef = options && options.resourceRef ? options.resourceRef : (options && options.ref ? options.ref : '');
            cacheKey = resourceRef && window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForRef === 'function' ? window.RevisionManifest.cacheKeyForRef(resourceRef, 'text') : '';
            if (!cacheKey && window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForUrl === 'function') cacheKey = window.RevisionManifest.cacheKeyForUrl(url, 'text');
            resourceKey = resourceRef && window.RevisionManifest && typeof window.RevisionManifest.resourceKeyForRef === 'function' ? window.RevisionManifest.resourceKeyForRef(resourceRef) : ('url:' + key);
            token = resourceRef && window.RevisionManifest && typeof window.RevisionManifest.tokenForRef === 'function' ? window.RevisionManifest.tokenForRef(resourceRef) : '';
            if (cacheKey && !(options && options.noStore) && window.EntryCache && typeof window.EntryCache.getText === 'function') {
                textPromiseCache[key] = window.EntryCache.getText(cacheKey).then(function (cachedText) {
                    if (cachedText !== null && cachedText !== undefined) {
                        textCache[key] = { key: key, url: url, text: cachedText, loadedAt: now(), persistent: true };
                        return cachedText;
                    }
                    return fetch(url, {
                        credentials: 'same-origin',
                        cache: 'force-cache'
                    }).then(function (res) {
                        if (!res.ok) throw new Error('HTTP ' + res.status);
                        return res.text();
                    }).then(function (text) {
                        textCache[key] = { key: key, url: url, text: text, loadedAt: now() };
                        window.EntryCache.putText(cacheKey, text, { resourceKey: resourceKey, token: token, kind: 'text', contentType: 'text/html; charset=UTF-8' });
                        return text;
                    });
                });
                return textPromiseCache[key];
            }
            textPromiseCache[key] = fetch(url, {
                credentials: 'same-origin',
                cache: options && options.noStore ? 'no-store' : 'force-cache'
            }).then(function (res) {
                if (!res.ok) throw new Error('HTTP ' + res.status);
                return res.text();
            }).then(function (text) {
                textCache[key] = { key: key, url: url, text: text, loadedAt: now() };
                return text;
            });
            return textPromiseCache[key];
        }

        function getTextSync(url) {
            var key = normalizeUrlKey(url);
            return key && textCache[key] ? textCache[key].text : '';
        }

        function setTextUrl(url, text) {
            var key = normalizeUrlKey(url);
            if (!key) return;
            textCache[key] = { key: key, url: url, text: String(text || ''), loadedAt: now() };
        }

        function cacheInfo() {
            return {
                json: Object.keys(jsonCache).length,
                jsonKeys: Object.keys(jsonCache),
                flags: Object.keys(flagUrlCache).length,
                files: Object.keys(fileUrlCache).length,
                images: Object.keys(imageReadyCache).length,
                retainedImages: Object.keys(imageObjectCache).length,
                displayImages: Object.keys(imageDisplayUrlCache).length,
                text: Object.keys(textCache).length,
                textKeys: Object.keys(textCache)
            };
        }

        return {
            fetchJsonRef: fetchJsonRef,
            getJsonSync: getJsonSync,
            setJsonRef: setJsonRef,
            normalizeRefKey: normalizeRefKey,
            rawUrlForRef: rawUrlForRef,
            revisionUrlForRef: function (ref, ctype) {
                var url = rawUrlForRef(ref, ctype);
                if (window.RevisionManifest && typeof window.RevisionManifest.addRevisionParam === 'function') {
                    url = window.RevisionManifest.addRevisionParam(url, ref);
                }
                return url;
            },
            resolveFlagUrls: resolveFlagUrls,
            setFlagUrl: setFlagUrl,
            getFlagUrl: getFlagUrl,
            resolveFileUrl: resolveFileUrl,
            preloadImageUrl: preloadImageUrl,
            preloadImages: preloadImages,
            isImageReady: isImageReady,
            getImageElement: getImageElement,
            getImageDisplayUrl: getImageDisplayUrl,
            fetchTextUrl: fetchTextUrl,
            getTextSync: getTextSync,
            setTextUrl: setTextUrl,
            stableDirectImageUrl: stableDirectImageUrl,
            cacheInfo: cacheInfo
        };
    }

    window.EntryStore = window.EntryStore || createEntryStore();

    function updateBootProgress(done, total, label) {
        var pct = total ? Math.max(0, Math.min(100, Math.round((done / total) * 100))) : 0;
        if (bootProgressNode) bootProgressNode.textContent = pct + '%';
        if (bootFillNode) bootFillNode.style.width = pct + '%';
        if (bootDetailNode && label) bootDetailNode.textContent = label;
    }

    function adoptBootScreen(node) {
        if (!node) return null;
        bootNode = node;
        bootStatusNode = bootNode.querySelector('.boot-gate-status');
        bootProgressNode = bootNode.querySelector('.boot-gate-progress');
        bootDetailNode = bootNode.querySelector('.boot-gate-detail');
        bootFillNode = bootNode.querySelector('.boot-gate-meter-fill');
        bootNode.classList.add('is-active');
        bootNode.classList.remove('is-complete');
        return bootNode;
    }

    function ensureBootScreen(options) {
        var panel;
        var header;
        var meter;
        var existing;
        var decoLayer;
        var close;
        var previewMode;
        options = options || {};
        previewMode = !!options.preview;
        if (bootNode && bootNode.parentNode) return bootNode;
        if (!document.body) return null;

        if (BOOT_EXCLUDED_PAGE && !previewMode) return null;
        if (!previewMode) activateBootSurface();

        existing = document.getElementById('boot-gate-screen') || (!previewMode && window.__BootGatePrelude && window.__BootGatePrelude.ensure ? window.__BootGatePrelude.ensure() : null);
        if (existing) return adoptBootScreen(existing);

        bootNode = document.createElement('div');
        bootNode.id = 'boot-gate-screen';
        bootNode.className = 'boot-gate-screen is-active';
        bootNode.setAttribute('role', 'status');
        bootNode.setAttribute('aria-live', 'polite');

        panel = document.createElement('div');
        panel.className = 'boot-gate-panel';

        header = document.createElement('div');
        header.className = 'boot-gate-title';
        header.textContent = 'ARCHIVE INITIALIZATION';

        bootStatusNode = document.createElement('div');
        bootStatusNode.className = 'boot-gate-status';
        bootStatusNode.textContent = 'Preparing entry systems';

        meter = document.createElement('div');
        meter.className = 'boot-gate-meter';
        bootFillNode = document.createElement('div');
        bootFillNode.className = 'boot-gate-meter-fill';
        meter.appendChild(bootFillNode);

        bootProgressNode = document.createElement('div');
        bootProgressNode.className = 'boot-gate-progress';
        bootProgressNode.textContent = '0%';

        bootDetailNode = document.createElement('div');
        bootDetailNode.className = 'boot-gate-detail';
        bootDetailNode.textContent = 'loading manifest';

        close = document.createElement('button');
        close.type = 'button';
        close.className = 'boot-gate-close';
        close.setAttribute('aria-label', 'Close boot preview');
        close.textContent = '×';
        close.addEventListener('click', function () { hideBootScreen({ force: true }); });

        decoLayer = document.createElement('div');
        decoLayer.className = 'boot-gate-decoration-layer';
        decoLayer.setAttribute('data-decoration-target', 'boot-gate');
        decoLayer.setAttribute('aria-hidden', 'true');

        panel.appendChild(header);
        panel.appendChild(bootStatusNode);
        panel.appendChild(meter);
        panel.appendChild(bootProgressNode);
        panel.appendChild(bootDetailNode);
        bootNode.appendChild(decoLayer);
        bootNode.appendChild(panel);
        bootNode.appendChild(close);
        document.body.appendChild(bootNode);
        return bootNode;
    }

    function buildLoginUrl() {
        var pageName = String(readConfig('wgPageName', '') || '').trim();
        var params = {};

        if (pageName && !isAuthenticationPage() && !isCreateAccountPage()) params.returnto = pageName;
        try {
            if (mw && mw.util && typeof mw.util.getUrl === 'function') {
                return mw.util.getUrl('Special:UserLogin', params);
            }
        } catch (err) {}

        return '/index.php?title=Special%3AUserLogin' + (params.returnto ? '&returnto=' + encodeURIComponent(params.returnto) : '');
    }

    function ensureLoginGateAction(panel) {
        var copy;
        var action;

        if (loginGateActionNode && loginGateActionNode.parentNode) return loginGateActionNode;
        loginGateActionNode = document.createElement('div');
        loginGateActionNode.className = 'boot-gate-login';

        copy = document.createElement('div');
        copy.className = 'boot-gate-login-copy';
        copy.textContent = 'SIGN IN TO ENTER THE WIKI.';

        action = document.createElement('a');
        action.className = 'boot-gate-login-action';
        action.href = buildLoginUrl();
        action.textContent = 'LOGIN';
        action.setAttribute('role', 'button');

        loginGateActionNode.appendChild(copy);
        loginGateActionNode.appendChild(action);
        panel.appendChild(loginGateActionNode);
        return loginGateActionNode;
    }

    function showLoginGate() {
        var node = ensureBootScreen();
        var panel;
        var title;
        var action;

        if (!node || !requiresLoginGate()) return false;
        activateBootSurface();
        loginGateLocked = true;
        node.classList.remove('is-complete');
        node.classList.add('is-active', 'is-login-required');
        node.setAttribute('role', 'dialog');
        node.setAttribute('aria-modal', 'true');
        node.setAttribute('aria-live', 'off');

        panel = node.querySelector('.boot-gate-panel');
        title = node.querySelector('.boot-gate-title');
        if (title) title.textContent = 'ACCOUNT AUTHENTICATION';
        if (bootStatusNode) bootStatusNode.textContent = 'LOGIN REQUIRED';
        if (bootDetailNode) bootDetailNode.textContent = '';
        if (bootProgressNode) bootProgressNode.textContent = '';
        if (bootFillNode) bootFillNode.style.width = '100%';

        action = panel ? ensureLoginGateAction(panel).querySelector('.boot-gate-login-action') : null;
        if (action) {
            action.href = buildLoginUrl();
            window.requestAnimationFrame(function () {
                try { action.focus({ preventScroll: true }); }
                catch (err) { try { action.focus(); } catch (ignore) {} }
            });
        }
        return true;
    }

    function hideBootScreen(options) {
        var node = bootNode || document.getElementById('boot-gate-screen');
        options = options || {};
        if (loginGateLocked && requiresLoginGate() && !options.force) return false;
        if (!node) {
            document.documentElement.classList.remove('boot-gate-active');
            if (document.body) document.body.classList.remove('boot-gate-active');
            return true;
        }
        node.classList.add('is-complete');
        node.classList.remove('is-active');
        window.setTimeout(function () {
            if (node.parentNode) node.parentNode.removeChild(node);
            if (bootNode === node) bootNode = null;
            loginGateActionNode = null;
            document.documentElement.classList.remove('boot-gate-active');
            if (document.body) document.body.classList.remove('boot-gate-active');
        }, 240);
        return true;
    }

    function collectFlagsFromNationPayload(payload) {
        var files = [];
        function add(value) {
            if (!value) return;
            if (typeof value === 'string') {
                files.push(value);
                return;
            }
            if (typeof value === 'object') files.push(value.file || value.flag_file || value.flag || value.flag_title || '');
        }
        function scanItem(item) {
            if (!item || typeof item !== 'object') return;
            if (Array.isArray(item.flags)) item.flags.forEach(add);
            add(item.flag_file || item.flag || item.flag_title || '');
        }
        (payload && payload.continents || []).forEach(function (continent) {
            (continent.regions || []).forEach(function (region) {
                (region.items || []).forEach(scanItem);
            });
        });
        return unique(files);
    }

    function collectFlagsFromLinkMap(payload) {
        var files = [];
        var source = payload && payload.items ? payload.items : {};
        Object.keys(source || {}).forEach(function (key) {
            var item = source[key];
            if (!item || typeof item !== 'object') return;
            files.push(item.flag_file || item.flag || item.flag_title || '');
        });
        return unique(files);
    }

    function prewarmImages(urls, limit) {
        return window.EntryStore.preloadImages(urls, {
            limit: Number(limit) > 0 ? Number(limit) : 0,
            concurrency: 16,
            persistent: false
        });
    }

    function getDecorationRuntime() {
        return window.Decorations || window.CLBI_DECORATIONS || null;
    }

    function waitForDecorationRuntime() {
        return new Promise(function (resolve) {
            var tries = 0;
            function tick() {
                var runtime = getDecorationRuntime();
                if (runtime) return resolve(runtime);
                tries += 1;
                if (tries > 40) return resolve(null);
                window.setTimeout(tick, 25);
            }
            tick();
        });
    }

    function matchesDecorationEntry(entry, filter) {
        var era = String(filter && filter.era || '').trim();
        var page = String(filter && filter.page || '').trim();
        var entryPage = String(entry && entry.page || '').replace(/_/g, ' ').trim();
        if (!entry || typeof entry !== 'object') return false;
        if (page && entryPage && entryPage !== page) return false;
        if (era && String(entry.era || '').trim() && String(entry.era || '').trim() !== era) return false;
        return true;
    }

    function prepareDecorationSet(task, level) {
        var ref = task.ref || 'MediaWiki:Decorations.json';
        return window.EntryStore.fetchJsonRef(ref, { noStore: !!task.noStore }).then(function (registry) {
            var list = registry && Array.isArray(registry.decorations) ? registry.decorations : [];
            var pixelRefs = [];
            list.forEach(function (entry) {
                var type = String(entry && entry.assetType || '').toLowerCase();
                var asset = String(entry && (entry.asset || entry.src) || '').trim();
                if (!asset) return;
                if (type !== 'pixel-json' && !/\.json(?:[?#].*)?$/i.test(asset)) return;
                if (!matchesDecorationEntry(entry, task)) return;
                pixelRefs.push(asset);
            });
            if (level !== 'full' || task.preparePixels === false || !pixelRefs.length) return registry;
            return waitForDecorationRuntime().then(function (runtime) {
                if (!runtime || typeof runtime.preparePixelCanvas !== 'function') {
                    return Promise.all(pixelRefs.map(function (pixelRef) {
                        return window.EntryStore.fetchJsonRef(pixelRef).catch(function () { return null; });
                    })).then(function () { return registry; });
                }
                return Promise.all(pixelRefs.map(function (pixelRef) {
                    return runtime.preparePixelCanvas(pixelRef).catch(function () { return null; });
                })).then(function () { return registry; });
            });
        });
    }

    function prepareNationsEra(task, level) {
        var era = String(task.era || '1950');
        var listRef = task.listRef || ('MediaWiki:' + era + '_Nation_List.json');
        var linkRef = task.linkMapRef || ('MediaWiki:' + era + '_Nation_Link_Map.json');
        var jsonPhaseId = BootPerf.start('nations-era json fetch', { era: era, level: level, listRef: listRef, linkRef: linkRef });
        var listPromise = window.EntryStore.fetchJsonRef(listRef).catch(function () { return null; });
        var linkPromise = window.EntryStore.fetchJsonRef(linkRef).catch(function () { return null; });

        return Promise.all([listPromise, linkPromise]).then(function (results) {
            BootPerf.end(jsonPhaseId, { ok: true });
            var files;
            var flagUrls;
            if (level !== 'full' && level !== 'warm') return results;
            files = unique(collectFlagsFromNationPayload(results[0]).concat(collectFlagsFromLinkMap(results[1])));
            return BootPerf.measure('nations-era flag url resolve', { era: era, count: files.length }, function () {
                return window.EntryStore.resolveFlagUrls(files);
            }).then(function () {
                if (level === 'warm') {
                    /*
                     * Warm tab contract — 20260708.
                     *
                     * A previous tab already stored the same-revision flag URL and image
                     * blobs.  Re-decoding every flag here makes the second tab feel as slow
                     * as the first one.  In warm mode we only hydrate the flag URL table from
                     * EntryCache so NationsPanel can render stable URLs immediately; image
                     * decode remains demand-driven by the live panel instead of blocking the
                     * boot screen.
                     */
                    return results;
                }
                flagUrls = files.map(function (file) { return window.EntryStore.getFlagUrl(file); }).filter(Boolean);
                /*
                 * 20260710: Flag URLs are part of the entry contract, but decoding every
                 * flag image is not.  The 1950 list has more than 150 flags, and waiting
                 * for all image decodes kept the public boot gate open for several seconds.
                 * Keep revision-aware URLs ready for the panel, then let the browser load
                 * the actual images from the live DOM.  A low-priority background warm-up
                 * may run after the boot gate has opened, so it never competes with the
                 * current entry surface or the globe ready contract.
                 */
                BootPerf.mark('nations-era flag image prewarm skipped', {
                    era: era,
                    count: flagUrls.length,
                    limit: task.flagLimit == null ? 0 : Number(task.flagLimit),
                    reason: 'deferred-after-boot-gate'
                });
                if (flagUrls.length && task.deferFlagImages !== false) {
                    deferredEntryWarmups.push(function () {
                        return BootPerf.measure('deferred nations-era flag image prewarm', {
                            era: era,
                            count: flagUrls.length,
                            limit: task.flagLimit == null ? 0 : Number(task.flagLimit)
                        }, function () {
                            return prewarmImages(flagUrls, task.flagLimit == null ? 0 : Number(task.flagLimit));
                        });
                    });
                }
                return results;
            });
        });
    }

    function prepareGlobeSharedAssets(task, level) {
        var refs = Array.isArray(task && task.assets) ? task.assets : [];
        if (!refs.length) return Promise.resolve(null);
        return BootPerf.measure('globe-shared url resolve', { count: refs.length, level: level }, function () {
            return Promise.all(refs.map(function (ref) {
                return window.EntryStore.resolveFileUrl(ref).catch(function () { return ''; });
            }));
        }).then(function (urls) {
            urls = urls.filter(Boolean);
            /*
             * Globe shared assets are heavy 6K texture sources.  The live
             * NationsGlobe ready contract already waits for the actual Three.js
             * texture path, so decoding the same images here only duplicates work
             * and holds the boot screen.  Keep revision-aware URL resolution in the
             * entry ledger, but make the image warm-up non-blocking.
             */
            BootPerf.mark('globe-shared image prewarm skipped', {
                count: urls.length,
                level: level,
                reason: 'deferred-to-nations-globe-ready-contract'
            });
            window.setTimeout(function () {
                if (!window.EntryStore || typeof window.EntryStore.preloadImages !== 'function') return;
                window.EntryStore.preloadImages(urls, {
                    limit: task.imageLimit == null ? 0 : Number(task.imageLimit),
                    concurrency: Math.max(1, Math.min(16, Number(task.concurrency) || 4)),
                    persistent: false
                }).catch(function () {});
            }, 0);
            return urls;
        });
    }

    function prepareImageAssets(task, level) {
        var refs = Array.isArray(task && task.assets) ? task.assets : [];
        var full = level === 'full';
        var exposeAs = String(task && task.exposeAs || '').trim();
        if (!refs.length) return Promise.resolve(null);
        return BootPerf.measure('image-assets url resolve', { count: refs.length, exposeAs: exposeAs, level: level }, function () {
            return Promise.all(refs.map(function (ref) {
                return window.EntryStore.resolveFileUrl(ref).catch(function () { return ''; });
            }));
        }).then(function (urls) {
            urls = urls.filter(Boolean);
            if (exposeAs === 'nationsGlobeLoadingGif') {
                window.NationsGlobeLoadingGifRef = refs[0] || '';
                window.NationsGlobeLoadingGifUrl = urls[0] || '';
                window.NationsGlobeLoadingGifFile = 'Gfx-vhs-glitch-001.gif';
            }
            if (!full) return urls;
            return BootPerf.measure('image-assets image prewarm', { count: urls.length, exposeAs: exposeAs, limit: task.imageLimit == null ? 0 : Number(task.imageLimit), concurrency: Math.max(1, Math.min(16, Number(task.concurrency) || 2)) }, function () {
                return window.EntryStore.preloadImages(urls, {
                    limit: task.imageLimit == null ? 0 : Number(task.imageLimit),
                    concurrency: Math.max(1, Math.min(16, Number(task.concurrency) || 2))
                });
            }).then(function () { return urls; });
        });
    }

    function prepareHtmlEntry(task) {
        var url = String(task && (task.url || task.ref) || '').trim();
        if (!url) return Promise.resolve(null);
        return window.EntryStore.fetchTextUrl(url, { noStore: !!task.noStore, resourceRef: task.resourceRef || task.ref || task.title || '' });
    }

    function prepareTask(task, defaultLevel) {
        var level = String(task && (task.level || defaultLevel) || 'half').toLowerCase();
        var type = String(task && task.type || '').toLowerCase();
        if (!task || typeof task !== 'object') return Promise.resolve(null);
        if (type === 'html') return prepareHtmlEntry(task);
        if (type === 'json') return window.EntryStore.fetchJsonRef(task.ref, { noStore: !!task.noStore });
        if (type === 'pixel-json') {
            return waitForDecorationRuntime().then(function (runtime) {
                if (level === 'full' && runtime && typeof runtime.preparePixelCanvas === 'function') {
                    return runtime.preparePixelCanvas(task.ref || task.asset);
                }
                return window.EntryStore.fetchJsonRef(task.ref || task.asset);
            });
        }
        if (type === 'decorations') return prepareDecorationSet(task, level);
        if (type === 'nations-era') return prepareNationsEra(task, level);
        if (type === 'globe-shared-assets') return prepareGlobeSharedAssets(task, level);
        if (type === 'image-assets') return prepareImageAssets(task, level);
        return Promise.resolve(null);
    }

    function loadManifest() {
        return BootPerf.measure('revision manifest load', {}, function () {
            return (window.RevisionManifest && typeof window.RevisionManifest.load === 'function' ? window.RevisionManifest.load() : Promise.resolve(null));
        }).then(function () {
            return BootPerf.measure('entry manifest json fetch', { ref: MANIFEST_TITLE }, function () {
                return window.EntryStore.fetchJsonRef(MANIFEST_TITLE, { noStore: false });
            });
        }).then(function (manifest) {
            if (!manifest || typeof manifest !== 'object' || !manifest.version) {
                BootPerf.mark('entry manifest fallback', { reason: 'invalid manifest' });
                return defaultManifest;
            }
            BootPerf.mark('entry manifest ready', { version: manifest.version });
            return manifest;
        }).catch(function (err) {
            BootPerf.mark('entry manifest fallback', { reason: err && (err.message || String(err)) || 'load failed' });
            return defaultManifest;
        });
    }

    function flattenInitialTasks(manifest) {
        var initial = manifest && manifest.initial ? manifest.initial : {};
        var full = Array.isArray(initial.full) ? initial.full : [];
        var half = Array.isArray(initial.half) ? initial.half : [];
        var tasks = [];
        full.forEach(function (task) {
            task = Object.assign({}, task);
            task.level = task.level || 'full';
            task.blocking = true;
            tasks.push(task);
        });
        half.forEach(function (task) {
            task = Object.assign({}, task);
            task.level = task.level || 'half';
            task.blocking = false;
            tasks.push(task);
        });
        return tasks;
    }


    function flattenWarmInitialTasks(tasks) {
        var warmed = [];
        (tasks || []).forEach(function (task) {
            var copy;
            var type = String(task && task.type || '').toLowerCase();
            if (!task || task.blocking === false) return;

            /*
             * Warm boot fast path — 20260708.
             *
             * Cold boot intentionally performs the expensive work: resolving every flag,
             * downloading/decoding images, preparing decoration canvases, and warming shared
             * globe textures.  Once a tab has certified the pack against the current revision
             * manifest, later tabs must not replay that full workload.  They only hydrate the
             * small tables needed by the live page and let already-cached image/blob data be
             * consumed on demand.  This is the missing layer that made second tabs feel almost
             * as slow as first tabs even though the string checks were true.
             */
            if (type === 'globe-shared-assets') return;
            if (type === 'image-assets') return;
            copy = Object.assign({}, task);
            if (type === 'nations-era') copy.level = 'warm';
            else if (type === 'decorations') {
                copy.level = 'half';
                copy.preparePixels = false;
            } else if (type === 'pixel-json') copy.level = 'half';
            warmed.push(copy);
        });
        return warmed;
    }

    function currentInitialPackKey(manifest) {
        var version = manifest && manifest.version ? String(manifest.version) : BUILD_ID;
        return 'initial-entry-full:' + version;
    }

    function currentInitialPackToken(manifest) {
        var version = manifest && manifest.version ? String(manifest.version) : BUILD_ID;
        var revToken = window.RevisionManifest && typeof window.RevisionManifest.manifestToken === 'function' ? window.RevisionManifest.manifestToken(version) : version;
        return revToken;
    }

    function isInitialPackWarm(manifest) {
        var key = currentInitialPackKey(manifest);
        var token = currentInitialPackToken(manifest);
        return !!(window.EntryCache && typeof window.EntryCache.packReady === 'function' && window.EntryCache.packReady(key, token));
    }

    function markInitialPackWarm(manifest, meta) {
        var key = currentInitialPackKey(manifest);
        var token = currentInitialPackToken(manifest);
        if (window.EntryCache && typeof window.EntryCache.setPackReady === 'function') {
            window.EntryCache.setPackReady(key, token, Object.assign({ manifestVersion: manifest && manifest.version || BUILD_ID }, meta || {}));
        }
    }


    function waitMs(ms) {
        return new Promise(function (resolve) { window.setTimeout(resolve, Math.max(0, ms || 0)); });
    }

    function waitForBody() {
        if (document.body) return Promise.resolve(document.body);
        return new Promise(function (resolve) {
            function tick() {
                if (document.body) return resolve(document.body);
                window.setTimeout(tick, 10);
            }
            tick();
        });
    }

    function waitForDomReady() {
        if (document.readyState !== 'loading') return Promise.resolve();
        return new Promise(function (resolve) {
            document.addEventListener('DOMContentLoaded', resolve, { once: true });
        });
    }

    function waitForAnimationFrames(count) {
        count = Math.max(1, Math.round(count || 1));
        return new Promise(function (resolve) {
            function next(left) {
                if (left <= 0) return resolve();
                window.requestAnimationFrame(function () { next(left - 1); });
            }
            next(count);
        });
    }

    function waitUntil(predicate, options) {
        var started = now();
        var timeout = options && options.timeoutMs ? options.timeoutMs : 8000;
        var interval = options && options.intervalMs ? options.intervalMs : 60;
        return new Promise(function (resolve) {
            function tick() {
                var result = false;
                try { result = predicate(); } catch (err) { result = false; }
                if (result) return resolve({ ok: true, value: result });
                if (now() - started >= timeout) return resolve({ ok: false, timeout: true });
                window.setTimeout(tick, interval);
            }
            tick();
        });
    }

    function waitForTrackedScripts() {
        var list = (window.EntryScriptLoads || []).slice();
        if (!list.length) return Promise.resolve([]);
        return Promise.all(list.map(function (promise) {
            return Promise.resolve(promise).catch(function (err) { return { ok: false, error: err }; });
        }));
    }

    function waitForDocumentSurface() {
        return waitForDomReady().then(function () {
            return waitForBody();
        }).then(function () {
            return waitUntil(function () {
                return document.querySelector('.content-wrapper') && document.querySelector('.liberty-content-main');
            }, { timeoutMs: 8000, intervalMs: 50 });
        });
    }

    function isNationsPageSurface() {
        var page = String(mw && mw.config ? (mw.config.get('wgPageName') || mw.config.get('wgTitle') || '') : '');
        return !!document.querySelector('.clbi-nations-panel-stack') || /(?:^|[_ ])시대(?:$|[_ ])/.test(page) || /(?:^|[_ ])Era(?:$|[_ ])/i.test(page);
    }

    function getInitialNationsEra(manifest) {
        var tasks = flattenInitialTasks(manifest);
        var i;
        for (i = 0; i < tasks.length; i += 1) {
            if (tasks[i] && tasks[i].type === 'nations-era' && String(tasks[i].level || '').toLowerCase() === 'full') {
                return String(tasks[i].era || '1950');
            }
        }
        return '1950';
    }

    function waitForNationsPanelReady(era) {
        return BootPerf.measure('wait nations panel api', { era: era }, function () {
            return waitUntil(function () { return window.NationsPanel && typeof window.NationsPanel.whenEraReady === 'function'; }, {
                timeoutMs: 8000,
                intervalMs: 50
            });
        }).then(function (result) {
            if (!result.ok || !window.NationsPanel || typeof window.NationsPanel.whenEraReady !== 'function') return null;
            return BootPerf.measure('wait nations panel era ready', { era: era }, function () {
                return window.NationsPanel.whenEraReady(era, { timeoutMs: 15000 }).catch(function () { return null; });
            });
        }).then(function () {
            return BootPerf.measure('wait nations panel dom ready', { era: era }, function () {
                return waitUntil(function () {
                    var panel = document.querySelector('.clbi-nations-era-content[data-era-content="' + era + '"] .clbi-nations-tabpanel[data-nation-list-source="1"]') ||
                        document.querySelector('.clbi-nations-tabpanel[data-nation-list-source="1"]');
                    return panel && panel.classList.contains('clbi-nations-list-json-ready') && panel.getAttribute('data-nation-list-year-loaded') === String(era);
                }, { timeoutMs: 15000, intervalMs: 80 });
            });
        });
    }

    function waitForNationsGlobeReady(options) {
        var globe = document.querySelector('.clbi-nations-globe-window[data-nations-globe], [data-nations-globe="real-world"]');
        var soft;
        var timeout;

        options = options || {};
        soft = !!options.soft;
        timeout = Number(options.timeoutMs || (soft ? 450 : 30000));

        if (!globe) {
            BootPerf.mark('wait nations globe skipped', { reason: 'no globe node', soft: soft });
            return Promise.resolve(null);
        }

        return BootPerf.measure(soft ? 'wait nations globe warm attach' : 'wait nations globe ready contract', { soft: soft, timeoutMs: timeout }, function () {
            if (soft) {
                /*
                Warm-tab policy:
                Raw globe images are already revision-checked and blob-cached by EntryCache,
                but WebGL scene creation, GPU upload, topojson parsing, and per-tab Three.js
                objects cannot be shared across browser tabs.  Waiting for the full is-ready
                contract here makes a warm tab slower than the first tab.  In warm mode the
                initial gate only waits until the globe consumer has been attached, then the
                globe finishes its own per-tab hydrate without holding the whole page hostage.
                */
                return waitUntil(function () {
                    var node = document.querySelector('.clbi-nations-globe-window[data-nations-globe], [data-nations-globe="real-world"]');
                    if (!node) return false;
                    return node.getAttribute('data-nations-globe-ready') === '1' ||
                        !!node.CLBI_NationsGlobeInstance ||
                        !!node.querySelector('.clbi-nations-globe-stage') ||
                        node.classList.contains('is-ready') ||
                        node.classList.contains('has-error');
                }, { timeoutMs: timeout, intervalMs: 40 });
            }

            return waitUntil(function () {
                var node = document.querySelector('.clbi-nations-globe-window[data-nations-globe], [data-nations-globe="real-world"]');
                return node && (node.classList.contains('is-ready') || node.classList.contains('has-error'));
            }, { timeoutMs: timeout, intervalMs: 100 });
        });
    }

    function waitForDecorationsReady(options) {
        options = options || {};
        return waitForDecorationRuntime().then(function (runtime) {
            if (!runtime) return null;
            if (options.warm) {
                /*
                 * Warm tab contract — 20260708.
                 *
                 * The decoration registry and pixel canvases were prepared by the cold tab.
                 * Calling reload() here re-reads and re-syncs the decoration layer during the
                 * boot gate, which is visible as a pointless delay.  A warm tab only needs the
                 * current visibility pass so boot can release quickly and editing/preview tools
                 * remain responsive.
                 */
                try {
                    if (typeof runtime.updateVisibility === 'function') runtime.updateVisibility(document);
                    else if (typeof runtime.sync === 'function') runtime.sync();
                } catch (err) {}
                return waitForAnimationFrames(1);
            }
            if (typeof runtime.reload !== 'function') return null;
            return runtime.reload().catch(function () { return null; }).then(function () {
                return waitForAnimationFrames(2);
            });
        });
    }

    function waitForCurrentEntrySurface(manifest, options) {
        var era = getInitialNationsEra(manifest);
        var warmPack;

        options = options || {};
        warmPack = !!options.warmPack;

        if (!isNationsPageSurface()) {
            return waitForDecorationsReady({ warm: !!warmPack }).then(function () { return waitForAnimationFrames(1); });
        }
        if (bootStatusNode) bootStatusNode.textContent = warmPack ? 'Hydrating current information surface from warm cache' : 'Preparing current information surface';
        if (bootDetailNode) bootDetailNode.textContent = 'waiting for era ' + era + ' ready contract';
        return waitForNationsPanelReady(era)
            .then(function () {
                if (warmPack) {
                    if (bootDetailNode) bootDetailNode.textContent = 'attaching globe warm consumer';
                    return waitForNationsGlobeReady({ soft: true, timeoutMs: 450 });
                }
                if (bootDetailNode) bootDetailNode.textContent = 'waiting for globe ready contract';
                return waitForNationsGlobeReady();
            })
            .then(function () {
                if (bootDetailNode) bootDetailNode.textContent = 'waiting for decoration surface';
                return waitForDecorationsReady({ warm: warmPack });
            })
            .then(function () { return waitForAnimationFrames(warmPack ? 1 : 2); });
    }

    function runDeferredEntryWarmups() {
        var queue = deferredEntryWarmups.splice(0);
        if (!queue.length) return;
        window.setTimeout(function () {
            var chain = Promise.resolve();
            queue.forEach(function (job) {
                chain = chain.then(function () {
                    try { return job(); }
                    catch (err) { return null; }
                }).catch(function () { return null; });
            });
        }, 1200);
    }

    function runInitialLoad(options) {
        var done = 0;
        var manifestRef;
        var tasks;
        var bootOptions;
        var timedOut = false;
        var warmPack = false;

        options = options || {};
        bootStartTime = window.__BootGatePrelude && window.__BootGatePrelude.startTime ? window.__BootGatePrelude.startTime : now();
        activateBootSurface();
        ensureBootScreen();
        updateBootProgress(0, 1, 'loading entry manifest');

        manifestRef = loadManifest().then(function (manifest) {
            var minDisplay;
            var totalSteps;
            var maxBlockingMs;
            var timeoutHandle;
            bootOptions = manifest.boot || {};
            warmPack = isInitialPackWarm(manifest);
            minDisplay = options.minDisplayMs || (warmPack ? (bootOptions.cachedMinDisplayMs || 220) : (bootOptions.minDisplayMs || 950));
            tasks = flattenInitialTasks(manifest);
            if (!tasks.length) tasks = flattenInitialTasks(defaultManifest);
            if (warmPack) tasks = flattenWarmInitialTasks(tasks);

            /*
            Full/half contract:
            These manifest tasks only prepare data assets.  The gate is not allowed to open
            until the current page surface has consumed that data and reported a real ready
            state below.  Do not reintroduce localStorage-only skip logic here; a cached
            version number is not the same as current-tab readiness.
            */
            totalSteps = tasks.length + 4;
            updateBootProgress(0, totalSteps, warmPack ? 'hydrating warm entry cache' : 'starting entry packs');

            return new Promise(function (resolve) {
                maxBlockingMs = Number(options.maxBlockingMs || bootOptions.maxBlockingMs || 30000);
                timeoutHandle = window.setTimeout(function () {
                    timedOut = true;
                    resolve();
                }, maxBlockingMs);

                Promise.all(tasks.map(function (task) {
                    var label = task.label || task.id || task.type || 'entry task';
                    return BootPerf.measure('boot task: ' + label, { id: task.id || '', type: task.type || '', level: task.level || task.level === 0 ? task.level : '' }, function () {
                        return prepareTask(task, task.level);
                    }).catch(function () {
                        return null;
                    }).then(function () {
                        done += 1;
                        updateBootProgress(done, totalSteps, label);
                    });
                })).then(function () {
                    updateBootProgress(++done, totalSteps, 'loading subsystem scripts');
                    return BootPerf.measure('wait tracked subsystem scripts', { count: (window.EntryScriptLoads || []).length }, function () { return waitForTrackedScripts(); });
                }).then(function () {
                    updateBootProgress(++done, totalSteps, 'waiting for document shell');
                    return BootPerf.measure('wait document shell', {}, function () { return waitForDocumentSurface(); });
                }).then(function () {
                    updateBootProgress(++done, totalSteps, 'waiting for current entry surface');
                    return BootPerf.measure('wait current entry surface', { warmPack: warmPack }, function () { return waitForCurrentEntrySurface(manifest, { warmPack: warmPack }); });
                }).then(function () {
                    updateBootProgress(totalSteps, totalSteps, warmPack ? 'warm entry surface complete' : 'entry surface complete');
                    window.clearTimeout(timeoutHandle);
                    resolve();
                }).catch(function () {
                    window.clearTimeout(timeoutHandle);
                    resolve();
                });
            }).then(function () {
                var elapsed = now() - bootStartTime;
                var wait = Math.max(0, minDisplay - elapsed);
                return waitMs(wait);
            }).then(function () {
                localStorage.setItem(READY_KEY, String(manifest.version));
                if (!timedOut) markInitialPackWarm(manifest, { warmSource: warmPack ? 'cache-hit' : 'cold-build' });
                if (bootStatusNode) bootStatusNode.textContent = timedOut ? 'Entry surface ready with deferred items' : (warmPack ? 'Entry surface ready from warm cache' : 'Entry surface ready');
                updateBootProgress(tasks.length + 4, tasks.length + 4, timedOut ? 'timeout: continuing deferred loading' : (warmPack ? 'warm cache complete' : 'complete'));
                BootPerf.mark('boot gate complete', { timedOut: timedOut, warmPack: warmPack, manifestVersion: manifest && manifest.version || '' });
                BootPerf.print();
                runDeferredEntryWarmups();
                window.setTimeout(function () {
                    if (requiresLoginGate()) showLoginGate();
                    else hideBootScreen();
                }, 120);
                return manifest;
            });
        });

        return manifestRef;
    }

    function startBoot(options) {
        if (BOOT_EXCLUDED_PAGE && !(options && options.force)) {
            hideBootScreen();
            return Promise.resolve({ skipped: true, reason: 'developer-or-editing-page' });
        }
        if (hasBootParam('0') && !requiresLoginGate() && !(options && options.force)) return Promise.resolve(null);
        if (bootStarted && bootPromise && !(options && options.force)) return bootPromise;
        bootStarted = true;
        bootPromise = runInitialLoad(options || {});
        return bootPromise;
    }

    function resetBoot() {
        localStorage.removeItem(READY_KEY);
        bootStarted = false;
        bootPromise = null;
        loginGateLocked = false;
    }

    /*
    BootGate intentionally has no SPA hold/release API.
    Initial boot is the only blocking phase; later SPA routes must consume prepared
    EntryStore artifacts without reopening the loading surface.
    */

    function buildBootReport() {
        return {
            build: BUILD_ID,
            state: {
                started: bootStarted,
                excludedPage: BOOT_EXCLUDED_PAGE,
                loginRequired: requiresLoginGate(),
                loginLocked: loginGateLocked,
                hasNode: !!((bootNode && bootNode.parentNode) || document.getElementById('boot-gate-screen')),
                htmlActive: !!(document.documentElement && document.documentElement.classList.contains('boot-gate-active')),
                bodyActive: !!(document.body && document.body.classList.contains('boot-gate-active'))
            },
            store: window.EntryStore && window.EntryStore.cacheInfo ? window.EntryStore.cacheInfo() : null,
            bootPerf: window.BootPerf && typeof window.BootPerf.summary === 'function' ? window.BootPerf.summary() : null,
            revisionManifest: window.RevisionManifest && typeof window.RevisionManifest.status === 'function' ? window.RevisionManifest.status() : null,
            nations: window.NationsPanel && typeof window.NationsPanel.diagnostics === 'function' ? window.NationsPanel.diagnostics() : null,
            decorations: window.Decorations && typeof window.Decorations.diagnostics === 'function' ? window.Decorations.diagnostics() : null
        };
    }

    window.EntryLoader = window.EntryLoader || {
        loadManifest: loadManifest,
        prepareTask: prepareTask,
        prepareNationsEra: prepareNationsEra,
        prepareDecorationSet: prepareDecorationSet,
        prepareGlobeSharedAssets: prepareGlobeSharedAssets,
        prepareImageAssets: prepareImageAssets,
        prepareHtmlEntry: prepareHtmlEntry,
        runInitialLoad: runInitialLoad
    };

    function showBootPreview(options) {
        var node;
        options = options || {};
        /*
         * Boot preview is a design/editing surface, not a real boot gate.
         * The earlier preview reused activateBootSurface(), which applied
         * html.boot-gate-active and hid the entire wiki shell, including
         * DevTools.  That made it impossible to edit loading-screen
         * decorations while previewing them.  Keep the real first-entry gate
         * full-screen, but make preview a small non-blocking surface below the
         * DevTools z-index so the owner can keep using the editor.
         */
        node = ensureBootScreen({ preview: true });
        if (!node) return null;
        node.classList.add('is-preview');
        if (bootStatusNode) bootStatusNode.textContent = options.status || 'Loading screen preview';
        updateBootProgress(Number(options.progress || 64), 100, options.detail || 'preview mode: no entry tasks are running');
        try {
            if (window.Decorations && typeof window.Decorations.sync === 'function') window.Decorations.sync();
        } catch (err) {}
        return node;
    }

    window.BootGate = window.BootGate || {
        version: BUILD_ID,
        start: startBoot,
        show: function (options) {
            options = options || {};
            options.force = true;
            resetBoot();
            return startBoot(options);
        },
        reset: resetBoot,
        hide: hideBootScreen,
        preview: showBootPreview,
        report: buildBootReport,
        state: function () {
            return {
                started: bootStarted,
                loginRequired: requiresLoginGate(),
                loginLocked: loginGateLocked,
                hasNode: !!((bootNode && bootNode.parentNode) || document.getElementById('boot-gate-screen')),
                htmlActive: !!(document.documentElement && document.documentElement.classList.contains('boot-gate-active')),
                bodyActive: !!(document.body && document.body.classList.contains('boot-gate-active')),
                prelude: !!window.__BootGatePrelude,
                store: window.EntryStore && window.EntryStore.cacheInfo ? window.EntryStore.cacheInfo() : null,
                revisionManifest: window.RevisionManifest && typeof window.RevisionManifest.status === 'function' ? window.RevisionManifest.status() : null
            };
        }
    };

    function prime() {
        if (BOOT_EXCLUDED_PAGE) {
            hideBootScreen();
            return;
        }
        activateBootSurface();
        waitForBody().then(function () {
            ensureBootScreen();
            return waitForAnimationFrames(1);
        }).then(function () {
            startBoot();
        });
    }

    waitForBody().then(function () {
        if (!BOOT_EXCLUDED_PAGE) ensureBootScreen();
        else hideBootScreen();
    });
    window.setTimeout(prime, 0);
})(window, document, window.mediaWiki || window.mw);


loadClbiRawScript('MediaWiki:DevTools.js');
loadClbiRawScript('MediaWiki:NationsPanel.js');
loadClbiRawScript('MediaWiki:NationsGlobe.js');

/* CLBI safety guard: adaptive reset functions must exist before shell metric callbacks run. */
function resetLeftRecentAdaptiveState() {
    var list = document.getElementById('clbi-left-recent-list');
    var newsBox = list ? list.closest('.clbi-left-news-box') : null;
    var items = list ? Array.prototype.slice.call(list.querySelectorAll('.news-recent-item')) : [];

    if (newsBox) {
        newsBox.classList.remove('is-adaptive-constrained');
        newsBox.style.removeProperty('--adaptive-news-h');
    }

    if (list) {
        list.classList.remove('is-adaptive-faded');
        list.removeAttribute('data-adaptive-limit');
        list.style.removeProperty('--adaptive-recent-h');
    }

    items.forEach(function (item) {
        item.classList.remove('is-adaptive-hidden');
    });
}

function resetLeftBillboardAdaptiveState() {
    var box = document.querySelector('#clbi-left-sidebar .left-billboard-box');

    if (!box) return;

    box.classList.remove('is-left-ad-title-only', 'is-left-ad-extended');
    box.style.removeProperty('--left-billboard-h');
    box.style.removeProperty('--left-billboard-finish-h');
}

window.resetLeftRecentAdaptiveState = resetLeftRecentAdaptiveState;
window.resetLeftBillboardAdaptiveState = resetLeftBillboardAdaptiveState;

loadClbiRawScript('MediaWiki:AnecdoteViewer.js');


(function () {
    'use strict';

    var SYSTEM_TITLE_NAMESPACES = {
        '-1': true,
        '4': true,
        '5': true,
        '6': true,
        '7': true,
        '8': true,
        '9': true,
        '10': true,
        '11': true,
        '12': true,
        '13': true,
        '14': true,
        '15': true,
        '828': true,
        '829': true
    };

    function normalizePageNameForShell(value) {
        return String(value || '')
            .split('?')[0]
            .replace(/^\/index\.php\//, '')
            .replace(/_/g, ' ')
            .trim();
    }

    function readCurrentPageNameForShell() {
        var pageName = mw.config.get('wgPageName') || '';

        if (pageName) {
            return normalizePageNameForShell(pageName);
        }

        return normalizePageNameForShell(window.location.pathname || '');
    }

    function isAnecdoteNamespaceForShell() {
        var namespaceNumber = Number(mw.config.get('wgNamespaceNumber'));
        var canonicalNamespace = String(mw.config.get('wgCanonicalNamespace') || '').toLowerCase();
        var pageName = readCurrentPageNameForShell();

        return namespaceNumber === 3000 ||
            canonicalNamespace === 'anecdote' ||
            /^(anecdote|에넥도트):/i.test(pageName);
    }

    function isBackendOrSystemPageForShell() {
        var namespaceNumber = Number(mw.config.get('wgNamespaceNumber'));
        var action = String(mw.config.get('wgAction') || 'view').toLowerCase();
        var contentModel = String(mw.config.get('wgPageContentModel') || '').toLowerCase();
        var pageName = readCurrentPageNameForShell();
        var lowerPageName = pageName.toLowerCase();

        if (action && action !== 'view') {
            return true;
        }

        if (pageName === '대문') {
            return false;
        }

        if (SYSTEM_TITLE_NAMESPACES[String(namespaceNumber)]) {
            return true;
        }

        if (contentModel === 'css' || contentModel === 'javascript' || contentModel === 'json' || contentModel === 'sanitized-css') {
            return true;
        }

        if (/\.(css|js|json)$/i.test(pageName)) {
            return true;
        }

        if (/^(mediawiki|미디어위키|special|특수):/i.test(pageName)) {
            return true;
        }

        return false;
    }

    function isMediaWikiSystemAssetPageForShell() {
        var namespaceNumber = Number(mw.config.get('wgNamespaceNumber'));
        var pageName = readCurrentPageNameForShell();
        var contentModel = String(mw.config.get('wgPageContentModel') || '').toLowerCase();

        return namespaceNumber === 8 &&
            (/\.(css|js)$/i.test(pageName) || contentModel === 'css' || contentModel === 'javascript' || contentModel === 'sanitized-css');
    }


    var systemDocRawFetchToken = 0;

    function cleanupLegacySystemDocCodeMutationsForShell() {
        document.querySelectorAll('.clbi-system-doc-codepane').forEach(function (pane) {
            var parent;

            if (!pane || !pane.parentNode) return;

            parent = pane.parentNode;
            while (pane.firstChild) {
                parent.insertBefore(pane.firstChild, pane);
            }
            parent.removeChild(pane);
        });

        document.querySelectorAll('.clbi-system-doc-codebox').forEach(function (node) {
            node.classList.remove('clbi-system-doc-codebox');
            node.removeAttribute('data-clbi-system-doc-codebox');
            node.removeAttribute('style');
        });
    }

    function getSystemDocOutputForShell() {
        return document.querySelector('.liberty-content-main .mw-parser-output');
    }

    function findSystemDocSourceNodeForShell() {
        var output = getSystemDocOutputForShell();
        var children;
        var preferred;

        if (!output) return null;

        children = Array.prototype.slice.call(output.children || [])
            .filter(function (el) {
                return el && el.nodeType === 1 &&
                    el.id !== 'clbi-system-doc-indicator-row' &&
                    el.id !== 'clbi-system-source-viewer' &&
                    !el.classList.contains('catlinks') &&
                    (el.textContent || '').trim().length > 200;
            });

        preferred = children.filter(function (el) {
            return el.matches && el.matches('.mw-highlight, .mw-code, pre');
        })[0];

        return preferred || children.sort(function (a, b) {
            return (b.textContent || '').trim().length - (a.textContent || '').trim().length;
        })[0] || null;
    }

    function getSystemDocRawUrlForShell() {
        var title = mw.config.get('wgPageName') || readCurrentPageNameForShell();
        var url;

        if (window.mw && mw.util && typeof mw.util.getUrl === 'function') {
            url = mw.util.getUrl(title, {
                action: 'raw',
                ctype: 'text/plain'
            });
        } else {
            url = '/index.php?title=' + encodeURIComponent(title) + '&action=raw&ctype=text/plain';
        }

        if (window.RevisionManifest && typeof window.RevisionManifest.addRevisionParam === 'function') {
            url = window.RevisionManifest.addRevisionParam(url, title);
        }
        return url;
    }

    function removeSystemDocSourceViewerForShell() {
        var viewer = document.getElementById('clbi-system-source-viewer');

        if (viewer && viewer.parentNode) {
            viewer.parentNode.removeChild(viewer);
        }

        document.querySelectorAll('.clbi-system-original-source-hidden').forEach(function (node) {
            node.classList.remove('clbi-system-original-source-hidden');
            node.removeAttribute('data-clbi-system-source-hidden');
            node.style.removeProperty('display');
        });

        cleanupLegacySystemDocCodeMutationsForShell();
    }

    function ensureSystemDocSourceViewerForShell() {
        var output = getSystemDocOutputForShell();
        var source;
        var viewer;
        var fallbackText;

        if (!output || !isMediaWikiSystemAssetPageForShell()) return null;

        cleanupLegacySystemDocCodeMutationsForShell();

        source = findSystemDocSourceNodeForShell();
        if (!source) return null;

        viewer = document.getElementById('clbi-system-source-viewer');

        if (!viewer) {
            viewer = document.createElement('pre');
            viewer.id = 'clbi-system-source-viewer';
            viewer.className = 'clbi-system-source-viewer';
            output.appendChild(viewer);
        }

        fallbackText = source.textContent || '';

        if (!viewer.textContent && fallbackText) {
            viewer.textContent = fallbackText;
        }

        source.classList.add('clbi-system-original-source-hidden');
        source.setAttribute('data-clbi-system-source-hidden', 'true');
        source.style.setProperty('display', 'none', 'important');

        return viewer;
    }

    function renderSystemDocSourceViewerForShell() {
        var viewer;
        var pageName;
        var token;
        var currentScrollTop;

        if (!isMediaWikiSystemAssetPageForShell()) return;

        pageName = String(mw.config.get('wgPageName') || readCurrentPageNameForShell());
        viewer = document.getElementById('clbi-system-source-viewer');

        /*
        시스템 문서 뷰어가 이미 만들어져 있고 raw 원문도 로드된 상태라면
        다시 source 탐색/숨김/스타일 재적용을 하지 않는다.
        DevTools Elements 패널에서 body가 계속 파랗게 깜빡이던 원인은
        MutationObserver가 이 재적용을 반복해서 DOM attribute mutation을 만들었기 때문이다.
        */
        if (
            viewer &&
            viewer.getAttribute('data-clbi-raw-title') === pageName &&
            viewer.getAttribute('data-clbi-raw-loaded') === '1'
        ) {
            return;
        }

        viewer = ensureSystemDocSourceViewerForShell();
        if (!viewer) return;

        currentScrollTop = viewer.scrollTop || 0;
        viewer.setAttribute('data-clbi-raw-title', pageName);
        token = ++systemDocRawFetchToken;

        fetch(getSystemDocRawUrlForShell(), { credentials: 'same-origin' })
            .then(function (res) {
                if (!res.ok) throw new Error('raw fetch failed ' + res.status);
                return res.text();
            })
            .then(function (text) {
                if (token !== systemDocRawFetchToken) return;

                currentScrollTop = viewer.scrollTop || currentScrollTop || 0;

                if (text && viewer.textContent !== text) {
                    viewer.textContent = text;
                }

                viewer.setAttribute('data-clbi-raw-loaded', '1');
                viewer.scrollTop = currentScrollTop;
            })
            .catch(function () {
                viewer.setAttribute('data-clbi-raw-loaded', '0');
            });
    }

    function removeSystemDocIndicatorForShell() {
        var existing = document.getElementById('clbi-system-doc-indicator-row');

        if (document.body) {
            document.body.classList.remove('clbi-system-doc-page');
        }

        if (existing && existing.parentNode) {
            existing.parentNode.removeChild(existing);
        }

        removeSystemDocSourceViewerForShell();
    }

    function renderSystemDocIndicatorForShell() {
        var pageName;
        var extMatch;
        var ext;
        var row;
        var box;
        var meta;
        var label;
        var type;
        var title;
        var anchor;
        var main;

        if (!document.body || !isMediaWikiSystemAssetPageForShell()) return;

        pageName = readCurrentPageNameForShell();
        extMatch = pageName.match(/\.(css|js)$/i);
        ext = extMatch ? extMatch[1].toUpperCase() : 'DOC';

        document.body.classList.add('clbi-system-doc-page');

        row = document.getElementById('clbi-system-doc-indicator-row');

        if (!row) {
            row = document.createElement('div');
            row.id = 'clbi-system-doc-indicator-row';
            row.className = 'clbi-system-doc-indicator-row';

            box = document.createElement('div');
            box.className = 'clbi-system-doc-indicator';

            meta = document.createElement('div');
            meta.className = 'clbi-system-doc-meta';

            label = document.createElement('span');
            label.className = 'clbi-system-doc-label';
            label.textContent = 'SYSTEM DOCUMENT';

            type = document.createElement('span');
            type.className = 'clbi-system-doc-type';

            title = document.createElement('div');
            title.className = 'clbi-system-doc-title';

            meta.appendChild(label);
            meta.appendChild(type);
            box.appendChild(meta);
            box.appendChild(title);
            row.appendChild(box);

            anchor = getSystemDocOutputForShell();
            main = document.querySelector('.liberty-content-main');

            if (anchor && anchor.parentNode) {
                anchor.parentNode.insertBefore(row, anchor);
            } else if (main) {
                main.insertBefore(row, main.firstChild);
            }
        }

        type = row.querySelector('.clbi-system-doc-type');
        title = row.querySelector('.clbi-system-doc-title');

        if (type) type.textContent = ext;
        if (title) title.textContent = pageName;

        renderSystemDocSourceViewerForShell();
    }

    var PAGE_TITLE_TARGET_SELECTORS = [
        '.liberty-content-header',
        '.liberty-content-header .title',
        '.liberty-content-header .title h1',
        '.liberty-content-header h1',
        '#firstHeading',
        '.firstHeading',
        '.mw-first-heading',
        '.page-heading',
        '.page-header',
        '.mw-page-title-main',
        '.mw-page-title-namespace',
        '.mw-page-title-separator'
    ];

    var pageShellObserverStarted = false;
    var pageShellObserverTimer = null;

    function setPageTitleDomHidden(hidden) {
        var nodes = document.querySelectorAll(PAGE_TITLE_TARGET_SELECTORS.join(','));

        nodes.forEach(function (node) {
            if (!node || !node.style) return;

            if (hidden) {
                node.setAttribute('data-clbi-title-hidden', 'true');
                node.style.setProperty('display', 'none', 'important');
            } else if (node.getAttribute('data-clbi-title-hidden') === 'true') {
                node.removeAttribute('data-clbi-title-hidden');
                node.style.removeProperty('display');
            }
        });
    }

    function applyPageShellClasses() {
        var body = document.body;
        var isSystemPage;

        if (!body) return;

        isSystemPage = isBackendOrSystemPageForShell();

        body.classList.remove('page-title-hidden', 'page-title-visible', 'backend-system-page', 'anecdote-namespace-page');

        if (!isMediaWikiSystemAssetPageForShell()) {
            body.classList.remove('clbi-system-doc-page');
            removeSystemDocIndicatorForShell();
        }

        if (isAnecdoteNamespaceForShell()) {
            body.classList.add('anecdote-namespace-page');
        }

        if (isMediaWikiSystemAssetPageForShell()) {
            body.classList.add('page-title-hidden', 'backend-system-page', 'clbi-system-doc-page');
            setPageTitleDomHidden(true);
            renderSystemDocIndicatorForShell();
        } else if (isSystemPage) {
            body.classList.add('page-title-visible', 'backend-system-page');
            setPageTitleDomHidden(false);
        } else {
            body.classList.add('page-title-hidden');
            setPageTitleDomHidden(true);
        }
    }

    function applyPageShellClassesDeferred() {
        applyPageShellClasses();
        window.setTimeout(applyPageShellClasses, 0);
        window.setTimeout(applyPageShellClasses, 80);
        window.setTimeout(applyPageShellClasses, 250);
    }

    function startPageShellObserver() {
        var observer;

        if (pageShellObserverStarted || !window.MutationObserver || !document.body) return;

        pageShellObserverStarted = true;
        observer = new MutationObserver(function (mutations) {
            var i;
            var target;

            /*
            시스템 CSS/JS 문서는 applyPageShellClasses()가 초기에 한 번
            인디케이터와 source viewer를 만든 뒤에는 MutationObserver가 다시
            같은 렌더링을 반복할 필요가 없다. 이 반복이 DevTools에서 body/요소가
            계속 플래시되는 직접 원인이다.
            SPA 전환 뒤의 처리는 loadPage()와 wikipage.content hook에서 따로 호출된다.
            */
            if (isMediaWikiSystemAssetPageForShell()) {
                for (i = 0; i < mutations.length; i += 1) {
                    target = mutations[i] && mutations[i].target;

                    if (
                        target &&
                        target.nodeType === 1 &&
                        (
                            target.id === 'clbi-system-source-viewer' ||
                            target.id === 'clbi-system-doc-indicator-row' ||
                            (target.closest && target.closest('#clbi-system-source-viewer, #clbi-system-doc-indicator-row'))
                        )
                    ) {
                        return;
                    }
                }

                if (
                    document.getElementById('clbi-system-doc-indicator-row') &&
                    document.getElementById('clbi-system-source-viewer')
                ) {
                    return;
                }
            }

            if (pageShellObserverTimer) return;

            pageShellObserverTimer = window.setTimeout(function () {
                pageShellObserverTimer = null;
                applyPageShellClasses();
            }, 50);
        });

        /*
        SPA 본문 교체는 wikipage.content 훅이 담당한다.
        body 전체 subtree를 감시하면 대문 SVG·장식·DevTools 내부 변경까지
        페이지 셸 재판정으로 증폭되므로 body 직계 자식 변화만 감시한다.
        */
        observer.observe(document.body, {
            childList: true,
            subtree: false
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function () {
            applyPageShellClassesDeferred();
            startPageShellObserver();
        });
    } else {
        applyPageShellClassesDeferred();
        startPageShellObserver();
    }

    if (mw.hook) {
        mw.hook('wikipage.content').add(applyPageShellClassesDeferred);
    }

    window.CLBI_PAGE_SHELL = {
        refresh: applyPageShellClasses,
        isBackendOrSystemPage: isBackendOrSystemPageForShell,
        isSystemAssetPage: isMediaWikiSystemAssetPageForShell,
        renderSystemDocIndicator: renderSystemDocIndicatorForShell,
        removeSystemDocIndicator: removeSystemDocIndicatorForShell,
        refreshSystemDocSourceViewer: renderSystemDocSourceViewerForShell
    };
}());

function loadLangScript(done) {
    $.getScript('/index.php?title=미디어위키:Lang.js&action=raw&ctype=text/javascript')
        .done(function() {
            if (typeof done === 'function') done();
        })
        .fail(function(a, b, c) {
            console.error('Lang.js load failed:', b, c);
            if (typeof done === 'function') done();
        });
}


/*
DevTools 같은 내부 스크롤은 셸 레이아웃을 바꾸지 않는다. 이 짧은 상호작용 동안
전체 화면 WebGL/CRT가 새 GPU 프레임을 계속 제출하면, transform 셸과 고정 네비의
합성 타일 갱신이 서로 경합한다. 마지막 정상 프레임은 그대로 유지하고 시각 시계도
정지시켜, 스크롤 종료 후 끊김 없이 이어지게 한다.
*/
var CLBI_COMPOSITOR_BUSY_UNTIL = 0;

function markClbiCompositorBusy(duration) {
    var now = window.performance && performance.now ? performance.now() : Date.now();
    CLBI_COMPOSITOR_BUSY_UNTIL = Math.max(CLBI_COMPOSITOR_BUSY_UNTIL, now + Math.max(80, Number(duration) || 140));
}

function isClbiCompositorBusy() {
    var now = window.performance && performance.now ? performance.now() : Date.now();
    return now < CLBI_COMPOSITOR_BUSY_UNTIL;
}

window.markClbiCompositorBusy = markClbiCompositorBusy;
window.isClbiCompositorBusy = isClbiCompositorBusy;

if (!window.CLBI_COMPOSITOR_ACTIVITY_BOUND) {
    window.CLBI_COMPOSITOR_ACTIVITY_BOUND = true;

    document.addEventListener('scroll', function (event) {
        var target = event.target && event.target.nodeType === 1 ? event.target : null;
        if (target && target.closest && target.closest('#dev-tools-panel')) {
            markClbiCompositorBusy(160);
        }
    }, true);

    document.addEventListener('wheel', function (event) {
        var target = event.target && event.target.nodeType === 1 ? event.target : null;
        if (target && target.closest && target.closest('#dev-tools-panel')) {
            markClbiCompositorBusy(160);
        }
    }, { capture:true, passive:true });
}

function initHalftoneBackground() {
    try {
        initWebGLHalftoneBackground();
    } catch (err) {
        console.error('WebGL halftone background failed:', err);
    }
}

function initWebGLHalftoneBackground() {
    var canvasId = 'site-halftone-bg';
    var existing = document.getElementById(canvasId);
    var canvas = existing || document.createElement('canvas');
    var halftoneState = window.SiteHalftoneBackgroundState || (window.SiteHalftoneBackgroundState = { runId: 0 });
    var runId = halftoneState.runId + 1;

    halftoneState.runId = runId;

    if (!existing) {
        canvas.id = canvasId;
        canvas.setAttribute('aria-hidden', 'true');
        document.body.insertBefore(canvas, document.body.firstChild || null);
    }

    canvas.style.position = 'fixed';
    canvas.style.inset = '0';
    canvas.style.width = '100vw';
    canvas.style.height = '100vh';
    canvas.style.pointerEvents = 'none';
    canvas.style.background = '#000000';
    canvas.style.display = 'block';

    if (!canvas.getAttribute('data-halftone-context-watch')) {
        canvas.setAttribute('data-halftone-context-watch', '1');
        canvas.addEventListener('webglcontextlost', function (event) {
            event.preventDefault();
            canvas.style.display = 'none';
            if (window.SiteHalftoneBackgroundState) {
                window.SiteHalftoneBackgroundState.contextLost = true;
                window.SiteHalftoneBackgroundState.runId += 1;
            }
        }, false);
        canvas.addEventListener('webglcontextrestored', function () {
            if (window.SiteHalftoneBackgroundState) {
                window.SiteHalftoneBackgroundState.contextLost = false;
            }
            window.setTimeout(initWebGLHalftoneBackground, 0);
        }, false);
    }

    var gl = canvas.getContext('webgl', {
        alpha: false,
        antialias: false,
        depth: false,
        stencil: false,
        preserveDrawingBuffer: false,
        powerPreference: 'low-power'
    }) || canvas.getContext('experimental-webgl');

    if (!gl) {
        canvas.style.display = 'none';
        console.warn('WebGL background unavailable.');
        return;
    }

    var vertexSrc = [
        'attribute vec2 a_position;',
        'void main() {',
        '  gl_Position = vec4(a_position, 0.0, 1.0);',
        '}'
    ].join('\n');

    var fragmentSrc = [
        'precision mediump float;',
        'uniform vec2 u_resolution;',
        'uniform float u_time;',
        'const float TAU = 6.28318530718;',
        'float gaussian(float v, float r) {',
        '  return exp(-((v * v) / max(0.0001, r * r)));',
        '}',
        'float hash(vec2 p) {',
        '  return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453123);',
        '}',
        'float bucketAlpha(float a) {',
        '  float i = floor(a * 9.0);',
        '  if (i < 1.0) return 0.040;',
        '  if (i < 2.0) return 0.080;',
        '  if (i < 3.0) return 0.135;',
        '  if (i < 4.0) return 0.210;',
        '  if (i < 5.0) return 0.310;',
        '  if (i < 6.0) return 0.430;',
        '  if (i < 7.0) return 0.580;',
        '  if (i < 8.0) return 0.760;',
        '  return 0.920;',
        '}',
        'void main() {',
        '  vec2 frag = gl_FragCoord.xy;',
        '  float spacing = 5.0;',
        '  float dotSize = 1.08;',
        '  vec2 grid = floor(frag / spacing);',
        '  vec2 inCell = mod(frag, spacing);',
        '  vec2 dotOrigin = vec2(1.0, 1.0);',
        '  vec2 dotCenter = dotOrigin + vec2(dotSize * 0.5);',
        '  vec2 local = abs(inCell - dotCenter);',
        '  float noise = hash(grid);',
        '  float size = dotSize + noise * 0.18;',
        '  float dotMask = 1.0 - smoothstep(size * 0.5, size * 0.5 + 0.22, max(local.x, local.y));',
        '  vec2 uv = frag / u_resolution;',
        '  float centerLine = 0.50 +',
        '    sin((uv.y * 1.32 + 0.08) * TAU) * 0.070 +',
        '    sin((uv.y * 3.18 + 0.34) * TAU) * 0.030;',
        '  float u = uv.x - centerLine;',
        '  float absU = abs(u);',
        '  float sideLift = smoothstep(0.065, 0.44, absU);',
        '  float valley = gaussian(u, 0.150);',
        '  float t = u_time;',
        '  float leftRibbonCenter = -0.28 + sin((uv.y * 3.20 + 0.12) * TAU) * 0.050;',
        '  float rightRibbonCenter = 0.27 + sin((uv.y * 2.85 + 0.56) * TAU) * 0.055;',
        '  float leftRibbon = gaussian(u - leftRibbonCenter, 0.105);',
        '  float rightRibbon = gaussian(u - rightRibbonCenter, 0.110);',
        '  float foldedU = u +',
        '    sin((uv.y * 4.40 + 0.22) * TAU) * 0.050 * (0.3 + sideLift) +',
        '    sin((uv.y * 7.20 + uv.x * 1.10) * TAU) * 0.022;',
        '  float verticalFold = pow(0.5 + 0.5 * cos(((foldedU * 3.05) + (sin(uv.y * TAU * 2.35) * 0.18)) * TAU), 2.5);',
        '  float diagonalFold = pow(0.5 + 0.5 * cos(((foldedU * 1.80) - (uv.y * 1.12) + 0.18) * TAU), 2.1);',
        '  float waist = gaussian(uv.y - 0.50, 0.25) * gaussian(absU - 0.20, 0.19);',
        '  float grain = (noise - 0.5) * 0.050;',
        '  float staticField =',
        '    0.055 +',
        '    sideLift * 0.210 +',
        '    (leftRibbon + rightRibbon) * 0.145 +',
        '    verticalFold * (0.055 + sideLift * 0.115) +',
        '    diagonalFold * 0.045 +',
        '    waist * 0.060 -',
        '    valley * 0.150 +',
        '    grain;',
        '  float alpha = staticField;',
        '  alpha += 0.115 * (leftRibbon + rightRibbon) * sin(t * 0.00030 + ((uv.y * 1.9) + sideLift * 0.4) * TAU);',
        '  alpha += 0.095 * verticalFold * (0.4 + sideLift) * sin(t * 0.00041 + ((uv.y * 2.7) + foldedU * 0.65) * TAU);',
        '  alpha += 0.070 * waist * sin(t * 0.00053 + ((uv.y * 3.1) - absU * 0.8) * TAU);',
        '  alpha += 0.060 * (1.0 - valley) * diagonalFold * sin(t * 0.00067 + ((uv.y * 1.4) + uv.x * 0.6) * TAU);',
        '  alpha += 0.038 * (0.35 + sideLift) * (0.35 + noise) * sin(t * 0.00079 + ((uv.y * 4.6) + noise * 0.8) * TAU);',
        '  alpha = bucketAlpha(clamp(alpha, 0.025, 0.96));',
        '  float value = alpha * dotMask;',
        '  gl_FragColor = vec4(vec3(0.8862745 * value), 1.0);',
        '}'
    ].join('\n');

    function compileShader(type, source) {
        var shader = gl.createShader(type);
        gl.shaderSource(shader, source);
        gl.compileShader(shader);

        if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
            console.error('WebGL shader compile error:', gl.getShaderInfoLog(shader));
            gl.deleteShader(shader);
            return null;
        }

        return shader;
    }

    var vertexShader = compileShader(gl.VERTEX_SHADER, vertexSrc);
    var fragmentShader = compileShader(gl.FRAGMENT_SHADER, fragmentSrc);

    if (!vertexShader || !fragmentShader) return;

    var program = gl.createProgram();
    gl.attachShader(program, vertexShader);
    gl.attachShader(program, fragmentShader);
    gl.linkProgram(program);

    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
        console.error('WebGL program link error:', gl.getProgramInfoLog(program));
        return;
    }

    var positionLoc = gl.getAttribLocation(program, 'a_position');
    var resolutionLoc = gl.getUniformLocation(program, 'u_resolution');
    var timeLoc = gl.getUniformLocation(program, 'u_time');

    var buffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
        -1, -1,
         1, -1,
        -1,  1,
        -1,  1,
         1, -1,
         1,  1
    ]), gl.STATIC_DRAW);

    gl.useProgram(program);
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
    gl.enableVertexAttribArray(positionLoc);
    gl.vertexAttribPointer(positionLoc, 2, gl.FLOAT, false, 0, 0);

    function resize() {
        var dpr = Math.min(window.devicePixelRatio || 1, 1.5);
        var cssW = Math.max(1, window.innerWidth || document.documentElement.clientWidth || 1);
        var cssH = Math.max(1, window.innerHeight || document.documentElement.clientHeight || 1);
        var w = Math.max(1, Math.floor(cssW * dpr));
        var h = Math.max(1, Math.floor(cssH * dpr));

        if (canvas.width !== w || canvas.height !== h) {
            canvas.width = w;
            canvas.height = h;
            canvas.style.width = cssW + 'px';
            canvas.style.height = cssH + 'px';
            gl.viewport(0, 0, w, h);
        }
    }

    var prefersReducedMotion = false;
    try {
        prefersReducedMotion = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    } catch (err) {}

    function getNationsGlobeHalftoneNode() {
        return document.querySelector('.clbi-nations-globe-window[data-nations-globe], [data-nations-globe="real-world"]');
    }

    function getNationsGlobeHalftoneState() {
        var globe = getNationsGlobeHalftoneNode();
        var instance;

        if (!globe) {
            return 'none';
        }

        if (globe.classList && globe.classList.contains('is-dragging')) {
            return 'active';
        }

        instance = globe.CLBI_NationsGlobeInstance || null;
        if (instance && typeof instance.isHalftoneBackgroundBusy === 'function' && instance.isHalftoneBackgroundBusy()) {
            return 'busy';
        }

        if (globe.getAttribute && globe.getAttribute('data-clbi-globe-bg-busy') === '1') {
            return 'busy';
        }

        return 'present';
    }

    function shouldSkipHalftoneDrawForGlobe() {
        var globe = getNationsGlobeHalftoneNode();
        var instance;

        if (!globe) return false;

        instance = globe.CLBI_NationsGlobeInstance || null;

        /*
         * Background pause/resume — 20260710.
         *
         * While the nations globe is being held, keep the last rendered halftone
         * frame on screen and pause the halftone clock.  The important detail is
         * that this is not a wall-clock catch-up: skipped seconds are not replayed
         * or fast-forwarded when the pointer is released.
         */
        if (globe.classList && globe.classList.contains('is-dragging')) return true;
        if (instance && instance.dragging) return true;

        if (instance && typeof instance.isHalftoneBackgroundHardBusy === 'function') {
            return instance.isHalftoneBackgroundHardBusy();
        }

        if (globe.getAttribute && globe.getAttribute('data-clbi-globe-bg-busy') === '1') return true;

        return false;
    }

    function getFrameInterval() {
        if (prefersReducedMotion) {
            return 1000;
        }

        /*
         * Nations background parity — 20260710.
         *
         * The nations page used to permanently lower the halftone cadence while
         * the globe existed.  Profiling showed that the steady halftone draw is
         * normally cheap; the real contention happens during globe drag, first
         * WebGL texture upload, and long layout/render tasks.  Keep the same
         * full-quality cadence as ordinary pages, and skip only the frames that
         * would directly collide with an active/busy globe moment.
         */
        return 66;
    }

    var lastFrame = 0;
    var startTime = performance.now();
    var visualTime = 0;
    var lastVisualNow = 0;

    function draw(now) {
        var state = getNationsGlobeHalftoneState();
        var interval = getFrameInterval();
        var perf = window.InteractionPerf;
        var delta;

        if (!lastVisualNow) {
            lastVisualNow = now;
        }
        delta = Math.max(0, Math.min(120, now - lastVisualNow));
        lastVisualNow = now;
        visualTime += delta;

        function runDraw() {
            resize();

            gl.clearColor(0, 0, 0, 1);
            gl.clear(gl.COLOR_BUFFER_BIT);
            gl.uniform2f(resolutionLoc, canvas.width, canvas.height);
            gl.uniform1f(timeLoc, visualTime);
            gl.drawArrays(gl.TRIANGLES, 0, 6);
        }

        if (perf && typeof perf.measureSync === 'function') {
            return perf.measureSync('background halftone draw', { globeState: state, interval: interval }, runDraw);
        }
        return runDraw();
    }

    var frameTimer = 0;
    var frameRaf = 0;

    function scheduleNextFrame(delay) {
        window.clearTimeout(frameTimer);
        frameTimer = window.setTimeout(function () {
            frameTimer = 0;
            if (halftoneState.runId !== runId || halftoneState.contextLost) return;
            if (window.requestAnimationFrame) {
                frameRaf = window.requestAnimationFrame(render);
            } else {
                render(performance.now());
            }
        }, Math.max(16, Number(delay) || getFrameInterval()));
    }

    function render(now) {
        var interval = getFrameInterval();

        frameRaf = 0;
        if (halftoneState.runId !== runId || halftoneState.contextLost) return;

        if (document.hidden) {
            lastVisualNow = now;
            scheduleNextFrame(250);
            return;
        }

        if (isClbiCompositorBusy()) {
            lastFrame = now;
            lastVisualNow = now;
            scheduleNextFrame(interval);
            return;
        }

        if (shouldSkipHalftoneDrawForGlobe()) {
            lastFrame = now;
            halftoneState.lastGlobeBusySkipAt = now;
            lastVisualNow = now;
            scheduleNextFrame(interval);
            return;
        }

        lastFrame = now;
        draw(now);
        scheduleNextFrame(interval);
    }

    draw(performance.now());
    scheduleNextFrame(getFrameInterval());

    document.addEventListener('visibilitychange', function () {
        if (!document.hidden && halftoneState.runId === runId && !halftoneState.contextLost) {
            window.clearTimeout(frameTimer);
            if (frameRaf && window.cancelAnimationFrame) window.cancelAnimationFrame(frameRaf);
            frameRaf = 0;
            scheduleNextFrame(16);
        }
    });

}

var CLBI_SVG_BELL = '<svg class="profile-svg profile-svg-bell" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10.268 21a2 2 0 0 0 3.464 0"/><path d="M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"/></svg>';
var CLBI_SVG_BELL_DOT = '<svg class="profile-svg profile-svg-bell-dot" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10.268 21a2 2 0 0 0 3.464 0"/><path d="M11.68 2.009A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673c-.824-.85-1.678-1.731-2.21-3.348"/><circle cx="18" cy="5" r="3"/></svg>';
var CLBI_SVG_LIST = '<svg class="profile-svg profile-svg-list" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 5h.01"/><path d="M3 12h.01"/><path d="M3 19h.01"/><path d="M8 5h13"/><path d="M8 12h13"/><path d="M8 19h13"/></svg>';
var CLBI_SVG_LANGUAGES = '<svg class="profile-svg profile-svg-languages" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 8 6 6"/><path d="m4 14 6-6 2-3"/><path d="M2 5h12"/><path d="M7 2h1"/><path d="m22 22-5-10-5 10"/><path d="M14 18h6"/></svg>';
var CLBI_SVG_POWER = '<svg class="profile-svg profile-svg-power" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 2v10"/><path d="M18.4 6.6a9 9 0 1 1-12.77.04"/></svg>';
var CLBI_SVG_SETTINGS = '<svg class="profile-svg profile-svg-settings" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"/><circle cx="12" cy="12" r="3"/></svg>';
var CLBI_SVG_SCAN_TEXT = '<svg class="profile-svg profile-svg-scan-text" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 7V5a2 2 0 0 1 2-2h2"/><path d="M17 3h2a2 2 0 0 1 2 2v2"/><path d="M21 17v2a2 2 0 0 1-2 2h-2"/><path d="M7 21H5a2 2 0 0 1-2-2v-2"/><path d="M7 8h8"/><path d="M7 12h10"/><path d="M7 16h6"/></svg>';
var CLBI_SVG_SCAN_EYE = '<svg class="profile-svg profile-svg-scan-eye" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 7V5a2 2 0 0 1 2-2h2"/><path d="M17 3h2a2 2 0 0 1 2 2v2"/><path d="M21 17v2a2 2 0 0 1-2 2h-2"/><path d="M7 21H5a2 2 0 0 1-2-2v-2"/><circle cx="12" cy="12" r="1"/><path d="M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0"/></svg>';
var CLBI_SVG_NEWSPAPER = '<svg class="profile-svg profile-svg-newspaper" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 18h-5"/><path d="M18 14h-8"/><path d="M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-4 0v-9a2 2 0 0 1 2-2h2"/><rect width="8" height="4" x="10" y="6" rx="1"/></svg>';
var CLBI_SVG_GREAT_WALL = '<svg class="profile-svg profile-svg-great-wall lucide lucide-paint-roller" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect width="16" height="6" x="2" y="2" rx="2"/><path d="M10 16v-2a2 2 0 0 1 2-2h8a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2"/><rect width="4" height="6" x="8" y="16" rx="1"/></svg>';
var CLBI_SVG_TROPHY = '<svg class="profile-svg profile-svg-trophy" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 14.66v1.626a2 2 0 0 1-.976 1.696A5 5 0 0 0 7 21.978"/><path d="M14 14.66v1.626a2 2 0 0 0 .976 1.696A5 5 0 0 1 17 21.978"/><path d="M18 9h1.5a1 1 0 0 0 0-5H18"/><path d="M4 22h16"/><path d="M6 9a6 6 0 0 0 12 0V3a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1z"/><path d="M6 9H4.5a1 1 0 0 1 0-5H6"/></svg>';
var CLBI_SVG_PACKAGE = '<svg class="profile-svg profile-svg-package" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3v6"/><path d="M16.76 3a2 2 0 0 1 1.8 1.1l2.23 4.479a2 2 0 0 1 .21.891V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V9.472a2 2 0 0 1 .211-.894L5.45 4.1A2 2 0 0 1 7.24 3z"/><path d="M3.054 9.013h17.893"/></svg>';

var PROFILE_RENDER_TOKEN = 0;

function invalidateProfileRender() {
    PROFILE_RENDER_TOKEN++;
}

$(function() {
    initHalftoneBackground();

// ── 하단 Plank 단축키 가이드 ──
function escapeClbiBottomGuideHtml(value) {
    return String(value == null ? '' : value)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

function readClbiBottomGuidePageName() {
    var pageName = window.mw && mw.config ? (mw.config.get('wgPageName') || '') : '';

    if (!pageName) {
        pageName = window.location.pathname || '';
    }

    return String(pageName)
        .split('?')[0]
        .replace(/^\/index\.php\//, '')
        .replace(/_/g, ' ')
        .trim();
}

function isClbiNationsShortcutContext() {
    var pageName = readClbiBottomGuidePageName();

    return pageName === '시대' ||
        pageName === 'Era' ||
        !!document.querySelector('.clbi-nations-panel-stack, .clbi-nations-globe-window, .clbi-nations-tabpanel');
}

function isClbiWikiEditShortcutContext() {
    var action = window.mw && mw.config ? String(mw.config.get('wgAction') || '') : '';
    var search = String(window.location.search || '');

    return action === 'edit' ||
        action === 'submit' ||
        /(?:^|[?&])action=(?:edit|submit)(?:&|$)/.test(search) ||
        !!document.querySelector('#editform, #wpSave, input[name="wpSave"], button[name="wpSave"]');
}


function isClbiNationListManagerShortcutContext() {
    return !!document.querySelector('.nation-list-manager');
}

function getClbiBottomShortcutItems() {
    if (isClbiWikiEditShortcutContext()) {
        return [
            { key: 'Ctrl+S', label: '변경사항 저장' }
        ];
    }


    if (isClbiNationListManagerShortcutContext()) {
        return [
            { key: 'Ctrl+S', label: '국가 목록 저장' }
        ];
    }

    if (isClbiNationsShortcutContext()) {
        return [
            { key: 'Q', label: '이전 시대' },
            { key: 'E', label: '다음 시대' },
            { key: 'Shift+Q', label: '이전 연도' },
            { key: 'Shift+E', label: '다음 연도' },
            { key: 'Ctrl+Q', label: '이전 대륙' },
            { key: 'Ctrl+E', label: '다음 대륙' }
        ];
    }

    return [];
}

function renderClbiBottomShortcutGuide() {
    var guide = document.getElementById('clbi-bottom-shortcut-guide');
    var items;
    var html;

    if (!guide) return;

    items = getClbiBottomShortcutItems();

    if (!items.length) {
        guide.classList.add('is-empty');
        guide.innerHTML = '';
        return;
    }

    guide.classList.remove('is-empty');

    html = '<div class="clbi-bottom-shortcut-list">';

    items.forEach(function (item) {
        html += '<div class="clbi-bottom-shortcut-item">' +
            '<span class="clbi-bottom-shortcut-key">' + escapeClbiBottomGuideHtml(item.key) + '</span>' +
            '<span class="clbi-bottom-shortcut-label">' + escapeClbiBottomGuideHtml(item.label) + '</span>' +
        '</div>';
    });

    html += '</div>';
    guide.innerHTML = html;
}

function buildClbiBottomPlankHtml(wrapId, navId, mainId) {
    return '' +
        '<div id="' + wrapId + '">' +
            '<div id="' + navId + '">' +
                '<div id="' + mainId + '">' +
                    '<div id="clbi-bottom-shortcut-guide" class="is-empty" aria-label="단축키 안내"></div>' +
                '</div>' +
            '</div>' +
        '</div>';
}

var CLBI_NATIONS_LAST_POINTER_X = null;
var CLBI_NATIONS_LAST_POINTER_Y = null;

function getClbiNationsTabAtPointer(tabpanel) {
    var element;
    var tab;

    if (!tabpanel) return null;
    if (CLBI_NATIONS_LAST_POINTER_X === null || CLBI_NATIONS_LAST_POINTER_Y === null) return null;
    if (typeof document.elementFromPoint !== 'function') return null;

    element = document.elementFromPoint(CLBI_NATIONS_LAST_POINTER_X, CLBI_NATIONS_LAST_POINTER_Y);
    if (!element) return null;

    tab = element.closest ? element.closest('.clbi-nations-tabpanel-tab[data-continent]') : null;

    if (!tab || !tabpanel.contains(tab)) return null;

    return tab;
}

function validateClbiNationsPointerHover(tabpanel, forceSuppress) {
    var tab = getClbiNationsTabAtPointer(tabpanel);
    var suppressContinent;
    var tabContinent;
    var tabIsActive;

    if (!tabpanel) return;

    if (!tab) {
        clearClbiNationsKeyboardHoverSuppressed(tabpanel);
        return;
    }

    tabContinent = tab.getAttribute('data-continent') || '';
    tabIsActive = tab.classList.contains('is-active') || tab.getAttribute('aria-selected') === 'true';

    if (tabIsActive) {
        clearClbiNationsKeyboardHoverSuppressed(tabpanel);
        return;
    }

    suppressContinent = tabpanel.getAttribute('data-clbi-hover-suppress-continent') || '';

    if (forceSuppress || !suppressContinent) {
        tabpanel.classList.add('is-keyboard-switching');
        tabpanel.setAttribute('data-clbi-hover-suppress-continent', tabContinent);
        return;
    }

    if (suppressContinent === tabContinent) {
        tabpanel.classList.add('is-keyboard-switching');
        return;
    }

    /*
     * The pointer actually moved onto another tab after the keyboard switch.
     * At that point this is no longer stale browser :hover; let normal hover work.
     */
    clearClbiNationsKeyboardHoverSuppressed(tabpanel);
}

function validateAllClbiNationsPointerHovers() {
    var panels = document.querySelectorAll('.clbi-nations-tabpanel.is-keyboard-switching');

    Array.prototype.forEach.call(panels, function (tabpanel) {
        if (isClbiNationsPanelOwnedTabpanel(tabpanel)) return;
        validateClbiNationsPointerHover(tabpanel, false);
    });
}

function isClbiNationsPanelOwnedTabpanel(tabpanel) {
    /*
     * Mouse continent tab regression guard.
     * -------------------------------------
     * Detached SPA preparation serializes attributes/classes but it cannot
     * serialize DOM event listeners or JS properties.  The NationsPanel fix
     * therefore uses the DOM property CLBI_NationsPanelOwned /
     * CLBI_NationsTabPanelBound as the real ownership marker.
     *
     * Do NOT treat data-nations-tabpanel-ready or clbi-nations-continent-cache
     * as ownership here.  Those can survive innerHTML insertion while the real
     * click listeners were lost, causing Common.js to delegate to a panel that
     * NationsPanel has not rebound yet.  The fallback below must remain able to
     * handle mouse clicks until NationsPanel reclaims the live DOM node.
     */
    return !!(tabpanel && tabpanel.CLBI_NationsPanelOwned);
}

function isClbiNationsLiveContinentActive(tabpanel, continent) {
    var tab;
    var panel;

    if (!tabpanel || !continent) return false;

    tab = Array.prototype.slice.call(tabpanel.querySelectorAll('.clbi-nations-tabpanel-tab[data-continent]')).find(function (candidate) {
        return candidate.getAttribute('data-continent') === continent;
    });

    panel = Array.prototype.slice.call(tabpanel.querySelectorAll('.clbi-nations-tabpanel-continent[data-continent-panel]')).find(function (candidate) {
        return candidate.getAttribute('data-continent-panel') === continent;
    });

    return !!(
        tab &&
        panel &&
        (tab.classList.contains('is-active') || tab.getAttribute('aria-selected') === 'true') &&
        panel.classList.contains('is-active') &&
        panel.getAttribute('aria-hidden') !== 'true' &&
        !panel.hasAttribute('hidden')
    );
}

function activateClbiNationsContinent(tabpanel, targetContinent, options) {
    var tabs;
    var panels;
    var skipOwner = !!(options && options.skipOwner);

    if (!tabpanel || !targetContinent) return false;

    if (!skipOwner && isClbiNationsPanelOwnedTabpanel(tabpanel)) {
        var owner = window.NationsPanel || window.CLBI_NATIONS_PANEL || null;

        if (owner && typeof owner.activateContinent === 'function') {
            try {
                if (owner.activateContinent(targetContinent, {
                    source: 'common-legacy-click',
                    panel: tabpanel
                })) {
                    return true;
                }
            } catch (err) {}
        }

        /*
         * Ownership markers can be stale during SPA/hydration edge cases.  If
         * the owner API is missing or refuses the live panel, do not drop the
         * mouse click.  Fall through to the local fallback so pointer users are
         * never left with keyboard-only continent tabs.
         */
    }

    tabs = Array.prototype.slice.call(tabpanel.querySelectorAll('.clbi-nations-tabpanel-tab[data-continent]'));
    panels = Array.prototype.slice.call(tabpanel.querySelectorAll('.clbi-nations-tabpanel-continent[data-continent-panel]'));

    if (!tabs.length || !panels.length) return false;

    tabs.forEach(function (tab) {
        var active = tab.getAttribute('data-continent') === targetContinent;
        tab.classList.toggle('is-active', active);
        tab.setAttribute('aria-selected', active ? 'true' : 'false');
        tab.setAttribute('tabindex', active ? '0' : '-1');
    });

    panels.forEach(function (panel) {
        var active = panel.getAttribute('data-continent-panel') === targetContinent;
        panel.classList.toggle('is-active', active);

        if (active) {
            panel.removeAttribute('hidden');
        } else {
            panel.setAttribute('hidden', 'hidden');
        }
    });

    try {
        if (window.Decorations && typeof window.Decorations.sync === 'function') window.Decorations.sync();
        else if (window.CLBI_DECORATIONS && typeof window.CLBI_DECORATIONS.sync === 'function') window.CLBI_DECORATIONS.sync();
    } catch (err) {}

    return true;
}

function setClbiNationsKeyboardHoverSuppressed(tabpanel) {
    validateClbiNationsPointerHover(tabpanel, true);
}

function clearClbiNationsKeyboardHoverSuppressed(tabpanel) {
    if (!tabpanel) return;
    tabpanel.classList.remove('is-keyboard-switching');
    tabpanel.removeAttribute('data-clbi-hover-suppress-continent');
}

function moveClbiNationsContinent(direction) {
    var tabpanel = document.querySelector('.clbi-nations-tabpanel');
    var tabs;
    var activeIndex;
    var nextIndex;
    var target;

    if (!tabpanel) return false;

    if (isClbiNationsPanelOwnedTabpanel(tabpanel) &&
        window.CLBI_NATIONS_PANEL &&
        typeof window.CLBI_NATIONS_PANEL.moveContinent === 'function') {
        return !!window.CLBI_NATIONS_PANEL.moveContinent(direction, {
            source: 'common-legacy-keyboard',
            panel: tabpanel
        });
    }

    tabs = Array.prototype.slice.call(tabpanel.querySelectorAll('.clbi-nations-tabpanel-tab[data-continent]'));
    if (!tabs.length) return false;

    activeIndex = tabs.findIndex(function (tab) {
        return tab.classList.contains('is-active') || tab.getAttribute('aria-selected') === 'true';
    });

    if (activeIndex < 0) activeIndex = 0;

    nextIndex = (activeIndex + direction + tabs.length) % tabs.length;
    target = tabs[nextIndex].getAttribute('data-continent');

    if (activateClbiNationsContinent(tabpanel, target)) {
        setClbiNationsKeyboardHoverSuppressed(tabpanel);
        window.setTimeout(function () {
            validateClbiNationsPointerHover(tabpanel, false);
        }, 0);
        return true;
    }

    return false;
}

function initClbiNationsTabpanelControls(root) {
    var scope = root && root.querySelectorAll ? root : document;
    var panels = scope.querySelectorAll('.clbi-nations-tabpanel');

    Array.prototype.forEach.call(panels, function (tabpanel) {
        /*
         * Common.js is only a safety fallback for continent tabs; NationsPanel
         * is the primary owner.  This guard must be a DOM property, not a
         * serialized attribute.  SPA warm prepaint can preserve
         * data-clbi-nations-tabs-ready="1" while losing the actual event
         * listeners, which was the root cause of mouse clicks no longer moving
         * continents while keyboard shortcuts still worked.
         */
        if (tabpanel.CLBI_NationsCommonTabsBound) return;
        tabpanel.CLBI_NationsCommonTabsBound = true;
        tabpanel.setAttribute('data-clbi-nations-tabs-ready', '1');

        tabpanel.addEventListener('pointerdown', function () {
            clearClbiNationsKeyboardHoverSuppressed(tabpanel);
        });

        tabpanel.addEventListener('pointerleave', function () {
            clearClbiNationsKeyboardHoverSuppressed(tabpanel);
        });

        tabpanel.addEventListener('click', function (event) {
            var tab = event.target.closest ? event.target.closest('.clbi-nations-tabpanel-tab[data-continent]') : null;

            if (!tab || !tabpanel.contains(tab)) return;

            clearClbiNationsKeyboardHoverSuppressed(tabpanel);

            if (activateClbiNationsContinent(tabpanel, tab.getAttribute('data-continent'))) {
                event.preventDefault();
            }
        });

        tabpanel.addEventListener('keydown', function (event) {
            var tab = event.target.closest ? event.target.closest('.clbi-nations-tabpanel-tab[data-continent]') : null;
            var handled = false;

            if (!tab || !tabpanel.contains(tab)) return;

            if (event.key === 'ArrowLeft') handled = moveClbiNationsContinent(-1);
            else if (event.key === 'ArrowRight') handled = moveClbiNationsContinent(1);

            if (handled) {
                event.preventDefault();
                event.stopPropagation();
            }
        });
    });
}

function handleClbiNationsContinentDocumentClick(event) {
    var target;
    var tab;
    var tabpanel;
    var continent;
    var owner;
    var handled = false;

    if (!event || event.__clbiNationsContinentHandled) return;
    target = event.target;
    if (!target || !target.closest) return;

    tab = target.closest('.clbi-nations-tabpanel-tab[data-continent]');
    if (!tab) return;

    tabpanel = tab.closest ? tab.closest('.clbi-nations-tabpanel') : null;
    if (!tabpanel || !tabpanel.contains(tab)) return;

    continent = tab.getAttribute('data-continent') || '';
    if (!continent) return;

    /*
     * Final live-DOM mouse delegate.
     * --------------------------------
     * The continent tab UI has two initialization phases: detached preparation
     * for seamless SPA entry, then live DOM hydration.  Detached preparation can
     * leave serialized "ready" attributes behind while losing event listeners.
     * Keyboard shortcuts still work because they call the public NationsPanel
     * API directly, but mouse clicks depend on live listeners.  This capturing
     * delegate is intentionally independent of per-panel ready attributes: it
     * always resolves the clicked live tab and hands it to NationsPanel first,
     * then falls back to the local Common.js switcher if needed.
     */
    event.__clbiNationsContinentHandled = true;
    clearClbiNationsKeyboardHoverSuppressed(tabpanel);

    owner = window.NationsPanel || window.CLBI_NATIONS_PANEL || null;
    if (owner && typeof owner.activateContinent === 'function') {
        try {
            handled = !!owner.activateContinent(continent, {
                source: 'mouse-click-live-delegate',
                panel: tabpanel
            });
        } catch (err) {
            handled = false;
        }

        /*
         * Owner API stale-cache guard.
         *
         * A previous regression came from NationsPanel returning true after it
         * updated cached/detached tab nodes instead of the clicked live tab. A
         * true return value alone is therefore not enough for mouse input. Verify
         * the live DOM that received the click. If it did not become active,
         * bypass the owner and run the Common.js live query fallback directly.
         */
        if (handled && !isClbiNationsLiveContinentActive(tabpanel, continent)) {
            handled = false;
        }
    }

    if (!handled) {
        handled = activateClbiNationsContinent(tabpanel, continent, { skipOwner: true });
    }

    if (handled) {
        try { playStaticSound(); } catch (err2) {}
        event.preventDefault();
        event.stopPropagation();
        if (typeof event.stopImmediatePropagation === 'function') event.stopImmediatePropagation();
    }
}

function initClbiNationsGlobalClickDelegate() {
    if (document.body.getAttribute('data-clbi-nations-global-click-ready') === '1') return;
    document.body.setAttribute('data-clbi-nations-global-click-ready', '1');
    document.addEventListener('click', handleClbiNationsContinentDocumentClick, true);
}


function initClbiNationsPointerHoverValidation() {
    if (document.body.getAttribute('data-clbi-nations-pointer-hover-ready') === '1') return;

    document.body.setAttribute('data-clbi-nations-pointer-hover-ready', '1');

    document.addEventListener('pointermove', function (event) {
        CLBI_NATIONS_LAST_POINTER_X = event.clientX;
        CLBI_NATIONS_LAST_POINTER_Y = event.clientY;
        validateAllClbiNationsPointerHovers();
    }, true);

    document.addEventListener('pointerleave', function () {
        CLBI_NATIONS_LAST_POINTER_X = null;
        CLBI_NATIONS_LAST_POINTER_Y = null;
        validateAllClbiNationsPointerHovers();
    }, true);

    window.addEventListener('blur', function () {
        CLBI_NATIONS_LAST_POINTER_X = null;
        CLBI_NATIONS_LAST_POINTER_Y = null;
        validateAllClbiNationsPointerHovers();
    });
}


function initClbiBottomShortcutSystem(root) {
    renderClbiBottomShortcutGuide();
    initClbiNationsGlobalClickDelegate();
    initClbiNationsTabpanelControls(root || document);
    initClbiNationsPointerHoverValidation();
}

// ── 상·하단 네비게이션 바 ──
function buildClbiNavHtml(position) {
    var isBottom = position === 'bottom';
    var base = isBottom ? 'clbi-bottom' : 'clbi-top';
    var shortBase = isBottom ? 'clbi-bnav' : 'clbi-tnav';
    var wrapId = base + '-nav-wrap';
    var navId = base + '-nav';
    var mainId = base + '-nav-main';
    var tabsId = base + '-nav-tabs';
    var searchId = base + '-nav-search';
    var inputId = isBottom ? 'clbi-bottom-search-input' : 'clbi-top-search-input';
    var worldId = shortBase + '-worldbuilding';
    var subId = isBottom ? 'clbi-bottom-sub-worldbuilding' : 'clbi-sub-worldbuilding';
    var subInnerId = subId + '-inner';

    if (isBottom) {
        return buildClbiBottomPlankHtml(wrapId, navId, mainId);
    }

    return '' +
        '<div id="' + wrapId + '">' +
            '<div id="' + navId + '">' +
                '<div id="' + mainId + '">' +
                    '<div id="' + tabsId + '">' +
                        '<a class="clbi-top-nav-item" href="/index.php/대문">' +
                            '<img class="clbi-tnav-icon" src="/index.php?title=특수:Redirect/file/Ic-main-menu-001.png" alt="">' +
                            '<span class="clbi-tnav-label">메인 메뉴</span>' +
                        '</a>' +
                        '<a class="clbi-top-nav-item" href="/index.php/프로젝트:소개">' +
                            '<img class="clbi-tnav-icon" src="/index.php?title=특수:Redirect/file/Ic-project-001.png" alt="">' +
                            '<span class="clbi-tnav-label">프로젝트</span>' +
                        '</a>' +
                        '<div class="clbi-top-nav-item" id="' + worldId + '">' +
                            '<img class="clbi-tnav-icon" src="/index.php?title=특수:Redirect/file/Ic-worldbuilding-001.png" alt="">' +
                            '<span class="clbi-tnav-label">세계관</span>' +
                            '<span class="clbi-tnav-arrow">▾</span>' +
                        '</div>' +
                    '</div>' +
                    (isBottom ? '' : (
                        '<div id="' + searchId + '">' +
                            '<input type="text" id="' + inputId + '" placeholder="검색...">' +
                        '</div>'
                    )) +
                '</div>' +
                '<div id="' + subId + '">' +
                    '<div id="' + subInnerId + '">' +
                        '<div class="clbi-tnav-sub-list">' +
                            '<a class="clbi-tnav-sub-item" href="/index.php/시대">시대</a>' +
                            '<a class="clbi-tnav-sub-item" href="/index.php/설정">설정</a>' +
                            '<a class="clbi-tnav-sub-item" href="/index.php/기업_및_공동체">기업 및 공동체</a>' +
                            '<a class="clbi-tnav-sub-item" href="/index.php/군_정치집단">군, 정치집단</a>' +
                            '<a class="clbi-tnav-sub-item" href="/index.php/인물">인물</a>' +
                        '</div>' +
                    '</div>' +
                '</div>' +
            '</div>' +
        '</div>';
}

function normalizeClbiShellDomOrder() {
    var contentWrapper = document.querySelector('.content-wrapper');
    var topNav = document.getElementById('clbi-top-nav-wrap');
    var bottomNav = document.getElementById('clbi-bottom-nav-wrap');
    var canvas = document.getElementById('site-halftone-bg');
    var anchor;
    var viewportH;
    var topRect;
    var wrapperRect;
    var needsRecovery;
    var expectedWrapperTop;
    var host;

    if (!contentWrapper || !topNav || !bottomNav || !document.body) return;

    /*
    CLBI shell can live inside a Liberty <section>.  Some skins/layouts give that
    section a flow context that lets the top nav visually overlap the content
    wrapper even when DOM sibling order is correct.  Mark the common parent and
    let Layout.css force a simple vertical flow for the shell.
    */
    host = topNav.parentElement === contentWrapper.parentElement &&
        contentWrapper.parentElement === bottomNav.parentElement
        ? contentWrapper.parentElement
        : null;

    if (host) {
        host.classList.add('clbi-shell-host');
    }

    viewportH = window.innerHeight || document.documentElement.clientHeight || 0;
    topRect = topNav.getBoundingClientRect();
    wrapperRect = contentWrapper.getBoundingClientRect();
    expectedWrapperTop = topRect.bottom + 8;

    needsRecovery = false;

    if (viewportH > 0) {
        if (topRect.top >= viewportH * 0.55) needsRecovery = true;
        if (wrapperRect.top >= viewportH * 0.60) needsRecovery = true;
    }

    if (topRect.top > 240 || wrapperRect.top > 320) {
        needsRecovery = true;
    }

    if (wrapperRect.top < expectedWrapperTop - 1) {
        needsRecovery = true;
    }

    if (!needsRecovery) {
        document.body.classList.add('clbi-shell-ready');
        return;
    }

    anchor = canvas && canvas.parentNode === document.body
        ? canvas.nextSibling
        : document.body.firstChild;

    document.body.insertBefore(topNav, anchor);
    document.body.insertBefore(contentWrapper, topNav.nextSibling);
    document.body.insertBefore(bottomNav, contentWrapper.nextSibling);

    document.body.classList.add('clbi-shell-ready');
}

window.normalizeClbiShellDomOrder = normalizeClbiShellDomOrder;


function ensureClbiVerticalScaleHost() {
    var topNav = document.getElementById('clbi-top-nav-wrap');
    var contentWrapper = document.querySelector('.content-wrapper');
    var bottomNav = document.getElementById('clbi-bottom-nav-wrap');
    var host;
    var existing;
    var parent;

    if (!topNav || !contentWrapper || !bottomNav || !document.body) return null;

    existing = document.getElementById('clbi-shell-scale-host');

    if (existing && existing.contains(topNav) && existing.contains(contentWrapper) && existing.contains(bottomNav)) {
        existing.classList.add('clbi-shell-host');
        return existing;
    }

    parent = topNav.parentElement === contentWrapper.parentElement && contentWrapper.parentElement === bottomNav.parentElement
        ? topNav.parentElement
        : null;

    if (parent && parent !== document.body) {
        parent.classList.add('clbi-shell-host');
        parent.id = parent.id || 'clbi-shell-scale-host';
        return parent;
    }

    host = existing || document.createElement('div');
    host.id = 'clbi-shell-scale-host';
    host.className = 'clbi-shell-host';

    if (!host.parentNode) {
        document.body.insertBefore(host, topNav);
    }

    host.appendChild(topNav);
    host.appendChild(contentWrapper);
    host.appendChild(bottomNav);

    return host;
}

function readClbiRootPx(name, fallback) {
    var raw = '';
    var value;

    try {
        raw = getComputedStyle(document.documentElement).getPropertyValue(name);
    } catch (err) {}

    value = parseFloat(raw);
    return isFinite(value) && value > 0 ? value : fallback;
}

function resetLeftRecentAdaptiveState() {
    var list = document.getElementById('clbi-left-recent-list');
    var newsBox = list ? list.closest('.clbi-left-news-box') : null;
    var items = list ? Array.prototype.slice.call(list.querySelectorAll('.news-recent-item')) : [];

    if (newsBox) {
        newsBox.classList.remove('is-adaptive-constrained');
        newsBox.style.removeProperty('--adaptive-news-h');
    }

    if (list) {
        list.classList.remove('is-adaptive-faded');
        list.removeAttribute('data-adaptive-limit');
        list.style.removeProperty('--adaptive-recent-h');
    }

    items.forEach(function (item) {
        item.classList.remove('is-adaptive-hidden');
    });
}

function resetLeftBillboardAdaptiveState() {
    var box = document.querySelector('#clbi-left-sidebar .left-billboard-box');

    if (!box) return;

    box.classList.remove('is-left-ad-title-only', 'is-left-ad-extended');
    box.style.removeProperty('--left-billboard-h');
    box.style.removeProperty('--left-billboard-finish-h');
}

function updateClbiShellVerticalScale() {
    var root = document.documentElement;
    var body = document.body;
    var host;
    var topInner;
    var bottomInner;
    var thresholdH;
    var gap;
    var outerGapTotal;
    var baseStageH;
    var stageW;
    var stageH;
    var viewportW;
    var viewportH;
    var availableW;
    var availableH;
    var topH;
    var bottomH;
    var contentH;
    var widthScale;
    var heightScale;
    var scale;
    var shouldScale;

    if (!root || !body) return;

    host = ensureClbiVerticalScaleHost();
    if (!host) return;

    thresholdH = readClbiRootPx('--clbi-vertical-scale-threshold-h', 1080);
    gap = readClbiRootPx('--layout-gap', 8);
    outerGapTotal = gap * 2;
    baseStageH = Math.max(420, thresholdH - outerGapTotal);
    stageW = readClbiRootPx('--layout-shell-w', 1880);

    viewportW = Math.max(320, window.innerWidth || document.documentElement.clientWidth || stageW);
    viewportH = Math.max(320, window.innerHeight || document.documentElement.clientHeight || thresholdH);
    availableW = Math.max(240, viewportW - outerGapTotal);
    availableH = Math.max(240, viewportH - outerGapTotal);

    /*
    평상시에는 기존 세로 채움 레이아웃을 기준으로 삼는다.
    세로가 기준점보다 작아지는 경우에는 기준 높이를 고정점으로 삼고,
    가로만 부족한 경우에는 현재 사용 가능한 세로 높이를 고정점으로 삼는다.
    이렇게 해야 가로 부족으로 scale에 들어갈 때 본문 높이가 갑자기 접히지 않는다.
    */
    stageH = availableH >= baseStageH ? availableH : baseStageH;

    topInner = document.getElementById('clbi-top-nav');
    bottomInner = document.getElementById('clbi-bottom-nav');

    topH = topInner ? Math.ceil(topInner.offsetHeight || topInner.getBoundingClientRect().height || 38) : 38;
    bottomH = bottomInner ? Math.ceil(bottomInner.offsetHeight || bottomInner.getBoundingClientRect().height || 38) : 38;
    contentH = Math.max(360, Math.floor(stageH - topH - bottomH - (gap * 2)));

    widthScale = availableW < stageW ? availableW / stageW : 1;
    heightScale = availableH < baseStageH ? availableH / baseStageH : 1;
    scale = Math.min(1, widthScale, heightScale);
    scale = Math.max(0.50, Math.min(1, Math.floor(scale * 1000) / 1000));
    shouldScale = scale < 0.999;

    setClbiRootMetric(root, '--clbi-stage-design-w', stageW + 'px');
    setClbiRootMetric(root, '--clbi-stage-design-h', Math.floor(stageH) + 'px');
    setClbiRootMetric(root, '--clbi-stage-content-h', contentH + 'px');
    setClbiRootMetric(root, '--clbi-shell-scale', String(scale));

    if (body.classList.contains('clbi-shell-vertical-scale') !== shouldScale) {
        body.classList.toggle('clbi-shell-vertical-scale', shouldScale);
    }

    if (shouldScale) {
        resetLeftRecentAdaptiveState();
        resetLeftBillboardAdaptiveState();
    }
}
window.updateClbiShellVerticalScale = updateClbiShellVerticalScale;

var $contentWrapper = $('.content-wrapper').first();

if ($contentWrapper.length) {
    $('#clbi-top-nav-wrap, #clbi-bottom-nav-wrap').remove();
    $contentWrapper.before(buildClbiNavHtml('top'));
    $contentWrapper.after(buildClbiNavHtml('bottom'));
    renderClbiBottomShortcutGuide();
    initClbiNationsTabpanelControls(document);
    if (typeof window.normalizeClbiShellDomOrder === 'function') window.normalizeClbiShellDomOrder();
}

var CLBI_SHELL_METRICS_RAF = null;
var CLBI_SHELL_METRICS_SETTLE_TIMER = null;
var CLBI_SHELL_METRICS_LAST = { topH:-1, bottomH:-1 };

function setClbiRootMetric(root, name, value) {
    var next = String(value);
    if (root.style.getPropertyValue(name) === next) return false;
    root.style.setProperty(name, next);
    return true;
}

function runClbiShellMetricsBatch() {
    var top = document.getElementById('clbi-top-nav-wrap');
    var bottom = document.getElementById('clbi-bottom-nav-wrap');
    var root = document.documentElement;
    var topH = 0;
    var bottomH = 0;

    CLBI_SHELL_METRICS_RAF = null;
    if (!root) return;

    if (top) topH = Math.ceil(top.offsetHeight || top.getBoundingClientRect().height || 0);
    if (bottom) bottomH = Math.ceil(bottom.offsetHeight || bottom.getBoundingClientRect().height || 0);

    if (topH !== CLBI_SHELL_METRICS_LAST.topH) {
        CLBI_SHELL_METRICS_LAST.topH = topH;
        setClbiRootMetric(root, '--clbi-top-nav-outer-h', topH + 'px');
    }
    if (bottomH !== CLBI_SHELL_METRICS_LAST.bottomH) {
        CLBI_SHELL_METRICS_LAST.bottomH = bottomH;
        setClbiRootMetric(root, '--clbi-bottom-nav-outer-h', bottomH + 'px');
    }

    if (typeof updateClbiShellVerticalScale === 'function') updateClbiShellVerticalScale();
    if (typeof scheduleAdaptiveLeftRecentItems === 'function') scheduleAdaptiveLeftRecentItems();
    if (typeof scheduleClbiContentBottomGap === 'function') scheduleClbiContentBottomGap();
}

function requestClbiShellMetricsFrame() {
    if (CLBI_SHELL_METRICS_RAF !== null) return;
    CLBI_SHELL_METRICS_RAF = window.requestAnimationFrame
        ? window.requestAnimationFrame(runClbiShellMetricsBatch)
        : window.setTimeout(runClbiShellMetricsBatch, 16);
}

function scheduleClbiShellMetrics() {
    requestClbiShellMetricsFrame();
    window.clearTimeout(CLBI_SHELL_METRICS_SETTLE_TIMER);
    CLBI_SHELL_METRICS_SETTLE_TIMER = window.setTimeout(function () {
        CLBI_SHELL_METRICS_SETTLE_TIMER = null;
        requestClbiShellMetricsFrame();
    }, 120);
}
function watchClbiShellMetrics() {
    var top = document.getElementById('clbi-top-nav-wrap');
    var bottom = document.getElementById('clbi-bottom-nav-wrap');
    var observer;

    scheduleClbiShellMetrics();

    $(window).on('resize orientationchange', scheduleClbiShellMetrics);
    $(window).on('pageshow.clbiShellScale focus.clbiShellScale', scheduleClbiShellMetrics);
    document.addEventListener('visibilitychange', function () {
        if (!document.hidden) scheduleClbiShellMetrics();
    });
    $(window).on('resize.clbiLeftBillboard orientationchange.clbiLeftBillboard', scheduleLeftSidebarVerticalFit);
    $(window).on('resize.clbiRecentViewport orientationchange.clbiRecentViewport', function () { scheduleAdaptiveLeftRecentItems(); scheduleClbiContentBottomGap(); });
    $(window).on('resize.clbiContentBottomGap orientationchange.clbiContentBottomGap', scheduleClbiContentBottomGap);

    if (window.ResizeObserver) {
        observer = new ResizeObserver(scheduleClbiShellMetrics);
        if (top) observer.observe(top);
        if (bottom) observer.observe(bottom);
        window.CLBI_SHELL_RESIZE_OBSERVER = observer;
    }
}

function bindClbiWorldbuildingToggle(buttonSelector, menuSelector) {
    $(buttonSelector).on('click', function() {
        var $menu = $(menuSelector);
        var $btn = $(this);

        $menu.toggleClass('worldbuilding-open');
        $btn.toggleClass('clbi-tnav-active', $menu.hasClass('worldbuilding-open'));
        scheduleClbiShellMetrics();
    });
}

bindClbiWorldbuildingToggle('#clbi-tnav-worldbuilding', '#clbi-sub-worldbuilding');
bindClbiWorldbuildingToggle('#clbi-bnav-worldbuilding', '#clbi-bottom-sub-worldbuilding');

$('#clbi-top-search-input, #clbi-bottom-search-input').on('keydown', function(e) {
    if (e.key === 'Enter') {
        var q = $(this).val().trim();
        if (q) window.location.href = '/index.php?search=' + encodeURIComponent(q);
    }
});

if (window.mw && mw.hook) {
    mw.hook('wikipage.content').add(function ($content) {
        initClbiBottomShortcutSystem($content && $content[0] ? $content[0] : document);
    });
}

watchClbiShellMetrics();

});

// 페이지 전환 사운드
var transitionSound = new Audio('/index.php?title=특수:Redirect/file/Sfx-ui-001.mp3');

(function() {
    var master = parseFloat(localStorage.getItem('clbi-audio-master') || 80) / 100;
    var sfx = parseFloat(localStorage.getItem('clbi-audio-sfx') || 60) / 100;
    var sfxOn = localStorage.getItem('clbi-audio-sfxOn') !== 'false';
    transitionSound.volume = sfxOn ? master * sfx : 0;
})();

function playStaticSound() {
    var master = parseFloat(localStorage.getItem('clbi-audio-master') || 80) / 100;
    var sfx = parseFloat(localStorage.getItem('clbi-audio-sfx') || 60) / 100;
    var sfxOn = localStorage.getItem('clbi-audio-sfxOn') !== 'false';

    if (!sfxOn) return;

    transitionSound.volume = master * sfx;
    transitionSound.currentTime = 0;
    transitionSound.play();
}

// 현재 언어 감지
function getCurrentLang() {
    var langData = document.getElementById('clbi-lang-data');
    return langData ? (langData.getAttribute('data-lang') || 'ko') : 'ko';
}

function normalizePageName(value) {
    return String(value || '')
        .split('?')[0]
        .replace(/^\/index\.php\//, '')
        .replace(/_/g, ' ')
        .trim();
}

function buildWikiPath(title) {
    return '/index.php/' + encodeURI(String(title || '').replace(/ /g, '_'));
}

function getLangShortCode(lang) {
    var map = { ko: 'KR', en: 'EN', zh: 'ZH', ja: 'JA', ru: 'RU', es: 'ES' };
    return map[lang] || String(lang || '').toUpperCase();
}

function getLanguageTargetTitle(lang) {
    var data = document.getElementById('clbi-lang-data');
    if (!data || !lang) return '';

    var keys = [
        'data-' + lang,
        'data-page-' + lang,
        'data-title-' + lang,
        'data-target-' + lang,
        'data-lang-' + lang
    ];

    for (var i = 0; i < keys.length; i++) {
        var value = data.getAttribute(keys[i]);
        if (value) return value;
    }

    return '';
}

function escapeClbiHtml(value) {
    return String(value == null ? '' : value)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}


var SIDEBAR_LANG_SVG_NS = 'http://www.w3.org/2000/svg';
var SIDEBAR_LANGUAGE_STATUS_TITLE = 'MediaWiki:LanguageStatus.json';
var SIDEBAR_LANGUAGE_LABELS = {
    ko: '한국어',
    en: 'English',
    zh: '中文',
    ja: '日本語',
    ru: 'Русский',
    es: 'Español'
};
var SIDEBAR_LANGUAGE_DIAL_LABELS = {
    ko: '한국어',
    en: 'ENG',
    zh: '中文',
    ja: '日本語',
    ru: 'РУС',
    es: 'ESP'
};
var SIDEBAR_LANGUAGE_STATUS_VALUES = {
    available: true,
    wip: true,
    unavailable: true
};

var sidebarLanguageStatusRegistry = {};
var sidebarLanguageStatusLoaded = false;
var sidebarLanguageStatusLoading = false;
var sidebarLanguageStatusCallbacks = [];

var sidebarLanguageState = {
    order: ['ko', 'en', 'zh', 'ja', 'ru', 'es'],
    currentLang: 'ko',
    baseIndex: 0,
    selectedIndex: 0,
    rotation: 0,
    dragging: false,
    dragMoved: false,
    dragStartX: 0,
    dragStartY: 0,
    dragStartRotation: 0,
    dragAxis: null,
    pointerCaptured: false,
    lastX: 0,
    lastTime: 0,
    releaseVelocity: 0,
    suppressClickUntil: 0,
    raf: null,
    pendingRotation: 0,
    snapTimer: null,
    inertiaRaf: null,
    navigateTimer: null,
    bound: false,
    boundElement: null,
    rotor: null,
    cx: 101,
    cy: 119,
    outerR: 109,
    innerR: 28,
    sectorAngle: 30,
    halfSector: 15,
    repeats: 8,
    dragSensitivity: 0.58,
    maxSpinVelocity: 1.75,
    minSpinVelocity: 0.055,
    spinDecel: 0.00185
};

function createSidebarLanguageSvgEl(tag) {
    return document.createElementNS(SIDEBAR_LANG_SVG_NS, tag);
}

function normalizeSidebarLanguageIndex(index) {
    var length = sidebarLanguageState.order.length;
    var normalized = index % length;
    return normalized < 0 ? normalized + length : normalized;
}

function getSidebarLanguageName(lang) {
    return SIDEBAR_LANGUAGE_LABELS[lang] || String(lang || '').toUpperCase();
}

function getSidebarLanguageDialName(lang) {
    return SIDEBAR_LANGUAGE_DIAL_LABELS[lang] || getSidebarLanguageName(lang);
}

function normalizeSidebarLanguageStatusValue(value) {
    value = String(value == null ? '' : value).toLowerCase().trim();
    return SIDEBAR_LANGUAGE_STATUS_VALUES[value] ? value : '';
}

function getSidebarLanguageStatusPageKey() {
    var raw = String(mw.config.get('wgPageName') || '').trim();
    var normalized = normalizePageName(raw);

    return normalized || raw || '대문';
}

function getSidebarLanguageStatusEntry() {
    var registry = sidebarLanguageStatusRegistry || {};
    var pages = registry.pages && typeof registry.pages === 'object' ? registry.pages : registry;
    var raw = String(mw.config.get('wgPageName') || '').trim();
    var normalized = normalizePageName(raw);
    var title = String(mw.config.get('wgTitle') || '').trim();
    var keys = [
        normalized,
        raw,
        raw.replace(/_/g, ' '),
        normalized.replace(/ /g, '_'),
        title,
        title.replace(/_/g, ' ')
    ];
    var i;

    for (i = 0; i < keys.length; i += 1) {
        if (keys[i] && pages[keys[i]] && typeof pages[keys[i]] === 'object') {
            return pages[keys[i]];
        }
    }

    return {};
}

function getSidebarLanguageStatusOverride(lang) {
    var entry = getSidebarLanguageStatusEntry();
    return normalizeSidebarLanguageStatusValue(entry[lang]);
}

function flushSidebarLanguageStatusCallbacks() {
    var callbacks = sidebarLanguageStatusCallbacks.slice();
    sidebarLanguageStatusCallbacks.length = 0;

    callbacks.forEach(function(callback) {
        if (typeof callback === 'function') {
            callback(sidebarLanguageStatusRegistry);
        }
    });
}

function loadSidebarLanguageStatusRegistry(callback, force) {
    if (typeof callback === 'function') {
        sidebarLanguageStatusCallbacks.push(callback);
    }

    if (sidebarLanguageStatusLoaded && !force) {
        flushSidebarLanguageStatusCallbacks();
        return;
    }

    if (sidebarLanguageStatusLoading) return;

    sidebarLanguageStatusLoading = true;

    function finishLanguageStatus(parsed) {
        sidebarLanguageStatusRegistry = parsed && typeof parsed === 'object' ? parsed : {};
        sidebarLanguageStatusLoaded = true;
        sidebarLanguageStatusLoading = false;
        flushSidebarLanguageStatusCallbacks();
    }

    if (!force && window.EntryStore && typeof window.EntryStore.fetchJsonRef === 'function') {
        window.EntryStore.fetchJsonRef(SIDEBAR_LANGUAGE_STATUS_TITLE, { noStore: false })
            .then(function (parsed) { finishLanguageStatus(parsed); })
            .catch(function () { finishLanguageStatus({}); });
        return;
    }

    (function () {
        var url = mw.util.getUrl(SIDEBAR_LANGUAGE_STATUS_TITLE, {
            action: 'raw',
            ctype: 'application/json'
        });
        if (window.RevisionManifest && typeof window.RevisionManifest.addRevisionParam === 'function') {
            url = window.RevisionManifest.addRevisionParam(url, SIDEBAR_LANGUAGE_STATUS_TITLE);
        }
        $.ajax({
            url: url,
            dataType: 'text',
            cache: true
        }).done(function(text) {
            var parsed = {};

            try {
                parsed = text ? JSON.parse(text) : {};
            } catch (err) {
                console.error('LanguageStatus.json parse failed:', err);
                parsed = {};
            }

            finishLanguageStatus(parsed);
        }).fail(function() {
            finishLanguageStatus({});
        });
    })();
}

window.CLBI_LANGUAGE_STATUS = {
    title: SIDEBAR_LANGUAGE_STATUS_TITLE,
    languages: sidebarLanguageState.order.slice(),
    labels: SIDEBAR_LANGUAGE_LABELS,
    dialLabels: SIDEBAR_LANGUAGE_DIAL_LABELS,
    getPageKey: getSidebarLanguageStatusPageKey,
    getRegistry: function() {
        return sidebarLanguageStatusRegistry || {};
    },
    reload: function(callback) {
        sidebarLanguageStatusLoaded = false;
        loadSidebarLanguageStatusRegistry(function() {
            renderSidebarLanguageBox();
            if (typeof callback === 'function') callback(sidebarLanguageStatusRegistry);
        }, true);
    },
    refreshDial: function() {
        renderSidebarLanguageBox();
    }
};

function getSidebarLanguageMeta(lang) {
    var currentLang = getCurrentLang();
    var targetTitle = getLanguageTargetTitle(lang);
    var isCurrent = lang === currentLang;

    return {
        lang: lang,
        code: getLangShortCode(lang),
        name: getSidebarLanguageName(lang),
        dialName: getSidebarLanguageDialName(lang),
        targetTitle: targetTitle,
        isCurrent: isCurrent,
        canMove: !!targetTitle && !isCurrent
    };
}

function getSidebarLanguageStatus(meta) {
    var override;

    if (!meta) {
        return {
            className: 'is-locked',
            label: 'UNAVAILABLE',
            canApply: false
        };
    }

    if (meta.isCurrent) {
        return {
            className: 'is-current',
            label: 'CURRENT',
            canApply: false
        };
    }

    override = getSidebarLanguageStatusOverride(meta.lang);

    if (override === 'wip') {
        return {
            className: 'is-locked',
            label: 'WIP',
            canApply: false
        };
    }

    if (override === 'unavailable') {
        return {
            className: 'is-locked',
            label: 'UNAVAILABLE',
            canApply: false
        };
    }

    if (override === 'available' || meta.targetTitle) {
        return {
            className: meta.targetTitle ? 'is-ready' : 'is-locked',
            label: meta.targetTitle ? 'AVAILABLE' : 'UNAVAILABLE',
            canApply: !!meta.targetTitle
        };
    }

    return {
        className: 'is-locked',
        label: 'UNAVAILABLE',
        canApply: false
    };
}

function sidebarLanguageRad(deg) {
    return (deg * Math.PI) / 180;
}

function sidebarLanguagePointAt(radius, deg) {
    var state = sidebarLanguageState;
    var angle = sidebarLanguageRad(deg);

    return {
        x: state.cx + Math.sin(angle) * radius,
        y: state.cy - Math.cos(angle) * radius
    };
}

function getSidebarLanguageSectorPath(start, end) {
    var state = sidebarLanguageState;
    var p1 = sidebarLanguagePointAt(state.outerR, start);
    var p2 = sidebarLanguagePointAt(state.outerR, end);
    var p3 = sidebarLanguagePointAt(state.innerR, end);
    var p4 = sidebarLanguagePointAt(state.innerR, start);
    var largeArc = Math.abs(end - start) > 180 ? 1 : 0;

    return [
        'M', p1.x.toFixed(3), p1.y.toFixed(3),
        'A', state.outerR, state.outerR, 0, largeArc, 1, p2.x.toFixed(3), p2.y.toFixed(3),
        'L', p3.x.toFixed(3), p3.y.toFixed(3),
        'A', state.innerR, state.innerR, 0, largeArc, 0, p4.x.toFixed(3), p4.y.toFixed(3),
        'Z'
    ].join(' ');
}

function getSidebarLanguageShellPath() {
    return getSidebarLanguageSectorPath(-68, 68);
}

function getSidebarLanguageByStep(step) {
    var state = sidebarLanguageState;
    var index = normalizeSidebarLanguageIndex(state.baseIndex + step);

    return {
        index: index,
        meta: getSidebarLanguageMeta(state.order[index])
    };
}

function getSidebarLanguagePreviewIndex() {
    var state = sidebarLanguageState;
    var step = Math.round(-state.rotation / state.sectorAngle);
    return normalizeSidebarLanguageIndex(state.baseIndex + step);
}

function getSidebarLanguagePreviewMeta() {
    var state = sidebarLanguageState;
    return getSidebarLanguageMeta(state.order[getSidebarLanguagePreviewIndex()]);
}

function makeSidebarLanguageSector(step) {
    var state = sidebarLanguageState;
    var item = getSidebarLanguageByStep(step);
    var group = createSidebarLanguageSvgEl('g');
    var path = createSidebarLanguageSvgEl('path');
    var label = createSidebarLanguageSvgEl('text');
    var labelY = state.cy - 78;
    var angle = step * state.sectorAngle;

    group.setAttribute('class', 'sidebar-lang-sector-group');
    group.setAttribute('data-step', String(step));
    group.setAttribute('data-index', String(item.index));
    group.setAttribute('data-lang', item.meta.lang);
    group.setAttribute('transform', 'rotate(' + angle + ' ' + state.cx + ' ' + state.cy + ')');

    path.setAttribute('class', 'sidebar-lang-sector');
    path.setAttribute('d', getSidebarLanguageSectorPath(-state.halfSector, state.halfSector));

    label.setAttribute('class', 'sidebar-lang-sector-label');
    label.setAttribute('x', String(state.cx));
    label.setAttribute('y', String(labelY + 5));
    label.textContent = item.meta.dialName || item.meta.name;

    group.appendChild(path);
    group.appendChild(label);

    group.addEventListener('click', function(e) {
        if (sidebarLanguageState.dragging || performance.now() < sidebarLanguageState.suppressClickUntil) return;

        e.preventDefault();
        e.stopPropagation();

        cancelSidebarLanguageSpin();
        snapSidebarLanguageToStep(parseInt(group.getAttribute('data-step') || '0', 10), true);
    });

    return group;
}

function renderSidebarLanguageWheel() {
    var state = sidebarLanguageState;
    var fan = document.getElementById('clbi-sidebar-lang-fan');
    var svg;
    var defs;
    var clip;
    var clipPath;
    var shadowBlur;
    var blur;
    var fixedDepthGradient;
    var shell;
    var clipped;
    var rotor;
    var fixedDepthPath;
    var fixedFocus;
    var shadowSoft;
    var shadowHard;
    var rim;
    var pointer;
    var tri;
    var line;
    var step;

    if (!fan) return;

    fan.innerHTML = '';

    svg = createSidebarLanguageSvgEl('svg');
    svg.setAttribute('class', 'sidebar-lang-fan-svg');
    svg.setAttribute('viewBox', '0 0 202 150');
    svg.setAttribute('preserveAspectRatio', 'xMidYMid meet');
    svg.setAttribute('role', 'img');
    svg.setAttribute('aria-label', '언어 선택 다이얼');

    defs = createSidebarLanguageSvgEl('defs');

    clip = createSidebarLanguageSvgEl('clipPath');
    clip.setAttribute('id', 'clbi-sidebar-language-fan-clip');
    clipPath = createSidebarLanguageSvgEl('path');
    clipPath.setAttribute('d', getSidebarLanguageShellPath());
    clip.appendChild(clipPath);

    shadowBlur = createSidebarLanguageSvgEl('filter');
    shadowBlur.setAttribute('id', 'clbi-sidebar-language-shadow-blur');
    shadowBlur.setAttribute('x', '-20%');
    shadowBlur.setAttribute('y', '-20%');
    shadowBlur.setAttribute('width', '140%');
    shadowBlur.setAttribute('height', '140%');
    blur = createSidebarLanguageSvgEl('feGaussianBlur');
    blur.setAttribute('stdDeviation', '3');
    shadowBlur.appendChild(blur);

    fixedDepthGradient = createSidebarLanguageSvgEl('linearGradient');
    fixedDepthGradient.setAttribute('id', 'clbi-sidebar-language-fixed-depth');
    fixedDepthGradient.setAttribute('x1', '0');
    fixedDepthGradient.setAttribute('y1', '0');
    fixedDepthGradient.setAttribute('x2', '0');
    fixedDepthGradient.setAttribute('y2', '1');

    [
        ['0%', '#ffffff', '0.030'],
        ['34%', '#ffffff', '0.006'],
        ['58%', '#000000', '0.030'],
        ['100%', '#000000', '0.250']
    ].forEach(function(item) {
        var stop = createSidebarLanguageSvgEl('stop');
        stop.setAttribute('offset', item[0]);
        stop.setAttribute('stop-color', item[1]);
        stop.setAttribute('stop-opacity', item[2]);
        fixedDepthGradient.appendChild(stop);
    });

    defs.appendChild(clip);
    defs.appendChild(shadowBlur);
    defs.appendChild(fixedDepthGradient);
    svg.appendChild(defs);

    shell = createSidebarLanguageSvgEl('path');
    shell.setAttribute('class', 'sidebar-lang-shell');
    shell.setAttribute('d', getSidebarLanguageShellPath());
    svg.appendChild(shell);

    clipped = createSidebarLanguageSvgEl('g');
    clipped.setAttribute('clip-path', 'url(#clbi-sidebar-language-fan-clip)');

    rotor = createSidebarLanguageSvgEl('g');
    rotor.setAttribute('id', 'clbi-sidebar-lang-wheel-rotor');
    rotor.setAttribute('class', 'sidebar-lang-wheel-rotor');

    for (step = -state.repeats; step <= state.repeats; step += 1) {
        rotor.appendChild(makeSidebarLanguageSector(step));
    }

    clipped.appendChild(rotor);
    svg.appendChild(clipped);

    fixedDepthPath = createSidebarLanguageSvgEl('path');
    fixedDepthPath.setAttribute('class', 'sidebar-lang-fixed-depth');
    fixedDepthPath.setAttribute('d', getSidebarLanguageShellPath());
    svg.appendChild(fixedDepthPath);

    fixedFocus = createSidebarLanguageSvgEl('path');
    fixedFocus.setAttribute('class', 'sidebar-lang-fixed-focus');
    fixedFocus.setAttribute('d', getSidebarLanguageSectorPath(-state.halfSector, state.halfSector));
    svg.appendChild(fixedFocus);

    shadowSoft = createSidebarLanguageSvgEl('path');
    shadowSoft.setAttribute('class', 'sidebar-lang-inner-shadow-soft');
    shadowSoft.setAttribute('d', getSidebarLanguageShellPath());
    svg.appendChild(shadowSoft);

    shadowHard = createSidebarLanguageSvgEl('path');
    shadowHard.setAttribute('class', 'sidebar-lang-inner-shadow-hard');
    shadowHard.setAttribute('d', getSidebarLanguageShellPath());
    svg.appendChild(shadowHard);

    rim = createSidebarLanguageSvgEl('path');
    rim.setAttribute('class', 'sidebar-lang-rim');
    rim.setAttribute('d', getSidebarLanguageShellPath());
    svg.appendChild(rim);

    pointer = createSidebarLanguageSvgEl('g');
    pointer.setAttribute('class', 'sidebar-lang-fixed-pointer');
    pointer.setAttribute('clip-path', 'url(#clbi-sidebar-language-fan-clip)');

    tri = createSidebarLanguageSvgEl('path');
    tri.setAttribute('class', 'sidebar-lang-pointer-triangle');
    tri.setAttribute('d', 'M ' + (state.cx - 10) + ' 10 L ' + (state.cx + 10) + ' 10 L ' + state.cx + ' 26 Z');
    pointer.appendChild(tri);

    line = createSidebarLanguageSvgEl('line');
    line.setAttribute('class', 'sidebar-lang-pointer-line');
    line.setAttribute('x1', String(state.cx));
    line.setAttribute('x2', String(state.cx));
    line.setAttribute('y1', '24');
    line.setAttribute('y2', '112');
    pointer.appendChild(line);

    svg.appendChild(pointer);
    fan.appendChild(svg);

    state.rotor = rotor;
    setSidebarLanguageRotation(state.rotation, false);
}

function updateSidebarLanguageDial() {
    var state = sidebarLanguageState;
    var meta = getSidebarLanguagePreviewMeta();
    var status = getSidebarLanguageStatus(meta);
    var selector = document.getElementById('clbi-sidebar-lang-selector');
    var apply = document.getElementById('clbi-sidebar-lang-apply');
    var selectedValue = document.getElementById('clbi-sidebar-lang-selected-value');
    var availabilityPanel = document.getElementById('clbi-sidebar-lang-availability-panel');
    var availabilityValue = document.getElementById('clbi-sidebar-lang-availability-value');

    if (selectedValue) {
        selectedValue.textContent = meta.name;
    }

    if (availabilityPanel) {
        availabilityPanel.classList.remove('is-ready', 'is-current', 'is-locked');
        availabilityPanel.classList.add(status.className);
    }

    if (availabilityValue) {
        availabilityValue.textContent = status.label;
    }

    if (apply) {
        apply.classList.toggle('is-disabled', !status.canApply);
        apply.setAttribute('aria-disabled', status.canApply ? 'false' : 'true');
        apply.setAttribute('aria-label', status.canApply ? (meta.name + ' 적용') : (meta.isCurrent ? '현재 언어' : '사용할 수 없는 언어'));
    }

    if (selector) {
        selector.setAttribute('data-selected-lang', meta.lang);
        selector.setAttribute('data-selected-code', meta.code);
        selector.classList.toggle('is-current', meta.isCurrent);
        selector.classList.toggle('is-ready', status.canApply);
        selector.classList.toggle('is-locked', !status.canApply && !meta.isCurrent);
        selector.classList.toggle('is-dragging', !!state.dragging);
        selector.classList.toggle('is-spinning', !!state.inertiaRaf);
    }

    return {
        meta: meta,
        status: status
    };
}

function setSidebarLanguageRotation(value, animate) {
    var state = sidebarLanguageState;
    state.rotation = value;
    updateSidebarLanguageDial();

    if (!state.rotor) return;

    if (animate) {
        $('#clbi-sidebar-lang-selector').addClass('is-snapping');
    } else {
        $('#clbi-sidebar-lang-selector').removeClass('is-snapping');
    }

    state.rotor.style.transform = 'rotate(' + state.rotation.toFixed(3) + 'deg)';
}

function requestSidebarLanguageRotation(value) {
    var state = sidebarLanguageState;
    state.pendingRotation = value;

    if (state.raf) return;

    state.raf = requestAnimationFrame(function() {
        state.raf = null;
        setSidebarLanguageRotation(state.pendingRotation, false);
    });
}

function cancelSidebarLanguageSpin() {
    var state = sidebarLanguageState;

    if (state.inertiaRaf) {
        cancelAnimationFrame(state.inertiaRaf);
        state.inertiaRaf = null;
    }

    $('#clbi-sidebar-lang-selector').removeClass('is-spinning');
}

function finishSidebarLanguageSnap(nearestIndex, callback) {
    var state = sidebarLanguageState;

    state.baseIndex = normalizeSidebarLanguageIndex(nearestIndex);
    state.selectedIndex = state.baseIndex;
    state.rotation = 0;
    state.dragging = false;

    $('#clbi-sidebar-lang-selector').removeClass('is-snapping is-dragging is-spinning');

    renderSidebarLanguageWheel();
    updateSidebarLanguageDial();

    if (typeof callback === 'function') {
        callback(getSidebarLanguageMeta(state.order[state.selectedIndex]));
    }
}

function snapSidebarLanguageToStep(step, animate, callback) {
    var state = sidebarLanguageState;
    var targetRotation = -step * state.sectorAngle;
    var nearestIndex = normalizeSidebarLanguageIndex(state.baseIndex + step);

    cancelSidebarLanguageSpin();
    clearTimeout(state.snapTimer);

    state.selectedIndex = nearestIndex;
    setSidebarLanguageRotation(targetRotation, !!animate);

    state.snapTimer = setTimeout(function() {
        finishSidebarLanguageSnap(nearestIndex, callback);
    }, animate ? 230 : 0);
}

function snapSidebarLanguageNearest(callback) {
    var state = sidebarLanguageState;
    var step = Math.round(-state.rotation / state.sectorAngle);
    snapSidebarLanguageToStep(step, true, callback);
}

function startSidebarLanguageInertiaSpin(initialVelocity) {
    var state = sidebarLanguageState;
    var velocity;
    var lastFrame;

    cancelSidebarLanguageSpin();

    velocity = Math.max(-state.maxSpinVelocity, Math.min(state.maxSpinVelocity, initialVelocity));

    if (Math.abs(velocity) < state.minSpinVelocity) {
        snapSidebarLanguageNearest();
        return;
    }

    $('#clbi-sidebar-lang-selector').addClass('is-spinning');
    lastFrame = performance.now();

    function frame(now) {
        var dt = Math.min(34, Math.max(1, now - lastFrame));
        var sign = velocity < 0 ? -1 : 1;
        var nextSpeed;

        lastFrame = now;
        state.rotation += velocity * dt;
        setSidebarLanguageRotation(state.rotation, false);

        nextSpeed = Math.max(0, Math.abs(velocity) - (state.spinDecel * dt));
        velocity = sign * nextSpeed;

        if (nextSpeed <= state.minSpinVelocity) {
            state.inertiaRaf = null;
            $('#clbi-sidebar-lang-selector').removeClass('is-spinning');
            snapSidebarLanguageNearest();
            return;
        }

        state.inertiaRaf = requestAnimationFrame(frame);
    }

    state.inertiaRaf = requestAnimationFrame(frame);
}

function scheduleSidebarLanguageNavigation(meta) {
    var status = getSidebarLanguageStatus(meta);

    if (!meta || !status.canApply) return;

    clearTimeout(sidebarLanguageState.navigateTimer);
    sidebarLanguageState.navigateTimer = setTimeout(function() {
        var title = getLanguageTargetTitle(meta.lang);

        if (!title || meta.lang === getCurrentLang()) return;

        window.location.href = buildWikiPath(title);
    }, 70);
}

function setSidebarLanguageSelection(lang) {
    var state = sidebarLanguageState;
    var index = state.order.indexOf(lang);

    if (index < 0) index = state.order.indexOf(getCurrentLang());
    if (index < 0) index = 0;

    if (state.raf) {
        cancelAnimationFrame(state.raf);
        state.raf = null;
    }

    cancelSidebarLanguageSpin();
    clearTimeout(state.snapTimer);

    state.currentLang = lang;
    state.baseIndex = index;
    state.selectedIndex = index;
    state.rotation = 0;
    state.dragging = false;
    state.dragMoved = false;
    state.releaseVelocity = 0;

    renderSidebarLanguageWheel();
    updateSidebarLanguageDial();
}

function moveSidebarLanguageSelection(delta) {
    snapSidebarLanguageToStep(-delta, true);
}

function bindSidebarLanguageSelector() {
    var state = sidebarLanguageState;
    var selector = document.getElementById('clbi-sidebar-lang-selector');
    var fan = document.getElementById('clbi-sidebar-lang-fan');
    var apply = document.getElementById('clbi-sidebar-lang-apply');

    if (!selector || !fan || !apply) return;

    if (state.bound && state.boundElement === selector) return;

    state.bound = true;
    state.boundElement = selector;

    fan.addEventListener('pointerdown', function(e) {
        cancelSidebarLanguageSpin();
        clearTimeout(state.snapTimer);

        state.dragging = true;
        state.dragMoved = false;
        state.dragStartX = e.clientX;
        state.dragStartY = e.clientY || 0;
        state.dragStartRotation = state.rotation;
        state.dragAxis = null;
        state.pointerCaptured = false;
        state.lastX = e.clientX;
        state.lastTime = performance.now();
        state.releaseVelocity = 0;

        selector.classList.add('is-dragging');
        selector.classList.remove('is-snapping');

        /*
        Vertical page scrolling must stay available when the pointer starts on
        the language dial. Capture and preventDefault are delayed until a
        horizontal drag is confirmed.
        */
    });

    fan.addEventListener('pointermove', function(e) {
        var now;
        var totalDx;
        var totalDy;
        var frameDx;
        var dt;
        var instantVelocity;

        if (!state.dragging) return;

        totalDx = e.clientX - state.dragStartX;
        totalDy = (e.clientY || 0) - state.dragStartY;

        if (!state.dragAxis && (Math.abs(totalDx) > 4 || Math.abs(totalDy) > 4)) {
            state.dragAxis = Math.abs(totalDx) >= Math.abs(totalDy) ? 'x' : 'y';

            if (state.dragAxis === 'y') {
                state.dragging = false;
                state.dragMoved = false;
                state.dragAxis = null;
                state.pointerCaptured = false;
                selector.classList.remove('is-dragging');
                return;
            }

            if (fan.setPointerCapture && e.pointerId != null) {
                try {
                    fan.setPointerCapture(e.pointerId);
                    state.pointerCaptured = true;
                } catch (err) {
                    state.pointerCaptured = false;
                }
            }
        }

        if (state.dragAxis !== 'x') return;

        now = performance.now();
        frameDx = e.clientX - state.lastX;
        dt = Math.max(1, now - state.lastTime);

        if (Math.abs(totalDx) > 3) state.dragMoved = true;

        instantVelocity = (frameDx * state.dragSensitivity) / dt;
        state.releaseVelocity = (state.releaseVelocity * 0.62) + (instantVelocity * 0.38);
        state.lastX = e.clientX;
        state.lastTime = now;

        requestSidebarLanguageRotation(state.dragStartRotation + totalDx * state.dragSensitivity);
        e.preventDefault();
        e.stopPropagation();
    });

    function finishDrag(e) {
        var velocityAge;
        var throwVelocity;
        var wasHorizontal;

        if (!state.dragging) return;

        wasHorizontal = state.dragAxis === 'x';
        state.dragging = false;
        selector.classList.remove('is-dragging');

        if (fan.releasePointerCapture && state.pointerCaptured && e && e.pointerId != null) {
            try { fan.releasePointerCapture(e.pointerId); } catch (err) {}
        }

        state.pointerCaptured = false;
        state.dragAxis = null;

        if (!wasHorizontal && !state.dragMoved) {
            return;
        }

        velocityAge = performance.now() - state.lastTime;
        throwVelocity = velocityAge > 120 ? 0 : state.releaseVelocity;

        if (state.dragMoved) {
            state.suppressClickUntil = performance.now() + 180;
        }

        if (state.dragMoved && Math.abs(throwVelocity) >= state.minSpinVelocity) {
            startSidebarLanguageInertiaSpin(throwVelocity);
        } else {
            snapSidebarLanguageNearest();
        }

        if (e) {
            e.preventDefault();
            e.stopPropagation();
        }
    }

    fan.addEventListener('pointerup', finishDrag);
    fan.addEventListener('pointercancel', finishDrag);
    fan.addEventListener('lostpointercapture', function() {
        if (!state.dragging) return;

        state.dragging = false;
        state.pointerCaptured = false;
        state.dragAxis = null;
        selector.classList.remove('is-dragging');

        if (state.dragMoved && Math.abs(state.releaseVelocity) >= state.minSpinVelocity) {
            state.suppressClickUntil = performance.now() + 180;
            startSidebarLanguageInertiaSpin(state.releaseVelocity);
        } else {
            snapSidebarLanguageNearest();
        }
    });

    apply.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();

        snapSidebarLanguageNearest(function(meta) {
            scheduleSidebarLanguageNavigation(meta);
        });
    });

    selector.addEventListener('keydown', function(e) {
        if (e.key === 'ArrowLeft') {
            moveSidebarLanguageSelection(-1);
            e.preventDefault();
        }

        if (e.key === 'ArrowRight') {
            moveSidebarLanguageSelection(1);
            e.preventDefault();
        }

        if (e.key === 'Enter' || e.key === ' ') {
            apply.click();
            e.preventDefault();
        }
    });
}

function renderSidebarLanguageBox() {
    bindSidebarLanguageSelector();
    setSidebarLanguageSelection(getCurrentLang());

    if (!sidebarLanguageStatusLoaded) {
        loadSidebarLanguageStatusRegistry(function() {
            setSidebarLanguageSelection(getCurrentLang());
        });
    }
}

function loadRecentChangesList(targetSelector, limit) {
    var $target = $(targetSelector);

    if (!$target.length) return;

    var lang = getCurrentLang();
    var t = (window.LANG && window.LANG[lang]) ? window.LANG[lang] : (window.LANG ? window.LANG.ko : null);
    var isNewsList = $target.closest('.clbi-left-news-box').length > 0;

    function escapeHtml(value) {
        return String(value == null ? '' : value)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    $target.html((t && t.loading) ? t.loading : '불러오는 중...');

    $.getJSON(
        '/api.php?action=query&list=recentchanges&rclimit=' + encodeURIComponent(limit || 5) + '&rcprop=title|timestamp|user&format=json&rcnamespace=0&rctype=edit|new',
        function(data) {
            var items = data && data.query ? data.query.recentchanges : [];
            var html = '';

            if (!items || !items.length) {
                $target.html('표시할 변경 사항이 없습니다.');
                return;
            }

            $.each(items, function(i, item) {
                var label = timeAgo(item.timestamp);
                var title = item.title || '';
                var userName = item.user || 'Unknown';
                var pageHref = buildWikiPath(title);
                var avatarSrc = '/index.php?title=특수:Redirect/file/Pfp-' + encodeURIComponent(userName) + '.png';

                if (isNewsList) {
                    html +=
                        '<a href="' + escapeHtml(pageHref) + '" class="news-recent-item">' +
                            '<img class="news-recent-avatar" src="' + escapeHtml(avatarSrc) + '" alt="" onerror="this.onerror=null;this.src=\'/index.php?title=특수:Redirect/file/Pfp-default.png\';">' +
                            '<div class="news-recent-main">' +
                                '<div class="news-recent-title-wrap">' +
                                    '<span class="news-recent-title">' + escapeHtml(title) + '</span>' +
                                '</div>' +
                                '<div class="news-recent-meta">' +
                                    '<span class="news-recent-user">@' + escapeHtml(userName) + '</span>' +
                                '</div>' +
                            '</div>' +
                            '<span class="news-recent-time">' + escapeHtml(label) + '</span>' +
                        '</a>';
                } else {
                    html +=
                        '<div class="clbi-recent-item">' +
                            '<div class="clbi-recent-title-wrap">' +
                                '<a href="' + escapeHtml(pageHref) + '" class="clbi-recent-title">' + escapeHtml(title) + '</a>' +
                            '</div>' +
                            '<span class="clbi-recent-time">' + escapeHtml(label) + '</span>' +
                        '</div>';
                }
            });

            if (isNewsList) {
                $target.html(
                    '<div class="news-recent-viewport">' +
                        '<div class="news-recent-stack">' + html + '</div>' +
                    '</div>'
                );

                if (typeof ensureNewsBottomFinish === 'function') {
                    ensureNewsBottomFinish();
                }
            } else {
                $target.html(html);
            }

            if (isNewsList && typeof scheduleAdaptiveLeftRecentItems === 'function') {
                scheduleAdaptiveLeftRecentItems();
            }

            $target.find(isNewsList ? '.news-recent-item' : '.clbi-recent-item').each(function() {
                var wrap = $(this).find(isNewsList ? '.news-recent-title-wrap' : '.clbi-recent-title-wrap');
                var title = $(this).find(isNewsList ? '.news-recent-title' : '.clbi-recent-title');

                if (!wrap.length || !title.length) return;

                var wrapW = wrap.width();
                var titleW = title[0].scrollWidth;

                if (titleW > wrapW + 20) {
                    var duration = titleW / 40;

                    title.css({
                        animation: 'clbi-scroll ' + duration + 's linear infinite',
                        '--scroll-dist': '-' + (titleW - wrapW + 8) + 'px'
                    });
                }
            });
        }
    ).fail(function() {
        var lang = getCurrentLang();
        var t = (window.LANG && window.LANG[lang]) ? window.LANG[lang] : (window.LANG ? window.LANG.ko : null);

        $target.html((t && t.loadFail) ? t.loadFail : '불러오기 실패');
    });
}


function ensureRecentViewport() {
    var list = document.getElementById('clbi-left-recent-list');
    var viewport;
    var stack;
    var children;

    if (!list) return null;

    viewport = list.querySelector(':scope > .news-recent-viewport');
    stack = viewport ? viewport.querySelector(':scope > .news-recent-stack') : null;

    if (viewport && stack) return viewport;

    children = Array.prototype.slice.call(list.children || []);

    viewport = document.createElement('div');
    viewport.className = 'news-recent-viewport';

    stack = document.createElement('div');
    stack.className = 'news-recent-stack';

    children.forEach(function (child) {
        if (child.classList && child.classList.contains('news-recent-viewport')) return;
        stack.appendChild(child);
    });

    viewport.appendChild(stack);
    list.appendChild(viewport);

    return viewport;
}

function ensureNewsBottomFinish() {
    var newsBox = document.querySelector('#clbi-left-sidebar .clbi-left-news-box');
    var content = newsBox ? newsBox.querySelector('.clbi-news-box') : null;
    var finish;

    if (!content) return null;

    finish = content.querySelector(':scope > .news-bottom-finish');

    if (!finish) {
        finish = document.createElement('div');
        finish.className = 'news-bottom-finish';
        finish.setAttribute('aria-hidden', 'true');
        content.appendChild(finish);
    }

    return finish;
}

function updateAdaptiveLeftRecentItems() {
    /*
    134 기준: 좌측 사이드는 뉴스 확장형 flex 레이아웃이 높이를 담당한다.
    이전 adaptive 코드는 항목을 숨기거나 mask/fade를 걸기 위한 것이었으므로
    여기서는 잔여 상태만 정리하고 DOM 래퍼만 보장한다.
    */
    resetLeftRecentAdaptiveState();

    if (typeof ensureRecentViewport === 'function') {
        ensureRecentViewport();
    }

    if (typeof ensureNewsBottomFinish === 'function') {
        ensureNewsBottomFinish();
    }

    if (typeof scheduleClbiContentBottomGap === 'function') {
        scheduleClbiContentBottomGap();
    }
}

function scheduleAdaptiveLeftRecentItems() {
    window.requestAnimationFrame(function () {
        updateAdaptiveLeftRecentItems();
    });

    window.setTimeout(updateAdaptiveLeftRecentItems, 80);
    window.setTimeout(updateAdaptiveLeftRecentItems, 240);
}



function updateClbiContentBottomGap(iteration) {
    var content = document.querySelector('.container-fluid.liberty-content');
    var main = document.querySelector('.liberty-content-main');
    var bottomNav = document.getElementById('clbi-bottom-nav-wrap');
    var desiredGap = 8;
    var rootStyle;
    var scale = 1;
    var contentRect;
    var bottomTop;
    var targetHeight;
    var currentHeight;
    var visualGap;

    iteration = iteration || 0;

    if (!content || !main || !bottomNav) return;

    /*
    하단 간격은 scale 모드에서도 같은 기준으로 계산한다.
    transform:scale()이 걸리면 getBoundingClientRect()는 축소된 화면 좌표를 반환하므로,
    목표 간격 8px도 scale을 곱한 화면 좌표로 비교하고 다시 design px로 환산한다.

    목표:
    .liberty-content-main.bottom === #clbi-bottom-nav-wrap.top - 8px
    */
    if (document.body && document.body.classList && document.body.classList.contains('clbi-shell-vertical-scale')) {
        rootStyle = window.getComputedStyle(document.documentElement);
        scale = parseFloat(rootStyle.getPropertyValue('--clbi-shell-scale')) || 1;
        scale = Math.max(0.25, scale);
    }

    contentRect = content.getBoundingClientRect();
    bottomTop = bottomNav.getBoundingClientRect().top;
    visualGap = desiredGap * scale;
    targetHeight = Math.floor((bottomTop - contentRect.top - visualGap) / scale);
    targetHeight = Math.max(120, targetHeight);

    currentHeight = Math.round(content.getBoundingClientRect().height / scale);

    content.style.setProperty('--clbi-content-extra', '0px');
    content.style.setProperty('height', targetHeight + 'px', 'important');
    content.style.setProperty('max-height', targetHeight + 'px', 'important');

    if (Math.abs(currentHeight - targetHeight) >= 1 && iteration < 4) {
        window.requestAnimationFrame(function () {
            updateClbiContentBottomGap(iteration + 1);
        });
    }
}

function scheduleClbiContentBottomGap() {
    window.requestAnimationFrame(function () {
        updateClbiContentBottomGap(0);
    });
    window.setTimeout(function () {
        updateClbiContentBottomGap(0);
    }, 40);
    window.setTimeout(function () {
        updateClbiContentBottomGap(0);
    }, 120);
    window.setTimeout(function () {
        updateClbiContentBottomGap(0);
    }, 280);
    window.setTimeout(function () {
        updateClbiContentBottomGap(0);
    }, 520);
}


function updateLeftBillboardAdaptive() {
    /*
    134 기준: Ad는 이미지/CRT 비율을 유지하는 고정 슬롯이다.
    남는 세로 공간은 뉴스 박스가 흡수하므로, Ad에 하단 finish를 늘리거나
    title-only 상태로 접는 adaptive 보정은 사용하지 않는다.
    */
    resetLeftBillboardAdaptiveState();
}

function scheduleLeftBillboardAdaptive() {
    window.requestAnimationFrame(updateLeftBillboardAdaptive);
    window.setTimeout(updateLeftBillboardAdaptive, 80);
    window.setTimeout(updateLeftBillboardAdaptive, 240);
}

function scheduleLeftSidebarVerticalFit() {
    if (typeof scheduleAdaptiveLeftRecentItems === 'function') {
        scheduleAdaptiveLeftRecentItems();
    }

    if (typeof scheduleLeftBillboardAdaptive === 'function') {
        scheduleLeftBillboardAdaptive();
    }

    window.setTimeout(function () {
        if (typeof scheduleAdaptiveLeftRecentItems === 'function') {
            scheduleAdaptiveLeftRecentItems();
        }

        if (typeof scheduleLeftBillboardAdaptive === 'function') {
            scheduleLeftBillboardAdaptive();
        }
    }, 120);
}


// 시대 문서 전용 왼쪽 사이드바 이미지
function updateLeftSidebarNationsImage() {
    $('#clbi-left-nations-image').remove();
}

function setProfileActionLabel(selector, text) {
    var target = $(selector);
    var label = target.find('.profile-action-label');

    if (label.length) {
        label.text(text);
    } else {
        target.text(text);
    }
}

// 사이드바 업데이트
function updateSidebar() {
    if (!window.LANG) {
        setTimeout(updateSidebar, 100);
        return;
    }

    var currentLang = getCurrentLang();
    var t = (window.LANG && window.LANG[currentLang]) ? window.LANG[currentLang] : window.LANG.ko;

    var newsTitle = t.news || '뉴스';
    var changelogTitle = t.changelog || '체인지로그';
    var recentTitle = t.recentChanges || '최근 변경';
    var languageTitle = t.language || '언어';

    $('#clbi-title-left-language').text(languageTitle);
    renderSidebarLanguageBox();

    $('#clbi-title-left-news').text(newsTitle);
    $('#clbi-left-news-changelog-main').text(changelogTitle);
    $('#clbi-left-news-recent-main').text(recentTitle);

    $('#clbi-title-search a').text(t.search);
    $('#clbi-search-input').attr('placeholder', t.search + '...');
    $('#clbi-title-recent a').text(recentTitle);
    $('#clbi-title-guide-label').text(t.guide);
    $('#clbi-guide-link').text(t.getStarted);
    $('#clbi-title-links-label').text(t.links);

    setProfileActionLabel('#clbi-btn-contribution', t.contribution);
    setProfileActionLabel('#clbi-btn-watchlist', t.watchlist);
    setProfileActionLabel('#clbi-btn-preferences', t.preferences);
    setProfileActionLabel('#clbi-btn-logout', t.logout);
    setProfileActionLabel('#clbi-btn-login', t.login);

    var pageName = normalizePageName(mw.config.get('wgPageName'));
    var specialPage = String(mw.config.get('wgCanonicalSpecialPageName') || '');

$('#clbi-left-news-changelog-main').text(changelogTitle);
$('#clbi-left-news-recent-title').text('RECENT CHANGES');

    $('.clbi-user-btn').removeClass('clbi-user-btn-active');

    if (
        specialPage === 'Contributions' ||
        specialPage === '기여' ||
        pageName.indexOf('특수:기여') === 0 ||
        pageName.indexOf('Special:Contributions') === 0
    ) {
        $('#clbi-btn-contribution').addClass('clbi-user-btn-active');
    }

    if (specialPage === 'Watchlist') {
        $('#clbi-btn-watchlist').addClass('clbi-user-btn-active');
    }

    if (
        specialPage === '설정' ||
        pageName === '특수:설정' ||
        pageName === 'Special:설정'
    ) {
        $('#clbi-btn-preferences').addClass('clbi-user-btn-active');
    }

    $('.toggleBtn').each(function() {
        var btn = $(this);

        if (!$('#' + btn.data('target')).hasClass('folding-open')) {
            btn.text(t.expand);
        } else {
            btn.text(t.collapse);
        }
    });

    updateLeftSidebarNationsImage();
}

function canShowContentTools() {
    // 비로그인 사용자는 편집/역사/공유 버튼을 숨김
    if (!mw.config.get('wgUserName')) {
        return false;
    }

    // MediaWiki가 현재 문서를 편집 가능하지 않다고 판단하면 숨김
    var isEditable = mw.config.get('wgIsProbablyEditable');
    if (isEditable === false) {
        return false;
    }

    var relevantEditable = mw.config.get('wgRelevantPageIsProbablyEditable');
    if (relevantEditable === false) {
        return false;
    }

    return true;
}

function getCatlinkNodes(root) {
    var seen = [];
    var nodes = [];
    var $root = root ? $(root) : $(document);

    $root.find('#catlinks, .catlinks').add($root.filter('#catlinks, .catlinks')).each(function () {
        if (seen.indexOf(this) !== -1) return;
        seen.push(this);
        nodes.push(this);
    });

    return nodes;
}

function getCatlinksTarget(root) {
    var $root = root ? $(root) : $(document);
    var parserOutput = $root.find('.liberty-content-main .mw-parser-output').first();
    var main = $root.find('.liberty-content-main').first();

    if (!parserOutput.length && root && $(root).is('.liberty-content-main')) {
        parserOutput = $(root).find('.mw-parser-output').first();
        main = $(root);
    }

    if (!parserOutput.length && root && $(root).is('.mw-parser-output')) {
        parserOutput = $(root);
    }

    if (parserOutput.length) return parserOutput;
    if (main.length) return main;

    if (!root) {
        parserOutput = $('.liberty-content-main .mw-parser-output').first();
        main = $('.liberty-content-main').first();
        if (parserOutput.length) return parserOutput;
        if (main.length) return main;
    }

    return $();
}

var CLBI_CATLINKS_FETCH_TOKEN = 0;

function getCurrentPageTitleForCatlinks() {
    return String(
        mw.config.get('wgPageName') ||
        mw.config.get('wgRelevantPageName') ||
        ''
    ).trim();
}

function shouldFetchCatlinks() {
    var pageName = getCurrentPageTitleForCatlinks();
    var specialPage = mw.config.get('wgCanonicalSpecialPageName');

    if (!pageName) return false;
    if (specialPage) return false;

    return true;
}

function clearCatlinksInlineHiding(cat) {
    if (!cat || !cat.style) return;

    cat.style.removeProperty('display');
    cat.style.removeProperty('visibility');
    cat.style.removeProperty('height');
    cat.style.removeProperty('max-height');
    cat.style.removeProperty('overflow');

    $(cat).find('.mw-normal-catlinks, #mw-normal-catlinks, .mw-hidden-catlinks, #mw-hidden-catlinks, .mw-hidden-cats-hidden, .mw-hidden-cats-user-shown').each(function () {
        if (!this.style) return;
        this.style.removeProperty('display');
        this.style.removeProperty('visibility');
        this.style.removeProperty('height');
        this.style.removeProperty('max-height');
        this.style.removeProperty('overflow');
    });
}

function exposeHiddenCatlinks(cat) {
    if (!cat) return;

    $(cat).find('.mw-hidden-catlinks, #mw-hidden-catlinks, .mw-hidden-cats-hidden, .mw-hidden-cats-user-shown').each(function () {
        this.classList.remove('mw-hidden-cats-hidden');
        this.classList.add('mw-hidden-cats-user-shown');

        if (this.style) {
            this.style.removeProperty('display');
            this.style.removeProperty('visibility');
            this.style.removeProperty('height');
            this.style.removeProperty('max-height');
            this.style.removeProperty('overflow');
        }
    });
}

function getCatlinkTextContent(cat) {
    var clone;
    var text;

    if (!cat) return '';

    clone = cat.cloneNode(true);
    $(clone).find('script, style').remove();

    text = String(clone.textContent || '')
        .replace(/\s+/g, ' ')
        .replace(/^(분류|숨은 분류|Category|Hidden categories)\s*:\s*/i, '')
        .replace(/^(분류|숨은 분류|Category|Hidden categories)\s*$/i, '')
        .trim();

    return text;
}

function hasRenderedCatlinkItems(cat) {
    var hasLink;
    var hasListText;

    if (!cat) return false;

    hasLink = false;
    $(cat).find('a').each(function () {
        var text = String($(this).text() || '').trim();
        var href = String(this.getAttribute('href') || '').trim();
        if (text || href) hasLink = true;
    });
    if (hasLink) return true;

    hasListText = false;
    $(cat).find('li').each(function () {
        if (String($(this).text() || '').trim()) hasListText = true;
    });
    if (hasListText) return true;

    return !!getCatlinkTextContent(cat);
}

function normalizeCategoryTitle(rawTitle) {
    var title = String(rawTitle == null ? '' : rawTitle).trim();

    if (!title) return '';

    title = title.replace(/_/g, ' ');

    if (/^(Category|분류):/i.test(title)) {
        return title;
    }

    return '분류:' + title;
}

function makeCategoryLinkTitle(rawTitle) {
    return String(rawTitle || '')
        .replace(/^Category:/i, '')
        .replace(/^분류:/, '')
        .replace(/_/g, ' ')
        .trim();
}

function dedupeCatlinkCategories(categories) {
    var seen = {};
    var result = [];

    (categories || []).forEach(function (item) {
        var title = '';
        var hidden = false;

        if (typeof item === 'string') {
            title = normalizeCategoryTitle(item);
        } else if (item && typeof item === 'object') {
            title = normalizeCategoryTitle(item.title || item.name || item.category || '');
            hidden = item.hidden !== undefined || item.isHidden === true;
        }

        if (!title) return;
        if (seen[title]) return;

        seen[title] = true;
        result.push({ title: title, hidden: hidden });
    });

    return result;
}

function getConfigCatlinksCategories() {
    var normal = mw.config.get('wgCategories') || [];
    var hidden = mw.config.get('wgHiddenCategories') || [];
    var categories = [];

    if (!Array.isArray(normal)) normal = [];
    if (!Array.isArray(hidden)) hidden = [];

    normal.forEach(function (name) {
        categories.push({ title: normalizeCategoryTitle(name), hidden: false });
    });

    hidden.forEach(function (name) {
        categories.push({ title: normalizeCategoryTitle(name), hidden: true });
    });

    return dedupeCatlinkCategories(categories);
}

function markCatlinksReady(cat, pageTitle) {
    if (!cat) return;

    cat.classList.add('catlinks');
    cat.classList.add('clbi-catlinks-ready');
    cat.classList.remove('clbi-catlinks-empty');
    cat.classList.remove('clbi-catlinks-pending');
    cat.classList.remove('clbi-catlinks-loading');
    cat.removeAttribute('data-clbi-catlinks-fetching');
    cat.setAttribute('data-clbi-catlinks-page', pageTitle || getCurrentPageTitleForCatlinks());
    clearCatlinksInlineHiding(cat);
    exposeHiddenCatlinks(cat);
}

function markCatlinksEmpty(cat) {
    if (!cat) return;

    cat.classList.add('catlinks');
    cat.classList.add('clbi-catlinks-empty');
    cat.classList.remove('clbi-catlinks-ready');
    cat.classList.remove('clbi-catlinks-pending');
    cat.classList.remove('clbi-catlinks-loading');
    cat.removeAttribute('data-clbi-catlinks-fetching');
    cat.removeAttribute('data-clbi-catlinks-page');
}

function markCatlinksPending(cat, pageTitle) {
    if (!cat) return;

    cat.classList.add('catlinks');
    cat.classList.remove('clbi-catlinks-ready');
    cat.classList.remove('clbi-catlinks-empty');
    cat.classList.add('clbi-catlinks-pending');
    cat.classList.add('clbi-catlinks-loading');
    cat.setAttribute('data-clbi-catlinks-fetching', '1');
    cat.setAttribute('data-clbi-catlinks-page', pageTitle || getCurrentPageTitleForCatlinks());
}

function renderFetchedCatlinks(cat, categories, pageTitle) {
    var container;
    var ul;
    var normalized;

    if (!cat) return false;

    normalized = dedupeCatlinkCategories(categories);

    if (!normalized.length) {
        markCatlinksEmpty(cat);
        return false;
    }

    cat.innerHTML = '';
    cat.classList.add('catlinks');
    cat.classList.add('clbi-catlinks-api-populated');

    container = document.createElement('div');
    container.className = 'mw-normal-catlinks';
    container.appendChild(document.createTextNode('분류: '));

    ul = document.createElement('ul');

    normalized.forEach(function (item) {
        var title = String(item && item.title ? item.title : '').trim();
        var li;
        var a;

        if (!title) return;

        li = document.createElement('li');
        a = document.createElement('a');
        a.href = mw.util.getUrl(title);
        a.title = title;
        a.textContent = makeCategoryLinkTitle(title);

        if (item.hidden) {
            li.className = 'clbi-hidden-category-item';
        }

        li.appendChild(a);
        ul.appendChild(li);
    });

    if (!ul.children.length) {
        markCatlinksEmpty(cat);
        return false;
    }

    container.appendChild(ul);
    cat.appendChild(container);
    markCatlinksReady(cat, pageTitle);
    return true;
}

function fetchCatlinksForPage(pageTitle, callback) {
    var api;

    if (typeof pageTitle === 'function') {
        callback = pageTitle;
        pageTitle = getCurrentPageTitleForCatlinks();
    }

    pageTitle = String(pageTitle || '').trim();

    if (!pageTitle || !shouldFetchCatlinks()) {
        if (typeof callback === 'function') callback([], pageTitle);
        return;
    }

    if (!mw.Api) {
        if (typeof callback === 'function') callback([], pageTitle);
        return;
    }

    api = new mw.Api();
    api.get({
        action: 'query',
        prop: 'categories',
        titles: pageTitle,
        cllimit: 'max',
        clprop: 'hidden',
        formatversion: 2
    }).done(function (data) {
        var pages = data && data.query && data.query.pages ? data.query.pages : [];
        var page = pages && pages.length ? pages[0] : null;
        var categories = page && page.categories ? page.categories : [];

        if (typeof callback === 'function') callback(categories || [], pageTitle);
    }).fail(function () {
        if (typeof callback === 'function') callback([], pageTitle);
    });
}

function finalizeEmptyCatlinks(cat) {
    if (!cat) return;
    if (!cat.isConnected) return;

    clearCatlinksInlineHiding(cat);
    exposeHiddenCatlinks(cat);

    if (hasRenderedCatlinkItems(cat)) {
        markCatlinksReady(cat, getCurrentPageTitleForCatlinks());
        return;
    }

    markCatlinksEmpty(cat);
}

function fetchCatlinksIfNeeded(cat) {
    var configCategories;
    var pageTitle;
    var requestToken;

    if (!cat) return;
    if (!cat.isConnected) return;

    pageTitle = getCurrentPageTitleForCatlinks();

    clearCatlinksInlineHiding(cat);
    exposeHiddenCatlinks(cat);

    if (hasRenderedCatlinkItems(cat)) {
        markCatlinksReady(cat, pageTitle);
        return;
    }

    configCategories = getConfigCatlinksCategories();
    if (configCategories.length) {
        renderFetchedCatlinks(cat, configCategories, pageTitle);
        return;
    }

    if (!shouldFetchCatlinks()) {
        finalizeEmptyCatlinks(cat);
        return;
    }

    if (cat.getAttribute('data-clbi-catlinks-fetching') === '1' && cat.getAttribute('data-clbi-catlinks-page') === pageTitle) return;

    requestToken = ++CLBI_CATLINKS_FETCH_TOKEN;
    markCatlinksPending(cat, pageTitle);

    fetchCatlinksForPage(pageTitle, function (categories, requestedPage) {
        if (requestToken !== CLBI_CATLINKS_FETCH_TOKEN) return;
        if (requestedPage !== getCurrentPageTitleForCatlinks()) return;
        if (!cat || !cat.isConnected) return;
        if (cat.getAttribute('data-clbi-catlinks-page') !== requestedPage) return;

        if (!renderFetchedCatlinks(cat, categories, requestedPage)) {
            finalizeEmptyCatlinks(cat);
        }
    });
}

function normalizeCatlinksPanel(cat) {
    if (!cat) return;

    cat.classList.add('catlinks');
    clearCatlinksInlineHiding(cat);
    exposeHiddenCatlinks(cat);

    if (hasRenderedCatlinkItems(cat)) {
        markCatlinksReady(cat, getCurrentPageTitleForCatlinks());
        return;
    }

    fetchCatlinksIfNeeded(cat);
}

function createCatlinksPanel(target, className) {
    var cat;

    if (!target || !target.length) return null;

    cat = document.createElement('div');
    cat.id = 'catlinks';
    cat.className = className || 'catlinks clbi-catlinks-created clbi-catlinks-pending';
    target.append(cat);
    return cat;
}

function prepareSpaCatlinksBeforeInsert(root) {
    var nodes;
    var target;
    var configCategories;
    var pageTitle;

    if (!root) return;

    pageTitle = getCurrentPageTitleForCatlinks();
    configCategories = getConfigCatlinksCategories();
    nodes = getCatlinkNodes(root);

    nodes.forEach(function (node) {
        node.classList.add('catlinks');
        clearCatlinksInlineHiding(node);
        exposeHiddenCatlinks(node);

        if (hasRenderedCatlinkItems(node)) {
            markCatlinksReady(node, pageTitle);
        } else if (configCategories.length) {
            renderFetchedCatlinks(node, configCategories, pageTitle);
        } else {
            markCatlinksEmpty(node);
        }
    });

    if (nodes.length || !configCategories.length) return;

    target = getCatlinksTarget(root);
    if (!target.length) target = $(root);

    renderFetchedCatlinks(createCatlinksPanel(target, 'catlinks catlinks-allhidden clbi-catlinks-created clbi-catlinks-pending'), configCategories, pageTitle);
}

function moveCatlinksToBottom() {
    var main = $('.liberty-content-main').first();
    var target = getCatlinksTarget();
    var catlinks = getCatlinkNodes();
    var configCategories;
    var pageTitle;
    var requestToken;

    if (!main.length || !target.length) return;

    pageTitle = getCurrentPageTitleForCatlinks();

    catlinks.forEach(function (node) {
        var catNode = $(node);

        if (node.parentNode !== target[0]) {
            catNode.appendTo(target);
        }

        normalizeCatlinksPanel(node);
    });

    if (catlinks.length) return;

    configCategories = getConfigCatlinksCategories();
    if (configCategories.length) {
        renderFetchedCatlinks(createCatlinksPanel(target, 'catlinks catlinks-allhidden clbi-catlinks-created clbi-catlinks-pending'), configCategories, pageTitle);
        return;
    }

    if (!shouldFetchCatlinks()) return;

    requestToken = ++CLBI_CATLINKS_FETCH_TOKEN;

    fetchCatlinksForPage(pageTitle, function (categories, requestedPage) {
        var cat;

        if (requestToken !== CLBI_CATLINKS_FETCH_TOKEN) return;
        if (requestedPage !== getCurrentPageTitleForCatlinks()) return;
        if (getCatlinkNodes().length) return;
        if (!categories || !categories.length) return;

        cat = createCatlinksPanel(target, 'catlinks catlinks-allhidden clbi-catlinks-created clbi-catlinks-pending');
        renderFetchedCatlinks(cat, categories, requestedPage);
    });
}

// 대문 스타일
function initCategoryNavIfAvailable(root) {
    /*
    CategoryNav.js는 대문 카테고리 네비를 SVG로 생성한다.

    Common.js가 SPA로 본문을 갈아끼운 뒤에는 MediaWiki 원래 페이지 로드와 달리
    CategoryNav.js의 초기 DOMContentLoaded만으로는 새 mount를 다시 잡지 못할 수 있다.
    CategoryNav.js 자체도 mw.hook('wikipage.content')를 듣지만, 로드 순서와 SPA 타이밍이
    엇갈릴 수 있으므로 Common.js 쪽에서도 존재 여부를 확인한 뒤 한 번 더 호출한다.

    이 함수는 CategoryNav.js가 아직 로드되지 않았으면 아무 것도 하지 않는다.
    */
    if (window.CategoryNav && typeof window.CategoryNav.init === 'function') {
        window.CategoryNav.init(root || document);
        return;
    }

    if (
        window.CLBI &&
        window.CLBI.categoryNav &&
        typeof window.CLBI.categoryNav.init === 'function'
    ) {
        window.CLBI.categoryNav.init(root || document);
    }
}

function removeLegacyMainPageHero() {
    /*
    기존 대문 전용 레거시 요소 정리
    -----------------------------------------
    이전 대문 구조에서는 Common.js가 본문 바깥에 #clbi-main-logo를 직접 삽입하고,
    본문 안의 #clbi-main-crt-hero를 #clbi-main-crt-hero-wrap으로 감싸서
    .liberty-content-main 위쪽으로 재배치했다.

    새 대문은 본문 내부의 .main-portal이 로고, 알림, 카테고리 네비, 이미지 피드,
    방명록, 상태 패널을 모두 담당한다. 따라서 Common.js가 별도 로고나 CRT 래퍼를
    삽입하면 새 로고/콘텐츠와 중복된다.

    여기서는 JS가 만들던 바깥 로고와 CRT 래퍼를 제거하고, 예전 대문 원본이나
    캐시된 렌더 결과에 남아 있을 수 있는 #clbi-main-crt-hero도 제거한다.
    */
    $('#clbi-main-logo').remove();
    $('#clbi-main-crt-hero-wrap').remove();
    $('#clbi-main-crt-hero').remove();
}


function setNativePageTitleHiddenHard(hidden) {
    var selectors = [
        '.liberty-content-header',
        '.liberty-content-header .title',
        '.liberty-content-header .title h1',
        '.liberty-content-header h1',
        '#firstHeading',
        '.firstHeading',
        '.mw-first-heading',
        '.page-heading',
        '.page-header',
        '.mw-page-title-main',
        '.mw-page-title-namespace',
        '.mw-page-title-separator'
    ];

    document.querySelectorAll(selectors.join(',')).forEach(function(node) {
        if (!node || !node.style) return;

        if (hidden) {
            node.setAttribute('data-clbi-title-hidden', 'true');
            node.style.setProperty('display', 'none', 'important');
            node.style.setProperty('visibility', 'hidden', 'important');
            node.style.setProperty('height', '0', 'important');
            node.style.setProperty('min-height', '0', 'important');
            node.style.setProperty('margin', '0', 'important');
            node.style.setProperty('padding', '0', 'important');
            node.style.setProperty('overflow', 'hidden', 'important');
        } else if (node.getAttribute('data-clbi-title-hidden') === 'true') {
            node.removeAttribute('data-clbi-title-hidden');
            node.style.removeProperty('display');
            node.style.removeProperty('visibility');
            node.style.removeProperty('height');
            node.style.removeProperty('min-height');
            node.style.removeProperty('margin');
            node.style.removeProperty('padding');
            node.style.removeProperty('overflow');
        }
    });
}

function applyDefaultPageTitleVisibility() {
    var hideTitle = true;
    var isSystemAssetPage = false;

    if (window.CLBI_PAGE_SHELL && typeof window.CLBI_PAGE_SHELL.isSystemAssetPage === 'function') {
        isSystemAssetPage = window.CLBI_PAGE_SHELL.isSystemAssetPage();
    }

    if (isSystemAssetPage) {
        hideTitle = true;
    } else if (window.CLBI_PAGE_SHELL && typeof window.CLBI_PAGE_SHELL.isBackendOrSystemPage === 'function') {
        hideTitle = !window.CLBI_PAGE_SHELL.isBackendOrSystemPage();
    }

    $('body')
        .toggleClass('page-title-hidden', hideTitle)
        .toggleClass('page-title-visible', !hideTitle)
        .toggleClass('clbi-system-doc-page', isSystemAssetPage);

    $('.content-tools').css('display', 'none');

    if (isSystemAssetPage && window.CLBI_PAGE_SHELL && typeof window.CLBI_PAGE_SHELL.renderSystemDocIndicator === 'function') {
        window.CLBI_PAGE_SHELL.renderSystemDocIndicator();
    } else if (!isSystemAssetPage && window.CLBI_PAGE_SHELL && typeof window.CLBI_PAGE_SHELL.removeSystemDocIndicator === 'function') {
        window.CLBI_PAGE_SHELL.removeSystemDocIndicator();
    }

    if (hideTitle) {
        $('.liberty-content-header').css('display', 'none');
        $('.mw-page-title-main, .mw-page-title-namespace, .mw-page-title-separator').addClass('clbi-hide');
        $('#firstHeading, .firstHeading, .mw-first-heading, .page-heading, .page-header').css('display', 'none');
        setNativePageTitleHiddenHard(true);
    } else {
        $('.liberty-content-header').css('display', '');
        $('.mw-page-title-main, .mw-page-title-namespace, .mw-page-title-separator').removeClass('clbi-hide');
        $('#firstHeading, .firstHeading, .mw-first-heading, .page-heading, .page-header').css('display', '');
        setNativePageTitleHiddenHard(false);
    }
}

function applyMainPageStyle() {
    var specialPage = mw.config.get('wgCanonicalSpecialPageName');
    if (specialPage === 'Preferences') return;

    var pageName = normalizePageName(mw.config.get('wgPageName'));
    var namespaceNumber = mw.config.get('wgNamespaceNumber');
    var isMainPage = (pageName === '대문');
    var isUserProfilePage = (namespaceNumber === 2);
    var isScreenDoc = ($('.screen-header').length > 0);
    var hideTools = (isMainPage || isUserProfilePage || !canShowContentTools());

    $('body').toggleClass('user-profile-page', isUserProfilePage);
    $('body').toggleClass('clbi-main-page', isMainPage);

    // 모든 문서에서 분류 바를 본문 컨테이너 아래로 이동
    moveCatlinksToBottom();

    if (isMainPage) {
        $('.liberty-content-header').css('display', 'none');
        $('.mw-page-title-main').addClass('clbi-hide');
        setNativePageTitleHiddenHard(true);
        $('.catlinks').css('display', 'none');
        $('.liberty-content-main').css('border-radius', '0');

        // 새 대문은 .main-portal 본문 구조가 로고/히어로를 담당한다.
        // Common.js의 구식 바깥 로고/CRT 재배치 루틴은 사용하지 않는다.
        removeLegacyMainPageHero();
        $('#clbi-tools-box').remove();

        $('.content-tools').css('display', 'none');

        initCategoryNavIfAvailable(document);

    } else if (isUserProfilePage) {
        $('.liberty-content-header').css('display', 'none');
        $('.mw-page-title-main, .mw-page-title-namespace, .mw-page-title-separator').addClass('clbi-hide');
        $('.catlinks').css('display', 'none');
        $('.liberty-content-main').css('border-radius', '0');

        $('#clbi-main-logo').remove();
        $('#clbi-main-crt-hero-wrap').remove();
        $('#clbi-main-crt-hero').remove();
        $('#clbi-tools-box').remove();

        $('.content-tools').css('display', 'none');

    } else if (isScreenDoc) {
        $('.liberty-content-header').css('display', 'none');
        $('.mw-page-title-main').addClass('clbi-hide');
        $('.catlinks').css('display', '');
        $('.liberty-content-main').css('border-radius', '0');

        $('#clbi-main-logo').remove();
        $('#clbi-main-crt-hero-wrap').remove();

        if ($('#clbi-tools-box').length === 0 && canShowContentTools()) {
            var $toolsBox = $('<div id="clbi-tools-box" class="clbi-left-box"></div>');
            var $toolsTitle = $('<div class="clbi-left-title">관리</div>');
            var $toolsContent = $('<div class="clbi-left-content"></div>');

            $toolsContent.append($('.content-tools .btn-group').clone(true));
            $toolsBox.append($toolsTitle).append($toolsContent);
            $('#clbi-left-sidebar').append($toolsBox);
        }

        $('.content-tools').css('display', 'none');

    } else {
        $('.liberty-content-header').css('display', '');
        $('.mw-page-title-main, .mw-page-title-namespace, .mw-page-title-separator').removeClass('clbi-hide');
        $('.catlinks').css('display', '');
        $('.liberty-content-main').css('border-radius', '0');

        $('#clbi-main-logo').remove();
        $('#clbi-main-crt-hero-wrap').remove();
        $('#clbi-tools-box').remove();
    }

    if (!isUserProfilePage) {
        $('.profile-card').remove();
        $('.user-profile-portal').removeClass('user-profile-portal');
    }

    $('.content-tools').css('display', 'none');

    applyDefaultPageTitleVisibility();
    updateSidebar();
}

// 본문 기본 목차 제거
function removeNativeTocFromContent() {
    $('.liberty-content-main #toc, .liberty-content-main .toc').remove();
}

// 왼쪽 목차: MediaWiki 문단 ID 가져오기
function getHeadingId(heading) {
    if (heading.id) {
        return heading.id;
    }

    var headline = heading.querySelector('.mw-headline[id]');
    if (headline && headline.id) {
        return headline.id;
    }

    return '';
}

// 왼쪽 목차: MediaWiki 문단 제목 텍스트 가져오기
function getHeadingText(heading) {
    var headline = heading.querySelector('.mw-headline');
    var source = headline || heading;
    var clone = source.cloneNode(true);

    $(clone).find('.mw-editsection, .mw-editsection-bracket, .mw-editsection-divider').remove();

    return (clone.textContent || '')
        .replace(/\s+/g, ' ')
        .trim();
}

// 왼쪽 목차: 긴 제목에 자동 스크롤 적용
function initTocTitleScroll(root) {
    var $items = root
        ? $(root).find('.toc-scroll-text')
        : $('#side-toc-box .toc-scroll-text');

    $items.each(function () {
        var $text = $(this);
        var $wrap = $text.closest('.toc-scroll-wrap');

        if (!$wrap.length) return;

        var wrapW = Math.floor($wrap.width());
        var textW = Math.ceil(this.scrollWidth);

        // 왼쪽 목차: 레이아웃 계산이 끝나지 않았으면 이번 실행에서는 건드리지 않는다.
        if (!wrapW || !textW) return;

        if (textW <= wrapW + 12) {
            // 왼쪽 목차: 칸을 넘지 않는 제목은 전체 텍스트를 그대로 보여준다.
            $wrap.removeClass('is-scrolling');

            if ($text.data('toc-scroll-enabled')) {
                $text.css({
                    animation: '',
                    'animation-delay': '',
                    '--scroll-dist': ''
                });
                $text.removeData('toc-scroll-enabled');
                $text.removeData('toc-scroll-key');
            }

            return;
        }

        var scrollDist = '-' + (textW - wrapW + 10) + 'px';
        var duration = Math.max(7, textW / 38) * 1.25;
        var scrollKey = scrollDist + '|' + duration;

        // 왼쪽 목차: 긴 제목에는 오른쪽 페이드와 스크롤을 적용한다.
        $wrap.addClass('is-scrolling');

        // 왼쪽 목차: 같은 값으로 이미 적용된 애니메이션은 다시 초기화하지 않는다.
        if ($text.data('toc-scroll-key') === scrollKey) {
            return;
        }

        $text.data('toc-scroll-enabled', true);
        $text.data('toc-scroll-key', scrollKey);

        $text.css({
            // 왼쪽 목차: 페이지 진입 직후에는 잠시 읽을 시간을 준 뒤 흐르게 한다.
            animation: 'toc-scroll-blink-reset ' + duration + 's linear infinite',
            'animation-delay': '1s',
            '--scroll-dist': scrollDist
        });
    });
}

// 목차를 왼쪽 사이드바에 새로 생성
function moveTocToLeftSidebar() {
    removeNativeTocFromContent();
    $('#side-toc-box').remove();
    return;

    // 왼쪽 목차: MediaWiki가 만든 원래 목차는 본문에서 제거한다.
    removeNativeTocFromContent();

    var leftSidebar = document.getElementById('clbi-left-sidebar');
    if (!leftSidebar) return;

    var content =
        document.querySelector('.liberty-content-main .mw-parser-output') ||
        document.querySelector('.liberty-content-main');

    if (!content) return;

    var headings = Array.prototype.slice.call(
        content.querySelectorAll('h2, h3')
    ).filter(function (heading) {
        if (heading.closest('#toc, .toc, #side-toc-box')) return false;

        var id = getHeadingId(heading);
        var text = getHeadingText(heading);

        if (!id || !text) return false;

        return true;
    });

    var tocKey = headings.map(function (heading) {
        return getHeadingId(heading) + '|' + getHeadingText(heading);
    }).join('||');

    var existingBox = document.getElementById('side-toc-box');

    // 왼쪽 목차: 같은 문서에서 같은 목차를 이미 만들었다면 다시 지우고 만들지 않는다.
    if (existingBox && existingBox.getAttribute('data-toc-key') === tocKey) {
        initTocTitleScroll(existingBox);
        return;
    }

    if (existingBox) {
        existingBox.remove();
    }

    if (!headings.length) return;

    var tocBox = document.createElement('div');
    tocBox.className = 'clbi-left-box';
    tocBox.id = 'side-toc-box';
    tocBox.setAttribute('data-toc-key', tocKey);

    var title = document.createElement('div');
    title.className = 'clbi-left-title';

    // 왼쪽 목차: 박스 제목은 Lang.js의 현재 UI 언어를 따른다.
    var currentLang = getCurrentLang();
    var t = (window.LANG && window.LANG[currentLang]) ? window.LANG[currentLang] : window.LANG.ko;
    var tocTitleText = (t && t.toc) ? t.toc : '목차';

    title.textContent = tocTitleText;

    var body = document.createElement('div');
    body.className = 'clbi-left-content toc-sidebar-content';

    var list = document.createElement('ul');
    list.className = 'generated-toc';

    headings.forEach(function (heading) {
        var id = getHeadingId(heading);
        var text = getHeadingText(heading);
        var level = heading.tagName.toLowerCase() === 'h3' ? 3 : 2;

        var item = document.createElement('li');
        item.className = 'toc-level-' + level;

        var link = document.createElement('a');
        link.setAttribute('href', '#' + id);

        // 왼쪽 목차: 긴 제목 스크롤을 위해 텍스트를 별도 span으로 감싼다.
        var textWrap = document.createElement('span');
        textWrap.className = 'toc-scroll-wrap';

        var textSpan = document.createElement('span');
        textSpan.className = 'toc-scroll-text';
        textSpan.textContent = text;

        textWrap.appendChild(textSpan);
        link.appendChild(textWrap);

        item.appendChild(link);
        list.appendChild(item);
    });

    body.appendChild(list);
    tocBox.appendChild(title);
    tocBox.appendChild(body);
    leftSidebar.appendChild(tocBox);

    // 왼쪽 목차: DOM 배치가 끝난 뒤 긴 제목 스크롤 여부를 계산한다.
    requestAnimationFrame(function () {
        initTocTitleScroll(tocBox);

        setTimeout(function () {
            initTocTitleScroll(tocBox);
        }, 120);
    });
}


// 우측 광고판: 이미지/번역 캡션 목록
var RIGHT_BILLBOARD_ITEMS = [
    {
        file: 'Side-visual-001.png',
        alt: 'PROOF TO THE WORLD / YOU ONCE PART OF IT',
        duration: 3000,
        caption: [
            '"당신이 한때 이 세계의',
            '',
            '일부였다는 것을 증명하십시오"'
        ]
    },
    {
        file: 'Side-visual-002.png',
        alt: 'APPLY NOW',
        duration: 1000,
        caption: [
            '"지금 지원하세요!"'
        ]
    },
    {
        file: 'Side-visual-003.png',
        alt: 'APPLY NOW',
        duration: 1000,
        caption: [
            '"지금 지원하세요!"'
        ]
    },
    {
        file: 'Side-visual-002.png',
        alt: 'APPLY NOW',
        duration: 1000,
        caption: [
            '"지금 지원하세요!"'
        ]
    }
];

function getRightBillboardItem(index) {
    var items = RIGHT_BILLBOARD_ITEMS;

    if (!items || !items.length) {
        return {
            file: 'Side-visual-001.png',
            alt: '',
            caption: []
        };
    }

    var normalized = index % items.length;
    if (normalized < 0) normalized += items.length;

    return items[normalized];
}

function getRightBillboardImageUrl(fileName) {
    return '/index.php?title=특수:Redirect/file/' + encodeURIComponent(fileName || 'Side-visual-001.png');
}

function getRightBillboardCaptionHtml(item) {
    var lines = item && item.caption ? item.caption : [];
    var html = '';

    function escapeCaptionText(value) {
        return String(value == null ? '' : value)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/\"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    lines.forEach(function(line) {
        var text = String(line == null ? '' : line);
        var isGap = !text.trim();
        var className = 'right-billboard-caption-line' + (isGap ? ' is-gap' : '');
        html += '<span class="' + className + '">' + (isGap ? '&nbsp;' : escapeCaptionText(text)) + '</span>';
    });

    return html;
}

function setRightBillboardItem(index) {
    var box = document.querySelector('.right-billboard-box');
    if (!box) return;

    var item = getRightBillboardItem(index);
    var src = getRightBillboardImageUrl(item.file);
    var images = box.querySelectorAll('.right-billboard-image');
    var caption = box.querySelector('#right-billboard-caption');
    var emptySub = box.querySelector('.right-billboard-empty-sub');

    box.setAttribute('data-billboard-index', String(index));
    box.classList.remove('is-empty');

    Array.prototype.forEach.call(images, function(img) {
        img.style.display = '';
        img.setAttribute('src', src);
        img.setAttribute('alt', img.classList.contains('right-billboard-image-base') ? (item.alt || '') : '');
    });

    if (caption) {
        caption.innerHTML = getRightBillboardCaptionHtml(item);
    }

    if (emptySub) {
        emptySub.textContent = item.file || 'Side-visual-001.png';
    }
}

function getRightBillboardItemDuration(item) {
    var duration = item && item.duration ? parseInt(item.duration, 10) : 3000;

    if (Number.isNaN(duration) || duration < 500) {
        duration = 3000;
    }

    return duration;
}

function initRightBillboardCarousel() {
    var box = document.querySelector('.right-billboard-box');
    if (!box || box.getAttribute('data-billboard-ready') === '1') return;

    box.setAttribute('data-billboard-ready', '1');
    box.setAttribute('data-billboard-index', '0');

    setRightBillboardItem(0);

    if (!RIGHT_BILLBOARD_ITEMS || RIGHT_BILLBOARD_ITEMS.length <= 1) return;

    function scheduleNext() {
        var current = parseInt(box.getAttribute('data-billboard-index') || '0', 10);
        if (Number.isNaN(current)) current = 0;

        var currentItem = getRightBillboardItem(current);
        var delay = getRightBillboardItemDuration(currentItem);

        window.setTimeout(function() {
            if (!document.body.contains(box)) return;

            if (!document.hidden) {
                setRightBillboardItem(current + 1);
            }

            scheduleNext();
        }, delay);
    }

    scheduleNext();
}


function escapeRightBillboardAttr(value) {
    return String(value == null ? '' : value)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

function buildRightBillboardBox() {
    var billboardInitial = getRightBillboardItem(0);
    var billboardSrc = getRightBillboardImageUrl(billboardInitial.file);

    return '' +
        '<div class="clbi-left-box right-billboard-box left-billboard-box left-ad-box" data-billboard-index="0">' +
            '<div class="clbi-left-title right-billboard-title left-ad-title left-ad-title-iconless">' +
                '<span id="clbi-title-left-ad" class="left-ad-title-label">Looking for a job?</span>' +
            '</div>' +
            '<div class="clbi-left-content left-ad-content-shell">' +
                '<div class="right-billboard-body">' +
                    '<div class="right-billboard-recess">' +
                        '<div class="right-billboard-screen">' +
                            '<img id="right-billboard-image" class="right-billboard-image right-billboard-image-base" src="' + escapeRightBillboardAttr(billboardSrc) + '" alt="' + escapeRightBillboardAttr(billboardInitial.alt || '') + '" onload="var b=this.closest(\'.right-billboard-box\'); if(b){b.classList.remove(\'is-empty\');}" onerror="this.onerror=null;this.style.display=\'none\';var b=this.closest(\'.right-billboard-box\'); if(b){b.classList.add(\'is-empty\');}">' +
                            '<img class="right-billboard-image right-billboard-image-bloom" src="' + escapeRightBillboardAttr(billboardSrc) + '" alt="" aria-hidden="true" onerror="this.onerror=null;this.style.display=\'none\';">' +
                            '<img class="right-billboard-image right-billboard-slice right-billboard-slice-a" src="' + escapeRightBillboardAttr(billboardSrc) + '" alt="" aria-hidden="true" onerror="this.onerror=null;this.style.display=\'none\';">' +
                            '<img class="right-billboard-image right-billboard-slice right-billboard-slice-b" src="' + escapeRightBillboardAttr(billboardSrc) + '" alt="" aria-hidden="true" onerror="this.onerror=null;this.style.display=\'none\';">' +
                            '<img class="right-billboard-image right-billboard-slice right-billboard-slice-c" src="' + escapeRightBillboardAttr(billboardSrc) + '" alt="" aria-hidden="true" onerror="this.onerror=null;this.style.display=\'none\';">' +
                            '<div class="right-billboard-glitch" aria-hidden="true"></div>' +
                            '<div class="right-billboard-tear" aria-hidden="true"></div>' +
                            '<div class="right-billboard-empty" aria-hidden="true">' +
                                '<span class="right-billboard-empty-main">SIGNAL EMPTY</span>' +
                                '<span class="right-billboard-empty-sub">' + escapeRightBillboardAttr(billboardInitial.file || 'Side-visual-001.png') + '</span>' +
                            '</div>' +
                        '</div>' +
                    '</div>' +
                    '<div id="right-billboard-caption" class="right-billboard-caption" aria-hidden="true">' + getRightBillboardCaptionHtml(billboardInitial) + '</div>' +
                    '<div class="right-billboard-bottom-finish left-ad-bottom-finish" aria-hidden="true"></div>' +
                '</div>' +
            '</div>' +
        '</div>';
}


var GREAT_WALL_DATA_TITLE = '프로젝트:The_Great_Wall/Data.json';
var GREAT_WALL_LIST_LIMIT = 0;
var greatWallState = {
    data: { entries: {} },
    loaded: false,
    loading: false,
    saving: false,
    selectedOwnEntry: false,
    statusText: ''
};

function normalizeGreatWallData(data) {
    var normalized = { entries: {} };
    var entries = data && data.entries && typeof data.entries === 'object' ? data.entries : {};

    Object.keys(entries).forEach(function(key) {
        var item = entries[key];
        var user = item && item.user ? String(item.user) : String(key || '');
        var text = item && item.text ? String(item.text) : '';
        var timestamp = item && item.timestamp ? String(item.timestamp) : '';

        if (!user || !text) return;

        normalized.entries[user] = {
            user: user,
            text: text.slice(0, 140),
            timestamp: timestamp || new Date(0).toISOString()
        };
    });

    return normalized;
}

function parseGreatWallData(text) {
    var parsed;

    try {
        parsed = text ? JSON.parse(text) : {};
    } catch (err) {
        console.error('The Great Wall data parse failed:', err);
        parsed = {};
    }

    return normalizeGreatWallData(parsed);
}

function stringifyGreatWallData(data) {
    return JSON.stringify(normalizeGreatWallData(data), null, 2) + '\n';
}

function getGreatWallRevisionText(page) {
    var rev;
    var slot;

    if (!page || !page.revisions || !page.revisions.length) return '';

    rev = page.revisions[0];

    if (rev.slots && rev.slots.main) {
        slot = rev.slots.main;
        return slot.content || slot['*'] || '';
    }

    return rev.content || rev['*'] || '';
}

function fetchGreatWallData() {
    var api = new mw.Api();

    return api.get({
        action: 'query',
        prop: 'revisions',
        titles: GREAT_WALL_DATA_TITLE,
        rvprop: 'content|timestamp',
        rvslots: 'main',
        formatversion: 2
    }).then(function(data) {
        var pages = data && data.query && data.query.pages ? data.query.pages : [];
        var page = pages[0] || null;

        if (!page || page.missing) {
            return { entries: {} };
        }

        return parseGreatWallData(getGreatWallRevisionText(page));
    }, function(err) {
        console.error('The Great Wall load failed:', err);
        return { entries: {} };
    });
}

function getGreatWallEntries(data) {
    var entries = data && data.entries && typeof data.entries === 'object' ? data.entries : {};

    return Object.keys(entries).map(function(key) {
        return entries[key];
    }).filter(function(item) {
        return item && item.user && item.text;
    }).sort(function(a, b) {
        return String(a.timestamp || '').localeCompare(String(b.timestamp || ''));
    });
}

function getGreatWallMessageTime(timestamp) {
    var date = timestamp ? new Date(timestamp) : null;
    var month;
    var day;
    var hour;
    var minute;

    if (!date || isNaN(date.getTime())) return '—';

    month = String(date.getMonth() + 1).padStart(2, '0');
    day = String(date.getDate()).padStart(2, '0');
    hour = String(date.getHours()).padStart(2, '0');
    minute = String(date.getMinutes()).padStart(2, '0');

    return month + '.' + day + ' ' + hour + ':' + minute;
}

function getGreatWallAvatarSrc(user) {
    return '/index.php?title=특수:Redirect/file/Pfp-' + encodeURIComponent(String(user || '')) + '.png';
}

function buildGreatWallEntryHtml(item, currentUser, selectedOwnEntry) {
    var isOwn = currentUser && item.user === currentUser;
    var tag = isOwn ? 'button' : 'div';
    var attrs = isOwn ? ' type="button" data-great-wall-own-entry="1" aria-label="Edit your wall message"' : '';
    var className = 'great-wall-entry' + (isOwn ? ' is-own' : '') + (isOwn && selectedOwnEntry ? ' is-selected' : '');
    var avatarSrc = getGreatWallAvatarSrc(item.user);
    var messageTime = getGreatWallMessageTime(item.timestamp);
    var isoTime = item.timestamp || '';

    return '' +
        '<' + tag + attrs + ' class="' + className + '">' +
            '<img class="great-wall-avatar" src="' + escapeClbiHtml(avatarSrc) + '" alt="" onerror="this.onerror=null;this.src=&quot;/index.php?title=특수:Redirect/file/Pfp-default.png&quot;;">' +
            '<div class="great-wall-bubble">' +
                '<div class="great-wall-entry-head">' +
                    '<span class="great-wall-user">@' + escapeClbiHtml(item.user) + '</span>' +
                    '<span class="great-wall-time" title="' + escapeClbiHtml(isoTime) + '">' + escapeClbiHtml(messageTime) + '</span>' +
                '</div>' +
                '<div class="great-wall-text">' + escapeClbiHtml(item.text) + '</div>' +
            '</div>' +
        '</' + tag + '>';
}

function renderGreatWallBox() {
    var box = document.getElementById('great-wall-sidebar');
    var list = document.getElementById('great-wall-list');
    var input = document.getElementById('great-wall-input');
    var submit = document.getElementById('great-wall-submit');
    var deleteButton = document.getElementById('great-wall-delete');
    var status = document.getElementById('great-wall-status');
    var currentUser = mw.config.get('wgUserName') || '';
    var entries = getGreatWallEntries(greatWallState.data);
    var ownEntry = currentUser && greatWallState.data.entries ? greatWallState.data.entries[currentUser] : null;
    var visibleEntries = [];
    var seen = {};

    if (!box || !list) return;

    box.classList.toggle('is-guest', !currentUser);
    box.classList.toggle('is-loading', !!greatWallState.loading);
    box.classList.toggle('is-saving', !!greatWallState.saving);
    box.classList.toggle('has-own-entry', !!ownEntry);
    box.classList.toggle('is-own-selected', !!greatWallState.selectedOwnEntry);

    entries.forEach(function(item) {
        if (seen[item.user]) return;
        visibleEntries.push(item);
        seen[item.user] = true;
    });

    if (greatWallState.loading && !greatWallState.loaded) {
        list.innerHTML = '<div class="great-wall-empty">SYNCING WALL</div>';
    } else if (!visibleEntries.length) {
        list.innerHTML = '<div class="great-wall-empty">NO MARKS</div>';
    } else {
        list.innerHTML = visibleEntries.map(function(item) {
            return buildGreatWallEntryHtml(item, currentUser, greatWallState.selectedOwnEntry);
        }).join('');
    }

    if (list && list.scrollHeight > list.clientHeight) {
        list.scrollTop = list.scrollHeight;
    }

    if (status) {
        // Status text is intentionally suppressed in the composer strip; the area is spacing-only UI.
        status.textContent = '';
    }

    if (!input || !submit) return;

    input.disabled = false;
    input.readOnly = false;
    input.removeAttribute('aria-readonly');

    if (!currentUser) {
        input.disabled = true;
        input.readOnly = false;
        input.value = '';
        input.placeholder = '담벼락';
        submit.textContent = 'LOGIN';
        submit.disabled = false;
        if (deleteButton) {
            deleteButton.disabled = true;
            deleteButton.title = 'Login required';
        }
        return;
    }

    if (greatWallState.saving || greatWallState.loading) {
        input.disabled = true;
        input.readOnly = false;
        submit.disabled = true;
        submit.textContent = greatWallState.saving ? 'SAVE' : 'SYNC';
        if (deleteButton) {
            deleteButton.disabled = true;
            deleteButton.title = greatWallState.saving ? 'Saving' : 'Syncing';
        }
        return;
    }

    if (deleteButton) {
        deleteButton.disabled = !ownEntry;
        deleteButton.title = ownEntry ? 'Delete your mark' : 'No mark to delete';
    }

    if (ownEntry && !greatWallState.selectedOwnEntry) {
        input.disabled = false;
        input.readOnly = true;
        input.setAttribute('aria-readonly', 'true');
        input.value = '';
        input.placeholder = '담벼락';
        submit.disabled = true;
        submit.textContent = 'UPDATE';
        return;
    }

    input.disabled = false;
    input.readOnly = false;
    input.removeAttribute('aria-readonly');
    input.placeholder = '담벼락';
    if (ownEntry && greatWallState.selectedOwnEntry && !input.value) {
        input.value = ownEntry.text || '';
    }
    submit.disabled = false;
    submit.textContent = ownEntry ? 'UPDATE' : 'POST';
}

function saveGreatWallEntry() {
    var input = document.getElementById('great-wall-input');
    var currentUser = mw.config.get('wgUserName') || '';
    var ownEntry = currentUser && greatWallState.data.entries ? greatWallState.data.entries[currentUser] : null;
    var text = input ? String(input.value || '').trim() : '';
    var api;

    if (!currentUser) {
        window.location.href = '/index.php?title=특수:로그인&returnto=' + encodeURIComponent(mw.config.get('wgPageName') || '대문');
        return;
    }

    if (ownEntry && !greatWallState.selectedOwnEntry) {
        greatWallState.statusText = '';
        renderGreatWallBox();
        return;
    }

    if (!text) {
        greatWallState.statusText = 'EMPTY MARK';
        renderGreatWallBox();
        return;
    }

    if (text.length > 140) {
        text = text.slice(0, 140);
    }

    greatWallState.saving = true;
    greatWallState.statusText = 'SAVING';
    renderGreatWallBox();

    fetchGreatWallData().then(function(data) {
        data = normalizeGreatWallData(data);
        data.entries[currentUser] = {
            user: currentUser,
            text: text,
            timestamp: new Date().toISOString()
        };

        api = new mw.Api();
        return api.postWithToken('csrf', {
            action: 'edit',
            title: GREAT_WALL_DATA_TITLE,
            text: stringifyGreatWallData(data),
            summary: 'Update The Great Wall entry',
            format: 'json'
        }).then(function() {
            greatWallState.data = data;
            greatWallState.loaded = true;
            greatWallState.selectedOwnEntry = false;
            greatWallState.statusText = 'MARK UPDATED';
            if (input) input.value = '';
        });
    }).then(function() {
        greatWallState.saving = false;
        renderGreatWallBox();
    }, function(err) {
        console.error('The Great Wall save failed:', err);
        greatWallState.saving = false;
        greatWallState.statusText = 'SAVE FAILED';
        renderGreatWallBox();
    });
}


function deleteGreatWallEntry() {
    var input = document.getElementById('great-wall-input');
    var currentUser = mw.config.get('wgUserName') || '';
    var ownEntry = currentUser && greatWallState.data.entries ? greatWallState.data.entries[currentUser] : null;
    var api;

    if (!currentUser) {
        window.location.href = '/index.php?title=특수:로그인&returnto=' + encodeURIComponent(mw.config.get('wgPageName') || '대문');
        return;
    }

    if (!ownEntry) {
        greatWallState.statusText = 'NO MARK TO DELETE';
        renderGreatWallBox();
        return;
    }

    greatWallState.saving = true;
    greatWallState.statusText = 'DELETING';
    renderGreatWallBox();

    fetchGreatWallData().then(function(data) {
        data = normalizeGreatWallData(data);
        if (data.entries && data.entries[currentUser]) {
            delete data.entries[currentUser];
        }

        api = new mw.Api();
        return api.postWithToken('csrf', {
            action: 'edit',
            title: GREAT_WALL_DATA_TITLE,
            text: stringifyGreatWallData(data),
            summary: 'Delete The Great Wall entry',
            format: 'json'
        }).then(function() {
            greatWallState.data = data;
            greatWallState.loaded = true;
            greatWallState.selectedOwnEntry = false;
            greatWallState.statusText = 'MARK DELETED';
            if (input) input.value = '';
        });
    }).then(function() {
        greatWallState.saving = false;
        renderGreatWallBox();
    }, function(err) {
        console.error('The Great Wall delete failed:', err);
        greatWallState.saving = false;
        greatWallState.statusText = 'DELETE FAILED';
        renderGreatWallBox();
    });
}

function initGreatWallBoxWhenReady() {
    if (!document.getElementById('great-wall-sidebar')) return;

    if (mw.Api) {
        initGreatWallBox();
        return;
    }

    if (mw.loader && mw.loader.using) {
        mw.loader.using(['mediawiki.api']).then(function() {
            initGreatWallBox();
        });
    }
}

function initGreatWallBox() {
    var box = document.getElementById('great-wall-sidebar');
    var input = document.getElementById('great-wall-input');
    var submit = document.getElementById('great-wall-submit');
    var deleteButton = document.getElementById('great-wall-delete');

    if (!box || box.getAttribute('data-great-wall-ready') === '1') return;

    if (!mw.Api) {
        initGreatWallBoxWhenReady();
        return;
    }

    box.setAttribute('data-great-wall-ready', '1');

    box.addEventListener('click', function(e) {
        var ownButton = e.target.closest ? e.target.closest('[data-great-wall-own-entry="1"]') : null;
        var currentUser = mw.config.get('wgUserName') || '';
        var ownEntry = currentUser && greatWallState.data.entries ? greatWallState.data.entries[currentUser] : null;

        if (!ownButton || !ownEntry) return;

        greatWallState.selectedOwnEntry = true;
        greatWallState.statusText = '';
        renderGreatWallBox();

        if (input) {
            input.focus();
            input.setSelectionRange(input.value.length, input.value.length);
        }
    });

    document.addEventListener('click', function(e) {
        var target = e.target;
        var keepSelection;

        if (!greatWallState.selectedOwnEntry || !target || !target.closest) return;

        keepSelection = target.closest('[data-great-wall-own-entry="1"], .great-wall-editor, .great-wall-compose-sector');

        if (keepSelection) return;

        greatWallState.selectedOwnEntry = false;
        greatWallState.statusText = '';
        if (input) input.value = '';
        renderGreatWallBox();
    });

    if (submit) {
        submit.addEventListener('click', function(e) {
            e.preventDefault();
            if (!mw.config.get('wgUserName')) {
                window.location.href = '/index.php?title=특수:로그인&returnto=' + encodeURIComponent(mw.config.get('wgPageName') || '대문');
                return;
            }
            saveGreatWallEntry();
        });
    }

    if (deleteButton) {
        deleteButton.addEventListener('click', function(e) {
            e.preventDefault();
            deleteGreatWallEntry();
        });
    }

    if (input) {
        input.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                saveGreatWallEntry();
            }
        });

        input.addEventListener('input', function() {
            if (input.value.length > 140) {
                input.value = input.value.slice(0, 140);
            }
        });
    }

    greatWallState.loading = true;
    greatWallState.statusText = 'SYNCING WALL';
    renderGreatWallBox();

    fetchGreatWallData().then(function(data) {
        greatWallState.data = normalizeGreatWallData(data);
        greatWallState.loaded = true;
        greatWallState.loading = false;
        greatWallState.selectedOwnEntry = false;
        greatWallState.statusText = '';
        renderGreatWallBox();
    });
}

function buildGreatWallBox() {
    return '' +
        '<div id="great-wall-sidebar" class="clbi-right-box great-wall-sidebar">' +
            '<div class="clbi-right-title great-wall-title">' +
                '<span id="clbi-title-great-wall">The Great Wall</span>' +
            '</div>' +
            '<div class="clbi-right-content great-wall-content">' +
                '<div id="great-wall-list" class="great-wall-list"><div class="great-wall-empty">SYNCING WALL</div></div>' +
            '</div>' +
            '<div class="great-wall-compose-sector" aria-label="The Great Wall editor">' +
                '<div class="great-wall-editor">' +
                    '<input id="great-wall-input" class="great-wall-input" type="text" maxlength="140" autocomplete="off" placeholder="담벼락">' +
                    '<button id="great-wall-submit" class="great-wall-submit" type="button">POST</button>' +
                    '<button id="great-wall-delete" class="great-wall-delete" type="button" disabled>DEL</button>' +
                '</div>' +
                '<div id="great-wall-status" class="great-wall-status">SYNCING WALL</div>' +
            '</div>' +
        '</div>';
}

function removeMainPortalGuestbookPreview() {
    var portal = document.querySelector('.main-portal');
    var guestbook = portal ? portal.querySelector('.guestbook-device') : null;
    var sideScreen;
    var grid;

    if (!portal || !guestbook) return;

    sideScreen = guestbook.closest ? guestbook.closest('.side-screen') : null;
    grid = sideScreen && sideScreen.closest ? sideScreen.closest('.console-grid') : null;

    if (guestbook.parentNode) {
        guestbook.parentNode.removeChild(guestbook);
    }

    if (sideScreen && !(sideScreen.textContent || '').trim() && !sideScreen.querySelector('img,svg,video,canvas,form,input,button,a')) {
        if (sideScreen.parentNode) {
            sideScreen.parentNode.removeChild(sideScreen);
        }

        if (grid) {
            grid.style.gridTemplateColumns = 'minmax(0,1fr)';
        }
    }

    portal.classList.add('is-great-wall-relocated');
}

function buildSiteInformationBox() {
    return '' +
        '<div class="clbi-right-box site-info-sidebar">' +
            '<div class="clbi-right-title site-info-title">' +
                '<span>정보</span>' +
            '</div>' +
            '<div class="clbi-right-content site-info-content">' +
                '<div class="policy-list">' +
                    '<div class="policy-row"><a href="/index.php/개인정보처리방침" class="site-info-policy-button"><span class="site-info-policy-title">개인정보처리방침</span><span class="site-info-policy-arrow" aria-hidden="true">›</span></a></div>' +
                    '<div class="policy-row"><a href="/index.php/면책_조항" class="site-info-policy-button"><span class="site-info-policy-title">면책 조항</span><span class="site-info-policy-arrow" aria-hidden="true">›</span></a></div>' +
                    '<div class="policy-row"><a href="/index.php/라이선스" class="site-info-policy-button"><span class="site-info-policy-title">라이선스</span><span class="site-info-policy-arrow" aria-hidden="true">›</span></a></div>' +
                    '<div class="policy-row"><a href="/index.php/크레딧" class="site-info-policy-button"><span class="site-info-policy-title">크레딧</span><span class="site-info-policy-arrow" aria-hidden="true">›</span></a></div>' +
                '</div>' +
                '<div class="social-strip">' +
                    '<span class="social-icon"><a href="https://discord.gg/ctaeJ9d3Q5" target="_blank" rel="noopener noreferrer">DC</a></span>' +
                    '<span class="social-icon"><a href="https://www.youtube.com/@nxdsxn" target="_blank" rel="noopener noreferrer">YT</a></span>' +
                    '<span class="social-icon"><a href="https://x.com/nxd_sxn" target="_blank" rel="noopener noreferrer">X</a></span>' +
                    '<span class="social-icon"><a href="/index.php/프로젝트:소개">WIP:</a></span>' +
                '</div>' +
            '</div>' +
        '</div>';
}


// 초기화 함수
function initSidebars() {
    var header = $('.liberty-content-header');
    var content = $('.liberty-content');

    if (header.length && content.length) {
        header.prependTo(content);
    }

    if ($('#clbi-right-sidebar').length === 0) {
        var username = mw.config.get('wgUserName');
        var isLoggedIn = username !== null;
        var avatarSrc = isLoggedIn
            ? '/index.php?title=특수:Redirect/file/Pfp-' + username + '.png'
            : '/index.php?title=특수:Redirect/file/Pfp-default.png';

        var userBox;

        if (isLoggedIn) {
            userBox =
                '<div class="clbi-right-box profile-card-box">' +
                    '<div id="clbi-user-avatar-wrap" class="profile-identity-panel">' +
                        '<div class="profile-avatar-stage">' +
                            '<img id="clbi-user-avatar" src="' + avatarSrc + '" onerror="this.onerror=null;this.src=\'/index.php?title=특수:Redirect/file/Pfp-default.png\';">' +
                        '</div>' +
                        '<div id="clbi-user-name-row" class="profile-name-row">' +
                            '<a href="/index.php/사용자:' + username + '" id="clbi-user-name">' + username + '</a>' +
                        '</div>' +
                    '</div>' +
                    '<div class="clbi-right-content profile-action-box">' +
                        '<div class="profile-quick-actions" aria-label="프로필 빠른 메뉴">' +
                            '<button type="button" class="profile-quick-btn" id="profile-quick-inventory" aria-label="인벤토리"><span class="profile-quick-icon" aria-hidden="true">' + CLBI_SVG_PACKAGE + '</span><span class="profile-quick-tip" aria-hidden="true">인벤토리</span></button>' +
                            '<button type="button" class="profile-quick-btn" id="profile-quick-achievements" aria-label="업적"><span class="profile-quick-icon" aria-hidden="true">' + CLBI_SVG_TROPHY + '</span><span class="profile-quick-tip" aria-hidden="true">업적</span></button>' +
                            '<button type="button" class="profile-quick-btn" id="profile-quick-notifications" aria-label="알림"><span id="profile-quick-notification-icon" class="profile-quick-icon" aria-hidden="true">' + CLBI_SVG_BELL + '</span><span class="profile-quick-tip" aria-hidden="true">알림</span></button>' +
                        '</div>' +
                        '<a href="/index.php/특수:기여/' + username + '" class="clbi-user-btn" id="clbi-btn-contribution"><span class="profile-action-icon" aria-hidden="true">' + CLBI_SVG_SCAN_TEXT + '</span><span class="profile-action-label">기여</span><i class="hn hn-angle-right-solid profile-action-arrow" aria-hidden="true"></i></a>' +
                        '<a href="/index.php/특수:주시문서목록" class="clbi-user-btn" id="clbi-btn-watchlist"><span class="profile-action-icon" aria-hidden="true">' + CLBI_SVG_SCAN_EYE + '</span><span class="profile-action-label">주시문서 목록</span><i class="hn hn-angle-right-solid profile-action-arrow" aria-hidden="true"></i></a>' +
                        '<a href="/index.php/특수:설정" class="clbi-user-btn" id="clbi-btn-preferences"><span class="profile-action-icon" aria-hidden="true">' + CLBI_SVG_SETTINGS + '</span><span class="profile-action-label">설정</span><i class="hn hn-angle-right-solid profile-action-arrow" aria-hidden="true"></i></a>' +
                        '<a href="/index.php?title=특수:로그아웃&returnto=대문" class="clbi-user-btn clbi-user-btn-logout" id="clbi-btn-logout"><span class="profile-action-icon" aria-hidden="true">' + CLBI_SVG_POWER + '</span><span class="profile-action-label">로그아웃</span><i class="hn hn-angle-right-solid profile-action-arrow" aria-hidden="true"></i></a>' +
                    '</div>' +
                '</div>';
        } else {
            userBox =
                '<div class="clbi-right-box profile-card-box">' +
                    '<div id="clbi-user-avatar-wrap" class="profile-identity-panel">' +
                        '<div class="profile-avatar-stage">' +
                            '<img id="clbi-user-avatar" src="/index.php?title=특수:Redirect/file/Pfp-default.png">' +
                        '</div>' +
                        '<div id="clbi-user-name-row" class="profile-name-row profile-name-row-guest">' +
                            '<span id="clbi-user-name">Guest</span>' +
                        '</div>' +
                    '</div>' +
                    '<div class="clbi-right-content profile-action-box">' +
                        '<a href="/index.php?title=특수:로그인&returnto=대문" class="clbi-user-btn" id="clbi-btn-login"><span class="profile-action-icon" aria-hidden="true">' + CLBI_SVG_POWER + '</span><span class="profile-action-label">로그인</span><i class="hn hn-angle-right-solid profile-action-arrow" aria-hidden="true"></i></a>' +
                    '</div>' +
                '</div>';
        }
        var greatWallBox = '';
        var siteInformationBox = '';

        try {
            greatWallBox = buildGreatWallBox();
        } catch (err) {
            console.error('The Great Wall build failed:', err);
            greatWallBox = '';
        }

        try {
            siteInformationBox = buildSiteInformationBox();
        } catch (err) {
            console.error('Site information build failed:', err);
            siteInformationBox = '';
        }


        var sidebar = userBox + greatWallBox + siteInformationBox;

        $('.content-wrapper').append('<div id="clbi-right-sidebar">' + sidebar + '</div>');
        initGreatWallBoxWhenReady();
        removeMainPortalGuestbookPreview();
    }

    initGreatWallBoxWhenReady();
    removeMainPortalGuestbookPreview();


    if ($('#clbi-left-sidebar').length === 0) {
var leftBillboardBox = '';

        try {
            leftBillboardBox = buildRightBillboardBox();
        } catch (err) {
            console.error('Left billboard build failed:', err);
            leftBillboardBox = '';
        }

var leftSidebar =
    '<div id="clbi-left-sidebar">' +
        '<div class="clbi-left-box clbi-left-lang-box">' +
            '<div class="clbi-left-title">' +
                '<span id="clbi-title-left-language">언어</span>' +
            '</div>' +
            '<div class="clbi-left-content sidebar-lang-box">' +
                '<div id="clbi-sidebar-lang-selector" class="sidebar-lang-selector sidebar-lang-dial" tabindex="0" role="group" aria-label="언어 선택">' +
                    '<div id="clbi-sidebar-lang-dial-stage" class="sidebar-lang-dial-stage">' +
                        '<div id="clbi-sidebar-lang-fan" class="sidebar-lang-fan" aria-hidden="true"></div>' +
                        '<div id="clbi-sidebar-lang-selected-panel" class="sidebar-lang-status-panel sidebar-lang-status-left" aria-hidden="true">' +
                            '<span id="clbi-sidebar-lang-selected-value" class="sidebar-lang-status-value">한국어</span>' +
                        '</div>' +
                        '<div id="clbi-sidebar-lang-availability-panel" class="sidebar-lang-status-panel sidebar-lang-status-right is-current" aria-hidden="true">' +
                            '<span id="clbi-sidebar-lang-availability-value" class="sidebar-lang-status-value">CURRENT</span>' +
                        '</div>' +
                        '<button type="button" id="clbi-sidebar-lang-apply" class="sidebar-lang-apply" aria-label="언어 적용">' +
                            '<span class="sidebar-lang-apply-mark" aria-hidden="true">✓</span>' +
                        '</button>' +
                    '</div>' +
                '</div>' +
            '</div>' +
        '</div>' +
        '<div class="clbi-left-box clbi-left-news-box">' +
            '<div class="clbi-left-title">' +
                '<span id="clbi-title-left-news">뉴스</span>' +
            '</div>' +
            '<div class="clbi-left-content clbi-news-box">' +

                '<div class="news-feed-title" id="clbi-left-news-changelog-title">CHANGELOG</div>' +
                '<div class="news-left-changelog-feed">' +
                    '<a href="/index.php/체인지로그" class="news-post-item">' +
                        '<div class="news-post-title-wrap">' +
                            '<span class="news-post-title" id="clbi-left-news-changelog-main">체인지로그</span>' +
                        '</div>' +
                        '<span class="news-post-jump" aria-hidden="true">›</span>' +
                    '</a>' +
                '</div>' +

                '<div class="news-divider"></div>' +

                '<div class="news-feed-title" id="clbi-left-news-recent-title">RECENT CHANGES</div>' +
                '<div class="news-left-recent-feed" id="clbi-left-recent-list">불러오는 중...</div>' +

                '<a class="news-fill-image-slot" id="clbi-left-news-fill-image" href="/index.php/특수:최근바뀜" aria-label="최근 바뀜으로 이동">' +
                    '<div class="news-fill-image-frame">' +
                        '<span class="news-fill-image" style="--news-fill-image-url:url(\'/index.php?title=특수:Redirect/file/Side-news-fill-001.png\');" aria-hidden="true"></span><img class="news-fill-image-probe" src="/index.php?title=특수:Redirect/file/Side-news-fill-001.png" alt="" aria-hidden="true" onerror="this.onerror=null;this.closest(\'.news-fill-image-slot\').classList.add(\'is-empty\');this.remove();">' +
                    '</div>' +
                '</a>' +

            '</div>' +
        '</div>' +
        leftBillboardBox +
    '</div>';

        $('.content-wrapper').prepend(leftSidebar);

        renderSidebarLanguageBox();
        loadRecentChangesList('#clbi-left-recent-list', 10);
        scheduleAdaptiveLeftRecentItems();
        scheduleLeftBillboardAdaptive();
        scheduleClbiContentBottomGap();
        updateLeftSidebarNationsImage();
    }

    try {
        initRightBillboardCarousel();
    } catch (err) {
        console.error('Right billboard carousel failed:', err);
    }

    if (typeof window.normalizeClbiShellDomOrder === 'function') window.normalizeClbiShellDomOrder();
    applyMainPageStyle();
    initClbiCustomDocumentScrollbars();
    initCategoryNavIfAvailable(document);

    if (window.ProgressSystemWebUi && typeof window.ProgressSystemWebUi.boot === 'function') {
        window.ProgressSystemWebUi.boot('initSidebars');
    }

    $('#side-toc-box').remove();

    mw.loader.using(['mediawiki.api']).then(function() {
        setTimeout(function() {
            initNotifications();
            initProfile();
            moveTocToLeftSidebar();
        }, 300);

        setTimeout(moveTocToLeftSidebar, 800);
        setTimeout(moveTocToLeftSidebar, 1500);
    });
}

$(function() {
    loadLangScript(function() {
        setTimeout(function() {
            initSidebars();
        }, 100);
    });
});

$(document).on('click.profileQuickPlaceholder', '#profile-quick-inventory, #profile-quick-achievements', function(e) {
    e.preventDefault();
    e.stopPropagation();
});

function extractJsonArrayAfterMwConfigKey(text, key) {
    var needle = '"' + key + '"';
    var keyIndex = String(text || '').indexOf(needle);
    var start;
    var i;
    var depth = 0;
    var inString = false;
    var escaped = false;

    if (keyIndex === -1) return null;

    start = String(text || '').indexOf('[', keyIndex + needle.length);
    if (start === -1) return null;

    for (i = start; i < text.length; i += 1) {
        var ch = text.charAt(i);

        if (inString) {
            if (escaped) {
                escaped = false;
            } else if (ch === '\\') {
                escaped = true;
            } else if (ch === '"') {
                inString = false;
            }
            continue;
        }

        if (ch === '"') {
            inString = true;
            continue;
        }

        if (ch === '[') depth += 1;
        if (ch === ']') {
            depth -= 1;
            if (depth === 0) {
                try {
                    return JSON.parse(text.slice(start, i + 1));
                } catch (err) {
                    return null;
                }
            }
        }
    }

    return null;
}

function extractJsonStringAfterMwConfigKey(text, key) {
    var needle = '"' + key + '"';
    var keyIndex = String(text || '').indexOf(needle);
    var colon;
    var start;
    var i;
    var escaped = false;

    if (keyIndex === -1) return null;

    colon = text.indexOf(':', keyIndex + needle.length);
    if (colon === -1) return null;

    start = text.indexOf('"', colon + 1);
    if (start === -1) return null;

    for (i = start + 1; i < text.length; i += 1) {
        var ch = text.charAt(i);

        if (escaped) {
            escaped = false;
            continue;
        }

        if (ch === '\\') {
            escaped = true;
            continue;
        }

        if (ch === '"') {
            try {
                return JSON.parse(text.slice(start, i + 1));
            } catch (err) {
                return text.slice(start + 1, i);
            }
        }
    }

    return null;
}

function syncCatlinksConfigFromSpaDocument(doc) {
    var scripts = doc ? doc.querySelectorAll('script') : [];
    var categories = null;
    var hiddenCategories = null;
    var relevantPageName = null;
    var pageName = null;
    var i;
    var text;
    var value;

    for (i = 0; i < scripts.length; i += 1) {
        text = scripts[i].textContent || '';

        if (categories === null) {
            value = extractJsonArrayAfterMwConfigKey(text, 'wgCategories');
            if (Array.isArray(value)) categories = value;
        }

        if (hiddenCategories === null) {
            value = extractJsonArrayAfterMwConfigKey(text, 'wgHiddenCategories');
            if (Array.isArray(value)) hiddenCategories = value;
        }

        if (relevantPageName === null) {
            value = extractJsonStringAfterMwConfigKey(text, 'wgRelevantPageName');
            if (value !== null) relevantPageName = value;
        }

        if (pageName === null) {
            value = extractJsonStringAfterMwConfigKey(text, 'wgPageName');
            if (value !== null) pageName = value;
        }
    }

    mw.config.set('wgCategories', Array.isArray(categories) ? categories : []);
    mw.config.set('wgHiddenCategories', Array.isArray(hiddenCategories) ? hiddenCategories : []);

    if (relevantPageName !== null) {
        mw.config.set('wgRelevantPageName', relevantPageName);
    } else if (pageName !== null) {
        mw.config.set('wgRelevantPageName', pageName);
    }

    CLBI_CATLINKS_FETCH_TOKEN += 1;
}

// SPA 네비게이션
function shouldSkip(url) {
    return url.match(/action=edit|action=submit|action=history|action=delete|action=protect|action=purge|특수:로그인|특수:로그아웃|Special:UserLogin|Special:UserLogout|특수:사용자정보|특수:비밀번호바꾸기|uselang=/);
}

$(function() {
    if (window._spaInitialized) return;
    window._spaInitialized = true;

    function isInternal(url) {
        var a = document.createElement('a');
        a.href = url;
        return a.hostname === window.location.hostname;
    }

    function getCachedSpaPageHtml(url) {
        if (!window.EntryStore || typeof window.EntryStore.getTextSync !== 'function') return '';
        return window.EntryStore.getTextSync(url) || window.EntryStore.getTextSync(String(url || '').replace(/^https?:\/\/[^/]+/i, '')) || '';
    }

    function fetchSpaPageHtml(url) {
        var cached = getCachedSpaPageHtml(url);
        if (cached) return Promise.resolve(cached);
        return fetch(url, { credentials: 'same-origin', cache: 'force-cache' }).then(function(res) {
            return res.text();
        });
    }

    function prepareDetachedEntryContent(newContent) {
        /*
        Initial boot prepares entry artifacts; SPA is only allowed to consume them.
        This hook runs while the fetched page is still detached, before the user sees it.
        It must stay synchronous or already-resolved: if a subsystem cannot prepare from
        EntryStore immediately, it should leave the old fallback path in place instead of
        opening BootGate during SPA.
        */
        try {
            if (window.NationsPanel && typeof window.NationsPanel.prepareContentForEntry === 'function') {
                window.NationsPanel.prepareContentForEntry(newContent);
            }
        } catch (err) {
            console.warn('entry content preparation failed:', err);
        }
    }

    function loadPage(url) {
        invalidateProfileRender();

        return fetchSpaPageHtml(url)
            .then(function(html) {
                var parser = new DOMParser();
                var doc = parser.parseFromString(html, 'text/html');

                var scripts = doc.querySelectorAll('script');
                for (var i = 0; i < scripts.length; i++) {
                    var src = scripts[i].textContent;

                    if (src.indexOf('wgNamespaceNumber') !== -1) {
                        var match = src.match(/"wgNamespaceNumber":(-?\d+)/);
                        if (match) mw.config.set('wgNamespaceNumber', parseInt(match[1], 10));

                        var matchTitle = src.match(/"wgTitle":"([^"]+)"/);
                        if (matchTitle) mw.config.set('wgTitle', matchTitle[1]);

                        var matchPage = src.match(/"wgPageName":"([^"]+)"/);
                        if (matchPage) mw.config.set('wgPageName', matchPage[1]);

                        var matchArticle = src.match(/"wgArticleId":(\d+)/);
                        if (matchArticle) {
                            mw.config.set('wgArticleId', parseInt(matchArticle[1], 10));
                        } else {
                            mw.config.set('wgArticleId', 0);
                        }

                        var matchIsMainPage = src.match(/"wgIsMainPage":(true|false)/);
                        if (matchIsMainPage) {
                            mw.config.set('wgIsMainPage', matchIsMainPage[1] === 'true');
                        } else {
                            mw.config.set('wgIsMainPage', false);
                        }

                        var matchSpecial = src.match(/"wgCanonicalSpecialPageName":"([^"]+)"/);
                        if (matchSpecial) {
                            mw.config.set('wgCanonicalSpecialPageName', matchSpecial[1]);
                        } else {
                            mw.config.set('wgCanonicalSpecialPageName', false);
                        }
                        break;
                    }
                }

                syncCatlinksConfigFromSpaDocument(doc);

                var newContent = doc.querySelector('.liberty-content-main');
                var newTitle = doc.querySelector('.mw-page-title-main');
                var newHead = doc.querySelector('title');
                var newHeader = doc.querySelector('.liberty-content-header');

                if (newContent) {
                    prepareDetachedEntryContent(newContent);
                    prepareSpaCatlinksBeforeInsert(newContent);
                    $('#side-toc-box').remove();
                    $('.profile-card').remove();
                    $('.user-profile-portal').removeClass('user-profile-portal');
                    $('.liberty-content-main').html(newContent.innerHTML);
                    $('.profile-card').remove();
                    try {
                        if (window.Decorations && typeof window.Decorations.renderPrepared === 'function') window.Decorations.renderPrepared();
                        else if (window.CLBI_DECORATIONS && typeof window.CLBI_DECORATIONS.renderPrepared === 'function') window.CLBI_DECORATIONS.renderPrepared();
                    } catch (err) {}
                    $('body').removeClass('page-loading');
                }

                if (newTitle) {
                    $('.mw-page-title-main').html(newTitle.innerHTML);
                }

                if (newHead) {
                    document.title = newHead.textContent;
                }

                if (newHeader) {
                    $('.liberty-content-header').html(newHeader.innerHTML);
                }

                if (typeof window.normalizeClbiShellDomOrder === 'function') window.normalizeClbiShellDomOrder();
                window.scrollTo(0, 0);
                mw.hook('wikipage.content').fire($('.liberty-content-main'));
                applyMainPageStyle();
                initClbiCustomDocumentScrollbars();
                initCategoryNavIfAvailable(document);

                if (window.ProgressSystemWebUi && typeof window.ProgressSystemWebUi.handleSpaPageView === 'function') {
                    window.ProgressSystemWebUi.handleSpaPageView();
                } else if (window.ProgressSystemWebUi && typeof window.ProgressSystemWebUi.boot === 'function') {
                    window.ProgressSystemWebUi.boot('spa');
                }

                $('#side-toc-box').remove();
                setTimeout(moveTocToLeftSidebar, 100);
                setTimeout(moveTocToLeftSidebar, 500);
                setTimeout(moveTocToLeftSidebar, 1200);

                mw.loader.using(['mediawiki.api']).then(function() {
                    initProfile();
                    moveTocToLeftSidebar();
                });
            })
            .catch(function (err) {
                console.error('SPA page load failed:', err);
                $('body').removeClass('page-loading');
            });
    }

// 목차 링크는 전용 처리
$(document).on('click', '#side-toc-box a, #toc a, .toc a', function(e) {
    var href = $(this).attr('href');
    if (!href || href.charAt(0) !== '#') return;

    var rawId = href.slice(1);
    if (!rawId) return;

    var decodedId = rawId;

    try {
        decodedId = decodeURIComponent(rawId);
    } catch (err) {
        decodedId = rawId;
    }

    var target = document.getElementById(decodedId);

    if (!target && window.CSS && CSS.escape) {
        target = document.querySelector('#' + CSS.escape(decodedId));
    }

    if (!target) return;

    e.preventDefault();
    e.stopPropagation();

    var scrollTarget = target.closest('h2, h3') || target;

    scrollTarget.scrollIntoView({
        behavior: 'auto',
        block: 'start'
    });

    history.replaceState(null, '', '#' + rawId);
});

    /* 길라잡이는 문서 링크가 아니라 대문 본문 화면 탭이다. */
    $(document).on('click', '.portal-guide-anchor[data-category-key="guide"]', function(e) {
        if (e.which && e.which !== 1) return;
        if (e.button && e.button !== 0) return;
        if (e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) return;

        if (window.BottomGuideNav && typeof window.BottomGuideNav.toggle === 'function') {
            e.preventDefault();
            e.stopImmediatePropagation();
            window.BottomGuideNav.toggle();
        }
    });

    $(document).on('click', 'a', function(e) {
        // 휠 클릭, 새 탭 열기, 보조키 이동은 브라우저 기본 동작을 유지한다.
        if (e.which && e.which !== 1) return;
        if (e.button && e.button !== 0) return;
        if (e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) return;

        /* 길라잡이 화면 탭은 위 전용 처리 외에는 SPA 문서 이동 대상으로 삼지 않는다. */
        if ($(this).is('.portal-guide-anchor[data-category-key="guide"]')) return;

        var href = $(this).attr('href');
        if (!href) return;

        // 목차 링크는 별도 핸들러에서 처리
        if ($(this).closest('#side-toc-box, #toc, .toc').length) return;

        // 단순 해시 링크는 SPA 가로채기 제외
        if (href.startsWith('#')) return;

        var link = document.createElement('a');
        link.href = href;

        var samePath = decodeURIComponent(link.pathname) === decodeURIComponent(window.location.pathname);
        var sameSearch = (link.search || '') === (window.location.search || '');

        if (link.hash && samePath && sameSearch) return;

        var currentBase = window.location.href.split('#')[0];
        var targetBase = link.href.split('#')[0];

        if (link.hash && currentBase === targetBase) return;

        if (!isInternal(href)) return;
        if (shouldSkip(href)) return;

        e.preventDefault();
        playStaticSound();
        /*
        SPA must remain a consumer phase.  If the target page HTML was prepared by
        the first-load boot pack, do not show the legacy page-loading veil.  The
        route will consume cached HTML and detached entry artifacts before insertion.
        */
        if (getCachedSpaPageHtml(href)) {
            $('body').removeClass('page-loading');
        } else {
            $('body').addClass('page-loading');
        }
        history.pushState(null, '', href);
        loadPage(href);
    });

    window.addEventListener('popstate', function() {
        loadPage(window.location.href);
    });
});



/* ========== CLBI Custom Document Scrollbar ========== */
function isGeneralDocumentView() {
    var body = document.body;
    if (!body) return false;

    return body.classList.contains('action-view') &&
        !body.classList.contains('clbi-main-page') &&
        !body.classList.contains('clbi-system-doc-page') &&
        !body.classList.contains('backend-system-page') &&
        !body.classList.contains('user-profile-page') &&
        !body.classList.contains('user-profile-settings-page');
}

function getClbiDocumentScrollTargets() {
    if (!isGeneralDocumentView()) return [];

    return Array.prototype.slice.call(document.querySelectorAll(
        '.liberty-content-main > #mw-content-text .mw-parser-output, ' +
        '.liberty-content-main > .mw-body-content .mw-parser-output'
    )).filter(function (el, index, list) {
        return el && list.indexOf(el) === index;
    });
}

function getClbiOuterWellForScroll(scrollEl) {
    var main = scrollEl ? scrollEl.closest('.liberty-content-main') : null;
    var children;
    var i;
    var child;

    if (!main) return null;

    children = Array.prototype.slice.call(main.children || []);
    for (i = 0; i < children.length; i += 1) {
        child = children[i];
        if (
            child &&
            (child.id === 'mw-content-text' || child.classList.contains('mw-body-content')) &&
            child.contains(scrollEl)
        ) {
            return child;
        }
    }

    return scrollEl.parentElement || null;
}

function buildClbiCustomScrollbar(well, scrollEl) {
    var bar = well.querySelector(':scope > .clbi-custom-scrollbar');
    var up;
    var track;
    var thumb;
    var down;

    if (!bar) {
        bar = document.createElement('div');
        bar.className = 'clbi-custom-scrollbar';
        bar.setAttribute('aria-hidden', 'true');
        bar.innerHTML =
            '<div class="clbi-custom-scroll-arrow clbi-custom-scroll-arrow-up" data-scroll-arrow="up"></div>' +
            '<div class="clbi-custom-scroll-track"><div class="clbi-custom-scroll-thumb"></div></div>' +
            '<div class="clbi-custom-scroll-arrow clbi-custom-scroll-arrow-down" data-scroll-arrow="down"></div>';
        well.appendChild(bar);
    }

    bar.__clbiScrollTarget = scrollEl;
    up = bar.querySelector('.clbi-custom-scroll-arrow-up');
    track = bar.querySelector('.clbi-custom-scroll-track');
    thumb = bar.querySelector('.clbi-custom-scroll-thumb');
    down = bar.querySelector('.clbi-custom-scroll-arrow-down');

    if (up && !up.__clbiBound) {
        up.__clbiBound = true;
        up.addEventListener('mousedown', function (e) {
            e.preventDefault();
            e.stopPropagation();
            if (bar.__clbiScrollTarget) bar.__clbiScrollTarget.scrollTop -= 48;
            updateClbiCustomScrollbar(bar);
        });
    }

    if (down && !down.__clbiBound) {
        down.__clbiBound = true;
        down.addEventListener('mousedown', function (e) {
            e.preventDefault();
            e.stopPropagation();
            if (bar.__clbiScrollTarget) bar.__clbiScrollTarget.scrollTop += 48;
            updateClbiCustomScrollbar(bar);
        });
    }

    if (track && !track.__clbiBound) {
        track.__clbiBound = true;
        track.addEventListener('mousedown', function (e) {
            var rect;
            var thumbRect;
            var target;
            var direction;

            if (e.target === thumb) return;
            e.preventDefault();
            e.stopPropagation();

            target = bar.__clbiScrollTarget;
            if (!target) return;

            rect = track.getBoundingClientRect();
            thumbRect = thumb.getBoundingClientRect();
            direction = e.clientY < thumbRect.top ? -1 : 1;
            target.scrollTop += direction * Math.max(60, Math.floor(target.clientHeight * 0.82));
            updateClbiCustomScrollbar(bar);
        });
    }

    if (thumb && !thumb.__clbiBound) {
        thumb.__clbiBound = true;
        thumb.addEventListener('mousedown', function (e) {
            var target = bar.__clbiScrollTarget;
            var startY;
            var startScroll;
            var maxScroll;
            var maxThumbTop;
            var trackHeight;
            var thumbHeight;

            if (!target) return;

            e.preventDefault();
            e.stopPropagation();

            startY = e.clientY;
            startScroll = target.scrollTop;
            maxScroll = Math.max(1, target.scrollHeight - target.clientHeight);
            trackHeight = track ? track.clientHeight : 0;
            thumbHeight = thumb.offsetHeight || 0;
            maxThumbTop = Math.max(1, trackHeight - thumbHeight);

            bar.classList.add('is-dragging');

            function onMove(moveEvent) {
                var dy = moveEvent.clientY - startY;
                target.scrollTop = startScroll + (dy / maxThumbTop) * maxScroll;
                updateClbiCustomScrollbar(bar);
                moveEvent.preventDefault();
            }

            function onUp() {
                bar.classList.remove('is-dragging');
                document.removeEventListener('mousemove', onMove);
                document.removeEventListener('mouseup', onUp);
            }

            document.addEventListener('mousemove', onMove);
            document.addEventListener('mouseup', onUp);
        });
    }

    if (!scrollEl.__clbiCustomScrollbarBound) {
        scrollEl.__clbiCustomScrollbarBound = true;
        scrollEl.addEventListener('scroll', function () {
            if (scrollEl.__clbiCustomScrollbar) {
                updateClbiCustomScrollbar(scrollEl.__clbiCustomScrollbar);
            }
        }, { passive: true });
    }

    scrollEl.__clbiCustomScrollbar = bar;
    updateClbiCustomScrollbar(bar);

    return bar;
}

function updateClbiCustomScrollbar(bar) {
    var scrollEl = bar && bar.__clbiScrollTarget;
    var track = bar ? bar.querySelector('.clbi-custom-scroll-track') : null;
    var thumb = bar ? bar.querySelector('.clbi-custom-scroll-thumb') : null;
    var maxScroll;
    var trackHeight;
    var thumbHeight;
    var maxTop;
    var top;

    if (!bar || !scrollEl || !track || !thumb) return;

    maxScroll = scrollEl.scrollHeight - scrollEl.clientHeight;
    if (maxScroll <= 1) {
        bar.classList.add('is-hidden');
        return;
    }

    bar.classList.remove('is-hidden');

    trackHeight = Math.max(1, track.clientHeight || 1);
    thumbHeight = Math.max(12, Math.floor((scrollEl.clientHeight / Math.max(scrollEl.scrollHeight, 1)) * trackHeight));
    thumbHeight = Math.min(trackHeight, thumbHeight);
    maxTop = Math.max(0, trackHeight - thumbHeight);
    top = maxScroll > 0 ? Math.round((scrollEl.scrollTop / maxScroll) * maxTop) : 0;

    thumb.style.height = thumbHeight + 'px';
    thumb.style.transform = 'translateY(' + top + 'px)';
}

function initClbiCustomDocumentScrollbars() {
    var existing = Array.prototype.slice.call(document.querySelectorAll('.clbi-custom-scrollbar'));
    var targets = getClbiDocumentScrollTargets();
    var liveBars = [];

    if (!targets.length) {
        existing.forEach(function (bar) { bar.remove(); });
        return;
    }

    targets.forEach(function (scrollEl) {
        var well = getClbiOuterWellForScroll(scrollEl);
        var bar;

        if (!well) return;
        bar = buildClbiCustomScrollbar(well, scrollEl);
        liveBars.push(bar);
    });

    existing.forEach(function (bar) {
        if (liveBars.indexOf(bar) === -1) bar.remove();
    });

    window.requestAnimationFrame(function () {
        liveBars.forEach(updateClbiCustomScrollbar);
    });

    setTimeout(function () {
        liveBars.forEach(updateClbiCustomScrollbar);
    }, 120);
}

if (!window.__clbiCustomScrollbarResizeBound) {
    window.__clbiCustomScrollbarResizeBound = true;
    window.addEventListener('resize', function () {
        setTimeout(initClbiCustomDocumentScrollbars, 60);
    });
}


// 시간 계산 함수
function timeAgo(timestamp) {
    var now = new Date();
    var date = new Date(timestamp);
    var diff = Math.floor((now - date) / 1000);

    if (diff < 60) return diff + '초 전';
    if (diff < 3600) return Math.floor(diff / 60) + '분 전';
    if (diff < 86400) return Math.floor(diff / 3600) + '시간 전';
    return Math.floor(diff / 86400) + '일 전';
}

// 펼접 토글
// 펼접 토글
function getFoldTexts() {
    var lang = getCurrentLang();
    return (window.LANG && window.LANG[lang])
        ? window.LANG[lang]
        : (window.LANG ? window.LANG.ko : { expand: '펼치기', collapse: '접기' });
}

function refreshOpenAncestors($start) {
    $start.parents('[id^="collapsible"]').each(function () {
        var $parent = $(this);
        if (!$parent.hasClass('folding-open')) return;

        // 이미 fully open 상태면 굳이 다시 잠그지 않음
        if ($parent.data('fold-state') === 'open') {
            return;
        }

        $parent.css('max-height', this.scrollHeight + 'px');
    });
}

function bindInnerResizeUpdates($target) {
    // 이미지 늦게 로드될 때 높이 갱신
    $target.find('img').off('.foldimg').on('load.foldimg', function () {
        if ($target.hasClass('folding-open')) {
            if ($target.data('fold-state') !== 'open') {
                $target.css('max-height', $target[0].scrollHeight + 'px');
            }
            refreshOpenAncestors($target);
        }
    });
}

function openFold($target, $btn) {
    var t = getFoldTexts();

    $target.data('fold-state', 'opening');
    $target.addClass('folding-open');

    // 열린 뒤 자연 확장 가능하게 만들기 위해 먼저 px로 열기
    $target.css('max-height', '0px');
    $target[0].offsetHeight;
    $target.css('max-height', $target[0].scrollHeight + 'px');

    $btn.text(t.collapse);

    bindInnerResizeUpdates($target);

    // 바깥 펼접 즉시 갱신
    refreshOpenAncestors($target);

    // 전환 끝나면 none으로 풀어서 중첩 펼접/동적 내용 증가를 자연스럽게 허용
    $target.off('transitionend.foldopen').on('transitionend.foldopen', function (e) {
        if (e.target !== this) return;
        if (!$target.hasClass('folding-open')) return;

        $target.css('max-height', 'none');
        $target.data('fold-state', 'open');

        refreshOpenAncestors($target);
    });

    // 늦게 렌더되는 콘텐츠 대응
    requestAnimationFrame(function () {
        if ($target.hasClass('folding-open') && $target.data('fold-state') !== 'open') {
            $target.css('max-height', $target[0].scrollHeight + 'px');
            refreshOpenAncestors($target);
        }
    });

    setTimeout(function () {
        if ($target.hasClass('folding-open') && $target.data('fold-state') !== 'open') {
            $target.css('max-height', $target[0].scrollHeight + 'px');
            refreshOpenAncestors($target);
        }
    }, 80);

    setTimeout(function () {
        if ($target.hasClass('folding-open') && $target.data('fold-state') !== 'open') {
            $target.css('max-height', $target[0].scrollHeight + 'px');
            refreshOpenAncestors($target);
        }
    }, 220);
}

function closeFold($target, $btn) {
    var t = getFoldTexts();

    // none 상태에서 닫으면 transition이 안 되므로 실제 높이로 고정
    if ($target.css('max-height') === 'none' || $target.data('fold-state') === 'open') {
        $target.css('max-height', $target[0].scrollHeight + 'px');
    } else {
        $target.css('max-height', $target[0].scrollHeight + 'px');
    }

    $target.data('fold-state', 'closing');
    $target[0].offsetHeight;
    $target.css('max-height', '0px');
    $target.removeClass('folding-open');

    $btn.text(t.expand);

    refreshOpenAncestors($target);

    setTimeout(function () {
        refreshOpenAncestors($target);
        $target.data('fold-state', 'closed');
    }, 250);
}

$(function () {
    $(document)
        .off('click.clbiToggle')
        .on('click.clbiToggle', '.toggleBtn', function () {
            var $btn = $(this);
            var targetId = $btn.data('target');
            var $target = $('#' + targetId);
            if (!$target.length) return;

            var scrollY = window.scrollY;

            if ($target.hasClass('folding-open')) {
                closeFold($target, $btn);
            } else {
                openFold($target, $btn);
            }

            window.scrollTo(0, scrollY);
        });
});

// ========== 프로필 시스템 ==========
function initProfile() {
    $('.profile-card').remove();
    $('.user-profile-portal').removeClass('user-profile-portal');

    var token = ++PROFILE_RENDER_TOKEN;
    var ns = mw.config.get('wgNamespaceNumber');
    var title = mw.config.get('wgTitle');
    var specialPage = mw.config.get('wgCanonicalSpecialPageName');
    var isProfileSettings = specialPage === '사용자정보';

    $('body').toggleClass('user-profile-page', ns === 2);
    $('body').toggleClass('user-profile-settings-page', isProfileSettings);

    if (ns === 2) {
        var profileUser = title.split('/')[0];
        renderProfile(profileUser, token);
    }

    if (isProfileSettings) {
        initUserProfilePage();
    }
}

function renderProfile(username, token) {
    var api = new mw.Api();
    api.get({
        action: 'query',
        list: 'users',
        ususers: username,
        usprop: 'editcount'
    }).then(function(data) {
        if (token !== PROFILE_RENDER_TOKEN) return;
        if (mw.config.get('wgNamespaceNumber') !== 2) return;

        var currentTitle = String(mw.config.get('wgTitle') || '').split('/')[0];
        if (currentTitle !== username) return;

        var user = data.query.users[0];
        var contentEl = document.getElementById('mw-content-text');
        if (!contentEl) return;

        var pageContent = contentEl.querySelector('.mw-parser-output') || contentEl;
        injectProfileCard(username, user, pageContent);
    });
}

function injectProfileCard(username, userData, container) {
    var isOwnPage = mw.config.get('wgUserName') === username;
    var editCount = (userData && userData.editcount) ? userData.editcount : 0;

    function escapeHtml(value) {
        return String(value == null ? '' : value)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    container.classList.add('user-profile-portal');

    var safeUsername = escapeHtml(username);
    var avatarSrc = '/index.php?title=특수:Redirect/file/Pfp-' + encodeURIComponent(username) + '.png&width=220';
    var fallbackSrc = '/index.php?title=특수:Redirect/file/Pfp-default.png&width=220';
    var editBtn = isOwnPage
        ? '<a href="/index.php/특수:사용자정보" class="profile-edit-btn"><span class="profile-edit-label">프로필 수정</span><span class="profile-edit-arrow">›</span></a>'
        : '';

    var progressHtml = isOwnPage
        ? '<div class="profile-page-progress is-syncing" data-profile-progress>' +
            '<div class="profile-section-title">LEVEL RECORD</div>' +
            '<div class="profile-page-progress-body">' +
                '<div class="profile-page-progress-row">' +
                    '<span class="profile-page-level">SYNC</span>' +
                    '<span class="profile-page-total-xp">— XP</span>' +
                '</div>' +
                '<div class="profile-page-xp-bar" aria-hidden="true"><div class="profile-page-xp-fill"></div></div>' +
                '<div class="profile-page-progress-sub">SYNCING</div>' +
                '<div class="profile-page-progress-meta">TODAY — · DISCOVERED —</div>' +
            '</div>' +
        '</div>'
        : '';

    var card = document.createElement('div');
    card.className = 'profile-card profile-page-console';
    card.innerHTML =
        '<div class="profile-card-titlebar">' +
            '<span>USER PROFILE</span>' +
            '<span>OFFICIAL ARCHIVE</span>' +
        '</div>' +
        '<div class="profile-card-body">' +
            '<div class="profile-identity-row">' +
                '<div class="profile-avatar-bay">' +
                    '<img src="' + avatarSrc + '" onerror="this.onerror=null;this.src=\'' + fallbackSrc + '\';" alt="' + safeUsername + '">' +
                '</div>' +
                '<div class="profile-info-panel">' +
                    '<div class="profile-nameplate">' +
                        '<h2 class="profile-username">' + safeUsername + '</h2>' +
                        editBtn +
                    '</div>' +
                    '<div class="profile-name" data-field="name"></div>' +
                    '<div class="profile-role" data-field="role"></div>' +
                    '<div class="profile-discord" data-field="discord"></div>' +
                '</div>' +
            '</div>' +
            '<div class="profile-lower-grid">' +
                '<div class="profile-bio-panel">' +
                    '<div class="profile-section-title">BIOGRAPHY</div>' +
                    '<div class="profile-bio" data-field="bio"></div>' +
                '</div>' +
                '<div class="profile-stats-panel">' +
                    '<div class="profile-section-title">RECORD</div>' +
                    '<div class="profile-stats">' +
                        progressHtml +
                        '<div class="profile-stat-grid">' +
                            '<div class="profile-stat">' +
                                '<span class="clbi-stat-value">' + editCount + '</span>' +
                                '<span class="clbi-stat-label">수정 횟수</span>' +
                            '</div>' +
                            '<div class="profile-stat" data-contrib-pages-stat>' +
                                '<span class="clbi-stat-value" data-contrib-pages-value>SYNC</span>' +
                                '<span class="clbi-stat-label">기여 문서</span>' +
                            '</div>' +
                        '</div>' +
                        '<div class="profile-info-grid">' +
                            '<div class="profile-info-stat">' +
                                '<span class="profile-info-label">TIME</span>' +
                                '<span class="profile-info-value" data-profile-time>UTC --:--</span>' +
                            '</div>' +
                            '<div class="profile-info-stat">' +
                                '<span class="profile-info-label">LANGUAGE</span>' +
                                '<span class="profile-info-value" data-profile-language>—</span>' +
                            '</div>' +
                        '</div>' +
                    '</div>' +
                '</div>' +
            '</div>' +
        '</div>';

    $('.profile-card').remove();
    container.insertBefore(card, container.firstChild);
    loadProfileFields(username, card);
    loadProfileContributionPages(username, card);
    updateProfilePageEnvironment(card, null);

    if (isOwnPage) {
        loadProfileProgressForUserPage(card);
    }
}

function getProfileLanguageLabel() {
    var lang = getCurrentLang();
    return SIDEBAR_LANGUAGE_LABELS[lang] || (lang ? lang.toUpperCase() : '—');
}

function updateProfilePageEnvironment(card, summary) {
    if (!card) return;

    var timezone = summary && summary.timezone ? summary.timezone : 'UTC';
    var timeEl = card.querySelector('[data-profile-time]');
    var langEl = card.querySelector('[data-profile-language]');

    if (timeEl) {
        try {
            timeEl.textContent = timezone + ' ' + new Intl.DateTimeFormat('ko-KR', {
                hour: '2-digit',
                minute: '2-digit',
                hour12: false,
                timeZone: timezone
            }).format(new Date());
        } catch (err) {
            timeEl.textContent = 'UTC ' + new Intl.DateTimeFormat('ko-KR', {
                hour: '2-digit',
                minute: '2-digit',
                hour12: false,
                timeZone: 'UTC'
            }).format(new Date());
        }
    }

    if (langEl) {
        langEl.textContent = getProfileLanguageLabel();
    }
}

function loadProfileContributionPages(username, card) {
    if (!username || !card) return;
    if (!mw.loader || typeof mw.loader.using !== 'function') return;

    var valueEl = card.querySelector('[data-contrib-pages-value]');
    if (valueEl) valueEl.textContent = 'SYNC';

    mw.loader.using(['mediawiki.api']).then(function () {
        var api = new mw.Api();
        var pages = Object.create(null);
        var cont = {};
        var guard = 0;

        function requestNext() {
            guard++;

            var params = Object.assign({
                action: 'query',
                list: 'usercontribs',
                ucuser: username,
                ucnamespace: 0,
                ucprop: 'title',
                uclimit: 'max',
                format: 'json',
                formatversion: 2
            }, cont);

            return api.get(params).then(function (data) {
                var rows = data && data.query && data.query.usercontribs ? data.query.usercontribs : [];

                rows.forEach(function (row) {
                    if (row && row.title) pages[row.title] = true;
                });

                if (data && data.continue && data.continue.uccontinue && guard < 40) {
                    cont = data.continue;
                    return requestNext();
                }

                if (valueEl) valueEl.textContent = Object.keys(pages).length;
            });
        }

        requestNext().fail(function () {
            if (valueEl) valueEl.textContent = '—';
        });
    });
}

function loadProfileProgressForUserPage(card) {
    if (!mw.config.get('wgUserName')) return;
    if (!mw.loader || typeof mw.loader.using !== 'function') return;

    mw.loader.using(['mediawiki.api']).then(function () {
        var api = new mw.Api();
        api.get({
            action: 'progress_summary',
            format: 'json',
            formatversion: 2
        }).then(function (data) {
            var payload = data && data.progress_summary;
            if (!payload || !payload.available || !payload.summary) return;
            updateUserPageProgress(card, payload.summary);
            updateProfilePageEnvironment(card, payload.summary);
        });
    });
}

function updateUserPageProgress(card, summary) {
    var panel = card.querySelector('[data-profile-progress]');
    if (!panel || !summary) return;

    var level = summary.level || 1;
    var totalXp = summary.totalXp || 0;
    var xpIntoLevel = summary.xpIntoLevel || 0;
    var xpForNext = summary.xpForNextLevel || 1;
    var percent = Math.max(0, Math.min(100, summary.progressPercent || 0));
    var isMaxLevel = !!summary.isMaxLevel;
    var dailyXp = summary.dailyXp || 0;
    var discoveries = summary.discoveryCount || 0;

    panel.classList.remove('is-syncing');
    panel.classList.toggle('is-max-level', isMaxLevel);

    var levelEl = panel.querySelector('.profile-page-level');
    var totalEl = panel.querySelector('.profile-page-total-xp');
    var fillEl = panel.querySelector('.profile-page-xp-fill');
    var subEl = panel.querySelector('.profile-page-progress-sub');
    var metaEl = panel.querySelector('.profile-page-progress-meta');

    if (levelEl) levelEl.textContent = (isMaxLevel ? 'MAX ' : 'LVL ') + level;
    if (totalEl) totalEl.textContent = totalXp + ' XP';
    if (fillEl) fillEl.style.width = percent + '%';
    if (subEl) subEl.textContent = isMaxLevel ? 'MAX LEVEL' : (xpIntoLevel + ' / ' + xpForNext + ' TO NEXT');
    if (metaEl) metaEl.textContent = 'TODAY ' + dailyXp + ' XP · DISCOVERED ' + discoveries;
}

function loadProfileFields(username, card) {
    var api = new mw.Api();
    api.get({
        action: 'userprofile',
        user: username
    }).then(function(data) {
        var profile = data.userprofile;
        updateProfileFields(card, {
            name: profile.name || '',
            discord: profile.discord || '',
            role: profile.role || '',
            bio: profile.bio || ''
        });
    }).fail(function() {
        updateProfileFields(card, {
            name: '',
            discord: '',
            role: '',
            bio: ''
        });
    });
}

function updateProfileFields(card, data) {
    var nameEl = card.querySelector('[data-field="name"]');
    var roleEl = card.querySelector('[data-field="role"]');
    var discordEl = card.querySelector('[data-field="discord"]');
    var bioEl = card.querySelector('[data-field="bio"]');
    if (nameEl) nameEl.textContent = data.name || '';
    if (roleEl) roleEl.textContent = data.role || '';
    if (discordEl) discordEl.textContent = data.discord ? ('디스코드: ' + data.discord) : '';
    if (bioEl) bioEl.textContent = data.bio || '';
}
// ========== 프로필 시스템 끝 ==========

// ========== 알림 시스템 ==========
function ensureNotificationPopup() {
    if (document.getElementById('clbi-notification-popup')) return;

    var popup = document.createElement('div');
    popup.id = 'clbi-notification-popup';
    popup.style.cssText =
        'display:none;position:fixed;z-index:99999;width:320px;max-height:420px;' +
        'background:#0a0909;border:2px solid #854369;border-radius:5px;' +
        'box-shadow:0 0 0 1px #1a1a1a, 0 8px 24px rgba(0,0,0,0.55);overflow:hidden;';

    popup.innerHTML =
        '<div style="padding:10px 12px;border-bottom:2px solid #854369;background:linear-gradient(to bottom, #171114 0%, #0a0909 100%);color:#E2E2E2;font-size:13px;font-weight:700;display:flex;align-items:center;justify-content:space-between;gap:8px;">' +
            '<span>알림</span>' +
            '<button type="button" id="clbi-notification-readall" style="background:#171717;border:1px solid #854369;border-radius:6px;color:#E2E2E2;font-size:11px;font-weight:700;padding:4px 8px;cursor:pointer;">전체 읽음</button>' +
        '</div>' +
        '<div id="clbi-notification-list" style="max-height:320px;overflow-y:auto;padding:8px 0;color:#E2E2E2;font-size:12px;">불러오는 중...</div>' +
        '<div style="padding:8px;border-top:1px solid #2a2a2a;background:#111;">' +
            '<a href="/index.php?title=Special:Notifications" id="clbi-notification-more" style="display:block;width:100%;text-align:center;padding:8px 10px;border-radius:6px;background:#171717;border:1px solid #854369;color:#E2E2E2 !important;text-decoration:none !important;font-size:12px;font-weight:700;">더보기</a>' +
        '</div>';

    document.body.appendChild(popup);
}

function positionNotificationPopup() {
    var btn = document.getElementById('profile-quick-notifications');
    var popup = document.getElementById('clbi-notification-popup');
    if (!btn || !popup) return;

    var rect = btn.getBoundingClientRect();
    var top = rect.bottom + 6;
    var left = rect.left + (rect.width / 2) - (popup.offsetWidth / 2);

    if (left < 8) left = 8;
    if (left + popup.offsetWidth > window.innerWidth - 8) {
        left = window.innerWidth - popup.offsetWidth - 8;
    }
    if (top + popup.offsetHeight > window.innerHeight - 8) {
        top = Math.max(8, rect.top - popup.offsetHeight - 6);
    }

    popup.style.top = top + 'px';
    popup.style.left = left + 'px';
}

function parseNotificationItemsFromHtml(html) {
    var parser = new DOMParser();
    var doc = parser.parseFromString(html, 'text/html');

    var selectors = [
        '.mw-echo-ui-notificationItemWidget',
        '.mw-echo-ui-notificationsInboxWidgetRow',
        '.echo-ui-notificationItemWidget',
        'li[data-notification-id]',
        '.mw-echo-notifications-list li'
    ];

    var items = [];
    for (var i = 0; i < selectors.length; i++) {
        items = Array.prototype.slice.call(doc.querySelectorAll(selectors[i]));
        if (items.length) break;
    }

    return items.slice(0, 5).map(function(item) {
        var link = item.querySelector('a[href]');
        var href = link ? link.getAttribute('href') : '/index.php?title=Special:Notifications';
        var text = (item.textContent || '').replace(/\s+/g, ' ').trim();

        var notificationId =
            item.getAttribute('data-notification-id') ||
            item.getAttribute('data-id') ||
            item.getAttribute('data-notification') ||
            '';

        if (!notificationId) {
            var anyWithId = item.querySelector('[data-notification-id], [data-id], [data-notification]');
            if (anyWithId) {
                notificationId =
                    anyWithId.getAttribute('data-notification-id') ||
                    anyWithId.getAttribute('data-id') ||
                    anyWithId.getAttribute('data-notification') ||
                    '';
            }
        }

        if (href && href.indexOf('http') !== 0) {
            href = href.charAt(0) === '/'
                ? href
                : '/index.php' + (href.charAt(0) === '?' ? href : '/' + href);
        }

        return {
            id: notificationId,
            href: href,
            text: text || '알림'
        };
    });
}

function setNotificationIcon(hasItems) {
    var quickIcon = document.getElementById('profile-quick-notification-icon');
    var svg = hasItems ? CLBI_SVG_BELL_DOT : CLBI_SVG_BELL;

    if (quickIcon) {
        quickIcon.innerHTML = svg;
        quickIcon.classList.toggle('has-notifications', !!hasItems);
    }
}

function renderNotificationPopup(items) {
    var list = document.getElementById('clbi-notification-list');
    var badge = document.getElementById('clbi-notification-badge');
    if (!list) return;

    if (!items || !items.length) {
        list.innerHTML = '<div style="padding:14px 12px;color:#999;">표시할 알림이 없습니다.</div>';
        if (badge) badge.style.display = 'none';
        setNotificationIcon(false);
        return;
    }

    var html = '';
    for (var i = 0; i < items.length; i++) {
        html +=
            '<a href="' + items[i].href + '" class="clbi-notification-item" data-notification-id="' + (items[i].id || '') + '" style="display:block;padding:10px 12px;color:#E2E2E2 !important;text-decoration:none !important;border-bottom:1px solid #1f1f1f;line-height:1.5;">' +
                items[i].text +
            '</a>';
    }
    list.innerHTML = html;

    if (badge) {
        badge.textContent = items.length;
        badge.style.display = 'block';
    }
    setNotificationIcon(true);
}

function loadNotificationsIntoPopup() {
    var list = document.getElementById('clbi-notification-list');
    if (list) {
        list.innerHTML = '<div style="padding:14px 12px;color:#999;">불러오는 중...</div>';
    }

    fetch('/index.php?title=Special:Notifications', { credentials: 'same-origin' })
        .then(function(res) {
            return res.text();
        })
        .then(function(html) {
            var items = parseNotificationItemsFromHtml(html);
            renderNotificationPopup(items);
        })
        .catch(function(err) {
            console.error(err);
            if (list) {
                list.innerHTML = '<div style="padding:14px 12px;color:#999;">알림을 불러오지 못했습니다.</div>';
            }
        });
}

function markAllNotificationsRead() {
    return new mw.Api().postWithToken('csrf', {
        action: 'echomarkread',
        list: 'all'
    });
}

function markNotificationReadById(notificationId) {
    if (!notificationId) {
        return $.Deferred().resolve().promise();
    }

    return new mw.Api().postWithToken('csrf', {
        action: 'echomarkread',
        list: notificationId
    });
}

function initNotifications() {
    var quickBtn = document.getElementById('profile-quick-notifications');

    if (!quickBtn) return;

    ensureNotificationPopup();
    loadNotificationsIntoPopup();

    $(document)
        .off('click.clbiNotificationToggle')
        .on('click.clbiNotificationToggle', '#profile-quick-notifications', function(e) {
            e.preventDefault();
            e.stopPropagation();

            var popup = document.getElementById('clbi-notification-popup');
            if (!popup) return;

            if (popup.style.display === 'none' || popup.style.display === '') {
                popup.style.display = 'block';
                positionNotificationPopup();
                loadNotificationsIntoPopup();
            } else {
                popup.style.display = 'none';
            }
        });

    $(document)
        .off('click.clbiNotificationOutside')
        .on('click.clbiNotificationOutside', function(e) {
            var popup = document.getElementById('clbi-notification-popup');
            var quickToggle = document.getElementById('profile-quick-notifications');
            if (!popup) return;

            if (!popup.contains(e.target) && (!quickToggle || !quickToggle.contains(e.target))) {
                popup.style.display = 'none';
            }
        });

    $(document)
        .off('click.clbiNotificationReadAll')
        .on('click.clbiNotificationReadAll', '#clbi-notification-readall', function(e) {
            e.preventDefault();
            e.stopPropagation();

            var button = this;
            button.disabled = true;
            button.textContent = '처리 중...';

            markAllNotificationsRead()
                .then(function() {
                    loadNotificationsIntoPopup();
                })
                .always(function() {
                    button.disabled = false;
                    button.textContent = '전체 읽음';
                });
        });

    $(document)
        .off('click.clbiNotificationItem')
        .on('click.clbiNotificationItem', '.clbi-notification-item', function(e) {
            e.preventDefault();
            e.stopPropagation();

            var href = this.getAttribute('href');
            var notificationId = this.getAttribute('data-notification-id') || '';

            markNotificationReadById(notificationId).always(function() {
                loadNotificationsIntoPopup();
                if (href) {
                    window.location.href = href;
                }
            });
        });

    $(window)
        .off('resize.clbiNotification')
        .on('resize.clbiNotification', function() {
            var popup = document.getElementById('clbi-notification-popup');
            if (popup && popup.style.display === 'block') {
                positionNotificationPopup();
            }
        });
}
// ========== 알림 시스템 끝 ==========

function initUserProfilePage() {
    $('body').addClass('user-profile-settings-page');

    var saveBtn = document.getElementById('pref-save');
    if (!saveBtn) return;

    function getPrefRow(id) {
        var el = document.getElementById(id);
        if (!el) return null;
        return el.closest('.clbi-pref-row') || el.parentNode;
    }

    function removePrefRow(id) {
        var row = getPrefRow(id);
        if (row && row.parentNode) {
            row.parentNode.removeChild(row);
        }
    }

    function createPrefSection(className, titleText) {
        var section = document.createElement('div');
        section.className = 'clbi-pref-section ' + className;

        var title = document.createElement('div');
        title.className = 'clbi-pref-section-title';
        title.textContent = titleText;

        var body = document.createElement('div');
        body.className = 'clbi-pref-section-body';

        section.appendChild(title);
        section.appendChild(body);

        return {
            section: section,
            body: body
        };
    }

    function moveRowToSection(id, targetBody, className) {
        var row = getPrefRow(id);
        if (!row || !targetBody) return false;

        row.classList.add('clbi-pref-row-key-' + className);
        targetBody.appendChild(row);
        return true;
    }

    function rebuildProfileSettingsLayout() {
        var root = document.querySelector('.clbi-prefs-profile');
        if (!root || root.dataset.profileSettingsReworked === '1') return;

        root.dataset.profileSettingsReworked = '1';
        root.classList.add('profile-settings-console');

        removePrefRow('pref-badges');

        var originalRows = Array.prototype.slice.call(root.querySelectorAll('.clbi-pref-row'));
        var actionNodes = [];

        if (saveBtn.parentNode === root || saveBtn.closest('.clbi-prefs-profile') === root) {
            actionNodes.push(saveBtn);
        }

        var statusNode = document.getElementById('pref-status');
        if (statusNode && statusNode.closest('.clbi-prefs-profile') === root) {
            actionNodes.push(statusNode);
        }

        var main = document.createElement('div');
        main.className = 'clbi-pref-main-grid';

        var media = createPrefSection('clbi-pref-section-media', 'PROFILE IMAGE');
        var identity = createPrefSection('clbi-pref-section-identity', 'IDENTITY RECORD');
        var bio = createPrefSection('clbi-pref-section-bio', 'BIOGRAPHY');
        var account = createPrefSection('clbi-pref-section-account', 'ACCOUNT CONTACT');
        var misc = createPrefSection('clbi-pref-section-misc', 'OTHER OPTIONS');

        main.appendChild(media.section);
        main.appendChild(identity.section);
        main.appendChild(bio.section);
        main.appendChild(account.section);
        main.appendChild(misc.section);

        root.innerHTML = '';
        root.appendChild(main);

        moveRowToSection('pref-pfp-preview', media.body, 'pfp');
        moveRowToSection('pref-pfp-btn', media.body, 'pfp');
        moveRowToSection('pref-pfp-input', media.body, 'pfp');

        moveRowToSection('pref-name', identity.body, 'name');
        moveRowToSection('pref-role', identity.body, 'role');
        moveRowToSection('pref-discord', identity.body, 'discord');

        moveRowToSection('pref-bio', bio.body, 'bio');

        moveRowToSection('pref-new-email', account.body, 'email');
        moveRowToSection('pref-email-password', account.body, 'email');
        moveRowToSection('pref-email-save', account.body, 'email');

        originalRows.forEach(function (row) {
            if (!row.parentNode && !row.className.match(/clbi-pref-row-key-/)) {
                misc.body.appendChild(row);
            }
        });

        if (!misc.body.children.length) {
            misc.section.parentNode.removeChild(misc.section);
        }

        var actions = document.createElement('div');
        actions.className = 'clbi-pref-actions';

        if (saveBtn) actions.appendChild(saveBtn);
        if (statusNode) actions.appendChild(statusNode);

        root.appendChild(actions);
    }

    rebuildProfileSettingsLayout();

    var api = new mw.Api();
    var selectedFile = null;
    var cropper = null;

    if (!document.getElementById('clbi-gallery-modal')) {
        var gModal = document.createElement('div');
        gModal.id = 'clbi-gallery-modal';
        gModal.style.cssText =
            'display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.85);z-index:99999;align-items:center;justify-content:center;';

        gModal.innerHTML =
            '<div style="background:#1e1e1e;border:2px solid #854369;border-radius:12px;padding:24px;max-width:480px;width:90%;display:flex;flex-direction:column;gap:16px;">' +
                '<div style="display:flex;justify-content:space-between;align-items:center;">' +
                    '<span style="font-size:14px;font-weight:700;color:#e2e2e2;">프로필 사진 선택</span>' +
                    '<button type="button" id="clbi-gallery-close" style="background:none;border:none;color:#aaa;font-size:18px;cursor:pointer;">✕</button>' +
                '</div>' +
                '<button type="button" id="clbi-gallery-upload-btn" style="background:#2a2a2a;border:2px dashed #854369;border-radius:8px;padding:32px;color:#e2e2e2;cursor:pointer;display:flex;flex-direction:column;align-items:center;gap:8px;font-size:13px;width:100%;">' +
                    '<span style="font-size:32px;">🖼️</span>새 사진 업로드' +
                '</button>' +
                '<div id="clbi-gallery-history-section" style="display:none;">' +
                    '<div style="font-size:11px;color:#888;margin-bottom:8px;">이전 사진 — 클릭하면 바로 적용</div>' +
                    '<div id="clbi-gallery-history" style="display:flex;gap:8px;flex-wrap:wrap;"></div>' +
                '</div>' +
            '</div>';

        document.body.appendChild(gModal);
    }

    if (!document.getElementById('clbi-crop-modal')) {
        var cModal = document.createElement('div');
        cModal.id = 'clbi-crop-modal';
        cModal.style.cssText =
            'display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.85);z-index:99999;align-items:center;justify-content:center;';

        cModal.innerHTML =
            '<div style="background:#1e1e1e;border:2px solid #854369;border-radius:12px;padding:24px;max-width:500px;width:90%;display:flex;flex-direction:column;gap:16px;">' +
                '<div style="font-size:14px;font-weight:700;color:#e2e2e2;">사진 조정</div>' +
                '<div style="width:100%;max-height:380px;overflow:hidden;border-radius:8px;">' +
                    '<img id="clbi-crop-image" style="max-width:100%;">' +
                '</div>' +
                '<div style="display:flex;gap:8px;justify-content:flex-end;">' +
                    '<button type="button" id="clbi-crop-cancel" style="background:#2a2a2a;color:#e2e2e2;border:1px solid #444;padding:8px 16px;border-radius:6px;cursor:pointer;">취소</button>' +
                    '<button type="button" id="clbi-crop-confirm" style="background:#854369;color:#fff;border:none;padding:8px 16px;border-radius:6px;cursor:pointer;">확정</button>' +
                '</div>' +
            '</div>';

        document.body.appendChild(cModal);
    }

    var gModal = document.getElementById('clbi-gallery-modal');
    var cModal = document.getElementById('clbi-crop-modal');
    var cropImage = document.getElementById('clbi-crop-image');
    var pfpInput = document.getElementById('pref-pfp-input');

    function openGallery() {
        gModal.style.display = 'flex';

        var username = mw.config.get('wgUserName');
        api.get({
            action: 'query',
            titles: '파일:Pfp-' + username + '.png',
            prop: 'imageinfo',
            iiprop: 'url|timestamp',
            iilimit: 6
        }).then(function(data) {
            var pages = data.query.pages;
            var page = pages[Object.keys(pages)[0]];
            if (!page.imageinfo || page.imageinfo.length === 0) return;

            var historyEl = document.getElementById('clbi-gallery-history');
            var sectionEl = document.getElementById('clbi-gallery-history-section');
            historyEl.innerHTML = '';

            page.imageinfo.forEach(function(info, idx) {
                var wrap = document.createElement('div');
                wrap.style.cssText = 'position:relative;cursor:pointer;';

                var img = document.createElement('img');
                img.src = info.url;
                img.style.cssText =
                    'width:72px;height:72px;object-fit:cover;border-radius:8px;border:2px solid #444;flex-shrink:0;';

                if (idx === 0) {
                    img.style.borderColor = '#854369';
                    var badge = document.createElement('div');
                    badge.textContent = '현재';
                    badge.style.cssText =
                        'position:absolute;bottom:4px;left:50%;transform:translateX(-50%);background:#854369;color:#fff;font-size:9px;padding:1px 6px;border-radius:10px;';
                    wrap.appendChild(badge);
                }

                img.addEventListener('mouseenter', function() {
                    if (idx !== 0) img.style.borderColor = '#854369';
                });

                img.addEventListener('mouseleave', function() {
                    if (idx !== 0) img.style.borderColor = '#444';
                });

                img.addEventListener('click', function() {
                    fetch(info.url)
                        .then(function(r) {
                            return r.blob();
                        })
                        .then(function(blob) {
                            selectedFile = new File([blob], 'profile.png', { type: 'image/png' });
                            document.getElementById('pref-pfp-preview').src = URL.createObjectURL(blob);
                            gModal.style.display = 'none';
                            document.getElementById('pref-pfp-btn').textContent = '✓ 사진 선택됨';
                        });
                });

                wrap.appendChild(img);
                historyEl.appendChild(wrap);
            });

            sectionEl.style.display = 'block';
        });
    }

    function openCrop(src) {
        cropImage.src = src;
        cModal.style.display = 'flex';

        if (cropper) {
            cropper.destroy();
            cropper = null;
        }

        setTimeout(function() {
            cropper = new Cropper(cropImage, {
                aspectRatio: 1,
                viewMode: 1,
                dragMode: 'move',
                autoCropArea: 0.8,
                cropBoxResizable: true,
                cropBoxMovable: true
            });
        }, 150);
    }

    document.getElementById('pref-pfp-btn').addEventListener('click', function() {
        openGallery();
    });

    document.getElementById('clbi-gallery-upload-btn').addEventListener('click', function() {
        pfpInput.click();
    });

    document.getElementById('clbi-gallery-close').addEventListener('click', function() {
        gModal.style.display = 'none';
    });

    pfpInput.addEventListener('change', function() {
        var file = this.files[0];
        if (!file) return;

        gModal.style.display = 'none';

        var reader = new FileReader();
        reader.onload = function(e) {
            openCrop(e.target.result);
        };
        reader.readAsDataURL(file);
    });

    document.getElementById('clbi-crop-cancel').addEventListener('click', function() {
        cModal.style.display = 'none';
        if (cropper) {
            cropper.destroy();
            cropper = null;
        }
        pfpInput.value = '';
    });

    document.getElementById('clbi-crop-confirm').addEventListener('click', function() {
        if (!cropper) return;

        var canvas = cropper.getCroppedCanvas({ width: 256, height: 256 });
        if (!canvas) return;

        canvas.toBlob(function(blob) {
            selectedFile = new File([blob], 'profile.png', { type: 'image/png' });
            document.getElementById('pref-pfp-preview').src = URL.createObjectURL(blob);
            cModal.style.display = 'none';
            cropper.destroy();
            cropper = null;
            document.getElementById('pref-pfp-btn').textContent = '✓ 사진 선택됨';
        }, 'image/png');
    });

    var emailSaveBtn = document.getElementById('pref-email-save');
    if (emailSaveBtn) {
        emailSaveBtn.addEventListener('click', function() {
            var statusEl = document.getElementById('pref-email-status');
            var newEmail = document.getElementById('pref-new-email').value;
            var password = document.getElementById('pref-email-password').value;

            if (!newEmail || !password) {
                statusEl.textContent = '이메일과 비밀번호를 입력해주세요.';
                return;
            }

            statusEl.textContent = '변경 중...';

            api.postWithToken('csrf', {
                action: 'changeemail',
                email: newEmail,
                password: password
            }).then(function() {
                statusEl.textContent = '✓ 이메일 변경됨';
                document.getElementById('pref-new-email').value = '';
                document.getElementById('pref-email-password').value = '';

                setTimeout(function() {
                    statusEl.textContent = '';
                }, 3000);
            }).fail(function(code, data) {
                var msg = data && data.error && data.error.info ? data.error.info : '변경 실패';
                statusEl.textContent = msg;
            });
        });
    }

    saveBtn.addEventListener('click', function() {
        var statusEl = document.getElementById('pref-status');
        statusEl.textContent = '저장 중...';

        var promises = [];

        if (selectedFile) {
            var username = mw.config.get('wgUserName');
            promises.push(
                api.postWithToken('csrf', {
                    action: 'upload',
                    filename: 'Pfp-' + username + '.png',
                    ignorewarnings: true,
                    file: selectedFile,
                    format: 'json'
                }, {
                    contentType: 'multipart/form-data'
                })
            );
        }

        var fields = ['name', 'discord', 'role', 'bio'];

        for (var i = 0; i < fields.length; i++) {
            var el = document.getElementById('pref-' + fields[i]);
            if (!el) continue;

            promises.push(
                api.postWithToken('csrf', {
                    action: 'options',
                    optionname: 'profile-' + fields[i],
                    optionvalue: el.value
                })
            );
        }

        $.when.apply($, promises)
            .then(function() {
                statusEl.textContent = '✓ 저장됨';
                selectedFile = null;
                document.getElementById('pref-pfp-btn').textContent = '사진 선택';

                setTimeout(function() {
                    statusEl.textContent = '';
                }, 2000);
            })
            .fail(function() {
                statusEl.textContent = '저장 실패';
            });
    });
}

/* =========================================
   Banner / CRT Page Monitor thumbnail slices
   - base 이미지는 틀에 들어간 파일 문법 그대로 사용
   - slice 레이어에는 300px MediaWiki 썸네일만 삽입
   ========================================= */

(function ($, mw) {
    var thumbCache = {};

    function parseSliceWidth(value) {
        var parsed = parseInt(value, 10);

        if (!isFinite(parsed) || parsed < 120) {
            return 300;
        }

        return parsed;
    }

    function getImageSrc(img) {
        return img ? (img.currentSrc || img.getAttribute('src') || img.src || '') : '';
    }

    function getFileNameFromSrc(src) {
        var a;
        var parts;
        var fileName;

        if (!src) return '';

        a = document.createElement('a');
        a.href = src;

        parts = (a.pathname || '').split('/').filter(function (part) {
            return !!part;
        });

        if (!parts.length) return '';

        fileName = parts.pop();

        /*
         * MediaWiki thumb URL 예시:
         * /images/thumb/a/ab/File.png/1000px-File.png
         * /images/thumb/a/ab/File.svg/1000px-File.svg.png
         *
         * 이 경우 실제 파일명은 마지막 조각이 아니라 그 앞 조각이다.
         */
        if (/^\d+px-/.test(fileName) && parts.length) {
            fileName = parts.pop();
        }

        fileName = fileName.replace(/^\d+px-/, '');

        try {
            fileName = decodeURIComponent(fileName);
        } catch (e) {}

        return fileName;
    }

    function resolveThumbUrl(img, width, callback) {
        var src = getImageSrc(img);
        var fileName = getFileNameFromSrc(src);
        var cacheKey;
        var entry;

        if (!src) return;

        if (!fileName || !mw || !mw.loader) {
            callback(src);
            return;
        }

        cacheKey = fileName + '|' + width;
        entry = thumbCache[cacheKey];

        if (entry) {
            if (entry.resolved) {
                callback(entry.url || src);
            } else {
                entry.callbacks.push(callback);
            }
            return;
        }

        entry = {
            resolved: false,
            url: '',
            callbacks: [callback]
        };

        thumbCache[cacheKey] = entry;

        function finish(url) {
            var callbacks = entry.callbacks.slice();
            var i;

            entry.resolved = true;
            entry.url = url || src;
            entry.callbacks = [];

            for (i = 0; i < callbacks.length; i++) {
                callbacks[i](entry.url);
            }
        }

        mw.loader.using('mediawiki.api').done(function () {
            var api = new mw.Api();

            api.get({
                action: 'query',
                titles: 'File:' + fileName,
                prop: 'imageinfo',
                iiprop: 'url',
                iiurlwidth: width,
                formatversion: 2
            }).done(function (data) {
                var page;
                var info;

                if (
                    data &&
                    data.query &&
                    data.query.pages &&
                    data.query.pages.length
                ) {
                    page = data.query.pages[0];

                    if (
                        page &&
                        page.imageinfo &&
                        page.imageinfo.length
                    ) {
                        info = page.imageinfo[0];
                    }
                }

                finish((info && (info.thumburl || info.url)) || src);
            }).fail(function () {
                finish(src);
            });
        }).fail(function () {
            finish(src);
        });
    }

    function applySliceImages(frame, thumbUrl) {
        var slices;
        var i;
        var img;

        if (!frame || !thumbUrl) return;

        slices = frame.querySelectorAll('.crt-page-monitor-slice');

        for (i = 0; i < slices.length; i++) {
            slices[i].innerHTML = '';

            img = document.createElement('img');
            img.className = 'crt-page-monitor-slice-img';
            img.src = thumbUrl;
            img.alt = '';
            img.decoding = 'async';
            img.loading = 'eager';
            img.setAttribute('aria-hidden', 'true');

            slices[i].appendChild(img);
        }

        frame.setAttribute('data-crt-slices-ready', '1');
    }

    function initBannerFrame(frame) {
        var baseImg;
        var width;

        if (!frame) return;
        if (frame.getAttribute('data-crt-slices-ready') === '1') return;

        baseImg = frame.querySelector('.crt-page-monitor-image-base img');

        if (!baseImg) return;

        width = parseSliceWidth(frame.getAttribute('data-crt-slice-width'));

        resolveThumbUrl(baseImg, width, function (thumbUrl) {
            if (!frame || !frame.parentNode) return;
            applySliceImages(frame, thumbUrl);
        });
    }

    function initBannerFrames(root) {
        var scope = root && root.querySelectorAll ? root : document;
        var frames = scope.querySelectorAll('.crt-page-monitor-frame');
        var i;

        for (i = 0; i < frames.length; i++) {
            initBannerFrame(frames[i]);
        }
    }

    $(function () {
        initBannerFrames(document);
    });

    if (mw && mw.hook) {
        mw.hook('wikipage.content').add(function ($content) {
            initBannerFrames($content && $content[0] ? $content[0] : document);
        });
    }
})(jQuery, window.mw);

/* =========================================
   Doc Tab System — tab switching UI
   글리치 플리커 + RGB split + 방향 슬라이드
   ========================================= */

(function () {
    'use strict';

    function initDocTabs() {
        var tabBars = document.querySelectorAll('.doc-tab-bar');
        if (!tabBars.length) return;

        tabBars.forEach(function (bar) {
            if (bar.getAttribute('data-tabs-init')) return;
            bar.setAttribute('data-tabs-init', '1');

            var tabs = Array.from(bar.querySelectorAll('.doc-tab'));
            if (!tabs.length) return;

            var panel = bar.closest('.doc-panel');
            var display = panel ? panel.querySelector('.doc-display') : null;
            if (!display) display = document.getElementById('doc-main-display');
            if (!display) return;

            tabs.forEach(function (tab, i) {
                tab.addEventListener('click', function () {
                    var currentIdx = tabs.findIndex(function (t) {
                        return t.classList.contains('active');
                    });
                    if (currentIdx === i) return;
                    switchTab(tabs, display, i, i > currentIdx ? 1 : -1);
                });
            });

            var initIdx = tabs.findIndex(function (t) { return t.classList.contains('active'); });
            if (initIdx !== -1) {
                var initRef = tabs[initIdx].dataset.ref;
                var initEl = initRef ? document.getElementById(initRef) : null;
                display.innerHTML = initEl ? initEl.innerHTML : (tabs[initIdx].dataset.content || '');
            }
        });

    }

    var isAnimating = false;

    function switchTab(tabs, display, nextIdx, dir) {
        if (isAnimating) return;
        isAnimating = true;

        tabs.forEach(function (t) { t.classList.remove('active'); });
        tabs[nextIdx].classList.add('active');

        var ref = tabs[nextIdx].dataset.ref;
        var nextContent;
        if (ref) {
            var refEl = document.getElementById(ref);
            nextContent = refEl ? refEl.innerHTML : '';
        } else {
            nextContent = tabs[nextIdx].dataset.content || '';
        }

        glitchOut(display, dir, function () {
            display.innerHTML = nextContent;
            glitchIn(display, dir, function () {
                isAnimating = false;
            });
        });
    }

    function glitchOut(el, dir, cb) {
        var duration = 160;
        var start = null;
        var slideX = dir * 16;

        function step(ts) {
            if (!start) start = ts;
            var p = Math.min((ts - start) / duration, 1);
            var ease = p * p;

            var tx = slideX * ease;
            var skew = dir * ease * 1.0;
            var opacity = 1 - ease;
            var rgb = ease * 5;

            el.style.transform = 'translateX(' + tx + 'px) skewX(' + skew + 'deg)';
            el.style.opacity = opacity;
            el.style.filter =
                'drop-shadow(' + (-rgb) + 'px 0 0 rgba(80,160,255,0.75)) ' +
                'drop-shadow(' + rgb + 'px 0 0 rgba(255,55,90,0.65)) ' +
                'brightness(' + (1 + ease * 0.25) + ')';

            if (p < 1) {
                requestAnimationFrame(step);
            } else {
                el.style.opacity = '0';
                cb();
            }
        }
        requestAnimationFrame(step);
    }

    function glitchIn(el, dir, cb) {
        var duration = 200;
        var start = null;
        var startX = -dir * 16;

        el.style.transform = 'translateX(' + startX + 'px) skewX(' + (-dir * 1.0) + 'deg)';
        el.style.opacity = '0';

        function step(ts) {
            if (!start) start = ts;
            var p = Math.min((ts - start) / duration, 1);
            var ease = 1 - Math.pow(1 - p, 3);

            var tx = startX * (1 - ease);
            var skew = -dir * 1.0 * (1 - ease);
            var opacity = ease;
            var rgb = (1 - ease) * 3;
            var brightness = 1 + (1 - ease) * 0.35;

            el.style.transform = 'translateX(' + tx + 'px) skewX(' + skew + 'deg)';
            el.style.opacity = opacity;
            el.style.filter =
                'drop-shadow(' + (-rgb) + 'px 0 0 rgba(80,160,255,0.65)) ' +
                'drop-shadow(' + rgb + 'px 0 0 rgba(255,55,90,0.55)) ' +
                'brightness(' + brightness + ')';

            if (p < 1) {
                requestAnimationFrame(step);
            } else {
                el.style.transform = '';
                el.style.opacity = '';
                el.style.filter = '';
                cb();
            }
        }
        requestAnimationFrame(step);
    }

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initDocTabs);
} else {
    initDocTabs();
}

if (typeof mw !== 'undefined' && mw.hook) {
    mw.hook('wikipage.content').add(function () {
        initDocTabs();
    });
}

})();

/* =========================================
   Doc Section Switch — 좌측 섹션 전환
   ========================================= */

$(document).on('click', '.doc-nav-item[data-section]', function () {
    var name = $(this).attr('data-section');
    var display = document.getElementById('doc-main-display');
    var titleEl = document.getElementById('doc-center-title');
    var tabBar = document.getElementById('doc-tab-bar-text');

    if (!display) return;

    $('.doc-nav-item[data-section]').removeClass('active');
    $('.doc-nav-item[data-section="' + name + '"]').addClass('active');

    if (name === 'text') {
        if (titleEl) titleEl.textContent = '개요';
        if (tabBar) $(tabBar).show();
        var activeTab = tabBar ? tabBar.querySelector('.doc-tab.active') : null;
        if (!activeTab && tabBar) activeTab = tabBar.querySelector('.doc-tab');
        if (activeTab) {
            var ref = activeTab.dataset.ref;
            var refEl = ref ? document.getElementById(ref) : null;
            display.innerHTML = refEl ? refEl.innerHTML : (activeTab.dataset.content || '');
        }
    } else {
        if (titleEl) titleEl.textContent = name === 'factions' ? '세력' : name === 'people' ? '인물' : name;
        if (tabBar) $(tabBar).hide();
        var refEl = document.getElementById('doc-content-' + name);
        display.innerHTML = refEl ? refEl.innerHTML : '';
    }
});

/* =========================================
   CRT WebGL Renderer — cool-retro-term IBM DOS style
   ========================================= */
(function () {
    'use strict';

    function createNoiseTexture(gl) {
        var size = 512;
        var data = new Uint8Array(size * size * 4);
        var s = 12345;
        function rand() {
            s = (s * 1664525 + 1013904223) & 0xffffffff;
            return (s >>> 0) / 0xffffffff;
        }
        for (var i = 0; i < data.length; i++) {
            data[i] = (rand() * 255) | 0;
        }
        var tex = gl.createTexture();
        gl.bindTexture(gl.TEXTURE_2D, tex);
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
        return tex;
    }

    var VERT = [
        'attribute vec2 a_pos;',
        'varying vec2 v_uv;',
        'void main() {',
        '  v_uv = vec2(a_pos.x * 0.5 + 0.5, 0.5 - a_pos.y * 0.5);',
        '  gl_Position = vec4(a_pos, 0.0, 1.0);',
        '}'
    ].join('\n');

    var FRAG = [
        'precision mediump float;',
        'uniform sampler2D u_tex;',
        'uniform sampler2D u_noise;',
        'uniform vec2 u_res;',
        'uniform vec2 u_imgSize;',
        'uniform float u_time;',
        'uniform vec2 u_noiseScale;',
        'varying vec2 v_uv;',

        'float sum2(vec2 v) { return v.x + v.y; }',
        'float min2(vec2 v) { return min(v.x, v.y); }',
        'float rgb2grey(vec3 v) { return dot(v, vec3(0.21, 0.72, 0.04)); }',

        'vec2 coverUV(vec2 uv) {',
        '  float imgAR = u_imgSize.x / u_imgSize.y;',
        '  float scrAR = u_res.x / u_res.y;',
        '  float scale = imgAR / scrAR;',
        '  float offsetY = (1.0 - scale) * 0.5;',
        '  return vec2(uv.x, uv.y * scale + offsetY);',
        '}',

        'vec2 barrel(vec2 v, vec2 cc, float k) {',
        '  float ar = u_res.x / u_res.y;',
        '  vec2 c2 = cc;',
        '  if (ar > 1.0) c2.x /= ar; else c2.y *= ar;',
        '  float dist = dot(c2, c2) * k;',
        '  return v - cc * (1.0 + dist) * dist;',
        '}',

        'vec4 sampleInitialNoise(float t) {',
        '  return texture2D(u_noise, vec2(fract(t/2048.0), fract(t/1048576.0)));',
        '}',

        'vec4 sampleScreenNoise(vec2 uv) {',
        '  return texture2D(u_noise, u_noiseScale * uv);',
        '}',

        'vec3 applyRgbShift(vec2 texUV, float shift) {',
        '  vec2 d = vec2(shift, 0.0);',
        '  vec3 r = texture2D(u_tex, clamp(texUV + d, 0.0, 1.0)).rgb;',
        '  vec3 c = texture2D(u_tex, texUV).rgb;',
        '  vec3 l = texture2D(u_tex, clamp(texUV - d, 0.0, 1.0)).rgb;',
        '  return vec3(',
        '    l.r*0.10 + r.r*0.30 + c.r*0.60,',
        '    l.g*0.20 + r.g*0.20 + c.g*0.60,',
        '    l.b*0.30 + r.b*0.10 + c.b*0.60',
        '  );',
        '}',

        'vec3 applyBloom(vec2 texUV, float strength) {',
        '  vec2 px = 2.0 / u_res;',
        '  vec3 acc = vec3(0.0);',
        '  acc += texture2D(u_tex, clamp(texUV + vec2( px.x,  0.0), 0.0, 1.0)).rgb;',
        '  acc += texture2D(u_tex, clamp(texUV + vec2(-px.x,  0.0), 0.0, 1.0)).rgb;',
        '  acc += texture2D(u_tex, clamp(texUV + vec2( 0.0,  px.y), 0.0, 1.0)).rgb;',
        '  acc += texture2D(u_tex, clamp(texUV + vec2( 0.0, -px.y), 0.0, 1.0)).rgb;',
        '  acc += texture2D(u_tex, clamp(texUV + vec2( px.x,  px.y), 0.0, 1.0)).rgb * 0.5;',
        '  acc += texture2D(u_tex, clamp(texUV + vec2(-px.x,  px.y), 0.0, 1.0)).rgb * 0.5;',
        '  acc += texture2D(u_tex, clamp(texUV + vec2( px.x, -px.y), 0.0, 1.0)).rgb * 0.5;',
        '  acc += texture2D(u_tex, clamp(texUV + vec2(-px.x, -px.y), 0.0, 1.0)).rgb * 0.5;',
        '  return acc / 6.0 * strength;',
        '}',

        'vec3 applyScanlines(vec2 uv, vec3 col) {',
        '  float line = mod(uv.y * u_res.y, 2.0);',
        '  vec3 hi = ((1.0 + 0.30) - 0.2 * col) * col;',
        '  vec3 lo = ((1.0 - 0.30) + 0.1 * col) * col;',
        '  return line < 1.0 ? lo : hi;',
        '}',

'vec3 applyRasterization(vec2 uv, vec3 col) {',
'  float t = u_time;',
'  vec2 noiseUV = uv + vec2(fract(t * 0.030), fract(t * 0.060));',
'  float wobbleX = (texture2D(u_noise, noiseUV * 0.8).r - 0.5) * 0.0018;',
'  float wobbleY = (texture2D(u_noise, noiseUV * 0.8 + 0.5).r - 0.5) * 0.0008;',
'  vec2 wobbledUV = clamp(uv + vec2(wobbleX, wobbleY), 0.0, 1.0);',
'  vec3 wobbled = texture2D(u_tex, wobbledUV).rgb;',
'  return mix(col, wobbled, 0.35);',
'}',

        'float glowingLine(vec2 uv, float t) {',
'  float pos = fract(t * 0.2);',
'  float lineY = pos * (u_res.y + 330.0) - 120.0;',
        '  float y = uv.y * u_res.y;',
        '  return fract(smoothstep(-300.0, 0.0, y - lineY));',
        '}',

        'vec2 applyHSync(vec2 uv, vec4 noise, float strength) {',
        '  float randval = strength - noise.r;',
        '  float scale = step(0.0, randval) * randval * strength;',
        '  float freq = mix(4.0, 40.0, noise.g);',
        '  uv.x += sin((uv.y + u_time * 0.001) * freq) * scale;',
        '  return uv;',
        '}',

        'void main() {',
        '  vec2 cc = vec2(0.5) - v_uv;',

        '  float curvature = 0.18;',
        '  vec2 uv = barrel(v_uv, cc, curvature);',

        '  float inScreen = min2(step(vec2(0.0), uv) - step(vec2(1.0), uv));',
        '  if (inScreen < 0.5) { gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); return; }',

        '  vec2 texUV = clamp(coverUV(uv), 0.0, 1.0);',

        '  vec4 initNoise = sampleInitialNoise(u_time);',
        '  vec4 screenNoise = sampleScreenNoise(uv);',

        '  texUV = applyHSync(texUV, initNoise, 0.006);',
        '  texUV = clamp(texUV, 0.0, 1.0);',

        '  texUV += (vec2(screenNoise.b, screenNoise.a) - 0.5) * 0.0006;',
        '  texUV = clamp(texUV, 0.0, 1.0);',

        '  vec3 col = applyRgbShift(texUV, 0.003);',
        '  col += applyBloom(texUV, 0.22);',

        '  vec2 bpx = 1.5 / u_res;',
        '  vec3 blurCol = vec3(0.0);',
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2(-bpx.x, -bpx.y), 0.0, 1.0)).rgb;',
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2( 0.0,   -bpx.y), 0.0, 1.0)).rgb;',
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2( bpx.x, -bpx.y), 0.0, 1.0)).rgb;',
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2(-bpx.x,  0.0  ), 0.0, 1.0)).rgb;',
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2( bpx.x,  0.0  ), 0.0, 1.0)).rgb;',
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2(-bpx.x,  bpx.y), 0.0, 1.0)).rgb;',
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2( 0.0,    bpx.y), 0.0, 1.0)).rgb;',
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2( bpx.x,  bpx.y), 0.0, 1.0)).rgb;',
        '  col = mix(col, blurCol / 8.0, 0.40);',

        '  col = applyScanlines(uv, col);',
        '  col = applyRasterization(texUV, col);',

        '  float glow = glowingLine(uv, u_time);',
'  col += glow * 0.08 * vec3(0.85, 0.95, 1.0);',

        '  float dist = length(cc);',
        '  col += screenNoise.a * 0.07 * (1.0 - dist * 1.3);',

        '  float grey = rgb2grey(col);',
        '  vec3 phosphor = vec3(0.75, 0.88, 1.0);',
        '  col = mix(col, grey * phosphor, 0.35);',

        '  vec2 vig = v_uv * (1.0 - v_uv);',
        '  col *= pow(vig.x * vig.y * 15.0, 0.25);',

        '  col *= 1.0 + (initNoise.g - 0.5) * 0.06;',

        '  col += vec3(0.012) * (1.0 - dist) * (1.0 - dist);',

        '  col = pow(clamp(col, 0.0, 1.0), vec3(0.90));',

        '  gl_FragColor = vec4(col, 1.0);',
        '}'
    ].join('\n');

    function initCRTCanvas(screen, imgEl) {
        var existing = screen.querySelector('.crt-webgl-canvas');
        if (existing) existing.remove();

        var canvas = document.createElement('canvas');
        canvas.className = 'crt-webgl-canvas';
        canvas.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;z-index:19;pointer-events:none;display:block;';
        screen.appendChild(canvas);

        var gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
        if (!gl) return;

        function compile(type, src) {
            var s = gl.createShader(type);
            gl.shaderSource(s, src);
            gl.compileShader(s);
            if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
                console.error('[CRT shader]', gl.getShaderInfoLog(s));
            }
            return s;
        }

        var prog = gl.createProgram();
        gl.attachShader(prog, compile(gl.VERTEX_SHADER, VERT));
        gl.attachShader(prog, compile(gl.FRAGMENT_SHADER, FRAG));
        gl.linkProgram(prog);
        gl.useProgram(prog);

        var buf = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, buf);
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1,-1, 1,-1, -1,1, 1,1]), gl.STATIC_DRAW);
        var aPos = gl.getAttribLocation(prog, 'a_pos');
        gl.enableVertexAttribArray(aPos);
        gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);

        var uTex     = gl.getUniformLocation(prog, 'u_tex');
        var uNoise   = gl.getUniformLocation(prog, 'u_noise');
        var uRes     = gl.getUniformLocation(prog, 'u_res');
        var uImgSize = gl.getUniformLocation(prog, 'u_imgSize');
        var uTime    = gl.getUniformLocation(prog, 'u_time');
        var uNoiseSc = gl.getUniformLocation(prog, 'u_noiseScale');

        var imgTex = gl.createTexture();
        gl.activeTexture(gl.TEXTURE0);
        gl.bindTexture(gl.TEXTURE_2D, imgTex);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

        gl.activeTexture(gl.TEXTURE1);
        createNoiseTexture(gl);

        var texReady = false;
        function uploadImg() {
            if (!imgEl || !imgEl.complete || !imgEl.naturalWidth) return;
            try {
                gl.activeTexture(gl.TEXTURE0);
                gl.bindTexture(gl.TEXTURE_2D, imgTex);
                gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, imgEl);
                texReady = true;
            } catch(e) { console.error('[CRT] tex:', e); }
        }

        var lastW = 0, lastH = 0;
        function resize() {
            var w = screen.offsetWidth, h = screen.offsetHeight;
            if (w === lastW && h === lastH) return;
            lastW = w; lastH = h;
            canvas.width = w; canvas.height = h;
            gl.viewport(0, 0, w, h);
        }

        var raf;
        var visualTime = 0;
        var lastVisualNow = 0;

        function render(now) {
            var delta;
            raf = requestAnimationFrame(render);

            if (!lastVisualNow) lastVisualNow = now;
            delta = Math.max(0, Math.min(100, now - lastVisualNow));
            lastVisualNow = now;

            if (document.hidden || isClbiCompositorBusy()) return;
            if (!texReady) { uploadImg(); return; }

            visualTime += delta;
            resize();
            var t = visualTime / 1000;
            gl.uniform1i(uTex, 0);
            gl.uniform1i(uNoise, 1);
            gl.uniform2f(uRes, canvas.width, canvas.height);
            gl.uniform2f(uImgSize, imgEl.naturalWidth, imgEl.naturalHeight);
            gl.uniform1f(uTime, t);
            gl.uniform2f(uNoiseSc, canvas.width / 512.0, canvas.height / 512.0);
            gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
        }

        if (imgEl.complete && imgEl.naturalWidth) { uploadImg(); }
        else { imgEl.addEventListener('load', uploadImg); }

        render();
        screen._crtCleanup = function () { cancelAnimationFrame(raf); };
    }

    function initAllCRTScreens(root) {
        var scope = root && root.querySelectorAll ? root : document;
        scope.querySelectorAll('.crt-page-monitor-screen').forEach(function (screen) {
            if (screen.getAttribute('data-crt-webgl') === '1') return;
            screen.setAttribute('data-crt-webgl', '1');
            var frame = screen.closest('.crt-page-monitor-frame');
            if (!frame) return;
            var imgEl = frame.querySelector('.crt-page-monitor-slice-img, .crt-page-monitor-image-base img');
            if (imgEl && imgEl.complete && imgEl.naturalWidth) {
                initCRTCanvas(screen, imgEl);
            } else if (imgEl) {
                imgEl.addEventListener('load', function () { initCRTCanvas(screen, imgEl); });
            } else {
                var obs = new MutationObserver(function () {
                    var img = frame.querySelector('.crt-page-monitor-slice-img');
                    if (!img) return;
                    obs.disconnect();
                    if (img.complete && img.naturalWidth) {
                        initCRTCanvas(screen, img);
                    } else {
                        img.addEventListener('load', function () { initCRTCanvas(screen, img); });
                    }
                });
                obs.observe(frame, { childList: true, subtree: true });
            }
        });
    }

    $(function () { initAllCRTScreens(document); });

    if (typeof mw !== 'undefined' && mw.hook) {
        mw.hook('wikipage.content').add(function ($c) {
            document.querySelectorAll('.crt-page-monitor-screen').forEach(function (s) {
                if (s._crtCleanup) s._crtCleanup();
                s.removeAttribute('data-crt-webgl');
            });
            initAllCRTScreens($c && $c[0] ? $c[0] : document);
        });
    }
})();

/* =========================================
Progress System UI
MediaWiki:Common.js controlled frontend
========================================= */
(function (mw, $) {
    'use strict';

    if (window.ProgressSystemWebUiInitialized) return;
    window.ProgressSystemWebUiInitialized = true;

    var api = null;

    function withApi(done, fail) {
        if (api) {
            done(api);
            return;
        }

        if (!mw.loader || typeof mw.loader.using !== 'function') {
            if (typeof fail === 'function') fail();
            return;
        }

        mw.loader.using(['mediawiki.api']).then(function () {
            api = new mw.Api();
            done(api);
        }, function () {
            if (typeof fail === 'function') fail();
        });
    }

    var inFlightPageIds = new Set();
    var handledPageIds = new Set();
    var notificationQueue = [];
    var notificationActive = false;
    var summaryRequested = false;
    var currentSummary = null;
    var pendingSummary = null;
    var pendingOptions = null;
    var visibilityBound = false;
    var barTimerA = null;
    var barTimerB = null;
    var barTimerC = null;
    var summaryRetryTimer = null;
    var summaryRetryAttempts = 0;

    function isLoggedIn() {
        return !!mw.config.get('wgUserName');
    }

    function getPageId() {
        var id = parseInt(mw.config.get('wgArticleId') || 0, 10);
        return Number.isFinite(id) ? id : 0;
    }

    function isRewardableClientSide() {
        if (!isLoggedIn()) return false;
        if (parseInt(mw.config.get('wgNamespaceNumber'), 10) !== 0) return false;
        if (mw.config.get('wgIsMainPage')) return false;
        if (getPageId() <= 0) return false;
        return true;
    }

    function getPanelHtml() {
        return '' +
            '<div id="progress-panel" class="profile-progress-block is-syncing" aria-live="polite" data-progress-state="syncing">' +
                '<div class="progress-title-row" hidden></div>' +
                '<div class="progress-level-row">' +
                    '<span class="progress-level-label">SYNC</span>' +
                    '<span class="progress-total-xp">— XP</span>' +
                '</div>' +
                '<div class="progress-xp-bar" aria-hidden="true">' +
                    '<div class="progress-xp-gain"></div>' +
                    '<div class="progress-xp-fill"></div>' +
                '</div>' +
                '<div class="progress-sub-row">' +
                    '<span class="progress-xp-next">SYNCING</span>' +
                    '<span class="progress-daily-xp">TODAY —</span>' +
                '</div>' +
                '<div class="progress-discovery-row">DISCOVERED —</div>' +
            '</div>';
    }

    function getDividerHtml() {
        /* 프로필 패널 최신 규칙: 레벨 패널과 버튼 영역 사이에 별도 나눔선은 만들지 않는다. */
        return '';
    }

    function setPanelSync($panel) {
        if (!$panel || !$panel.length) return;

        $panel.addClass('is-syncing').removeClass('is-max-level').attr('data-progress-state', 'syncing');
        $panel.find('.progress-title-row').text('').prop('hidden', true);
        $panel.find('.progress-level-label').text('SYNC');
        $panel.find('.progress-total-xp').text('— XP');
        $panel.find('.progress-xp-next').text('SYNCING');
        $panel.find('.progress-daily-xp').text('TODAY —');
        $panel.find('.progress-discovery-row').text('DISCOVERED —');
        $panel.find('.progress-xp-fill').css({ transition: 'none', width: '0%' });
        $panel.find('.progress-xp-gain').css({ transition: 'none', width: '0%', opacity: 0 });
    }

    function placePanel($panel) {
        var $right = $('#clbi-right-sidebar');
        if (!$right.length) return false;

        var $userBox = $right.children('.clbi-right-box').first();
        if (!$userBox.length) return false;

        var $buttonArea = $userBox.children('.clbi-right-content').first();
        var $oldFallback = $panel.closest('.progress-panel-fallback');

        if ($buttonArea.length) {
            var $divider = $('#profile-progress-divider');

            $panel.insertBefore($buttonArea);

            if (!$divider.length) {
                $divider = $(getDividerHtml());
            }

            $divider.insertAfter($panel);
        } else {
            $('#profile-progress-divider').remove();
            $userBox.append($panel);
        }

        if ($oldFallback.length && !$oldFallback.find('#progress-panel').length) {
            $oldFallback.remove();
        }

        return true;
    }

    function ensurePanel() {
        if (!isLoggedIn()) return $();

        var $right = $('#clbi-right-sidebar');
        if (!$right.length) return $();

        var $panel = $('#progress-panel');

        if (!$panel.length) {
            $panel = $(getPanelHtml());
            if (!placePanel($panel)) return $();
            setPanelSync($panel);
        } else {
            $panel.addClass('profile-progress-block');
            placePanel($panel);

            if (!currentSummary && $panel.attr('data-progress-state') !== 'syncing') {
                setPanelSync($panel);
            }
        }

        return $('#progress-panel');
    }

    function clampPercent(value) {
        return Math.max(0, Math.min(100, value || 0));
    }

    function hasXpNotification(items) {
        if (!items || !items.length) return false;
        return items.some(function (item) {
            return item && item.type === 'xp' && parseInt(item.amount || 0, 10) > 0;
        });
    }

    function clearBarTimers() {
        [barTimerA, barTimerB, barTimerC].forEach(function (timer) {
            if (timer) clearTimeout(timer);
        });
        barTimerA = null;
        barTimerB = null;
        barTimerC = null;
    }

    function setBarInstant($fill, $gain, percent) {
        clearBarTimers();
        percent = clampPercent(percent);
        $fill.css({ transition: 'none', width: percent + '%' });
        $gain.css({ transition: 'none', left: '0%', width: '0%', opacity: 0 });
        if ($fill[0]) $fill[0].offsetHeight;
        $fill.css({ transition: '' });
        $gain.css({ transition: '' });
    }

    function animateGain($fill, $gain, fromPercent, toPercent, levelChanged) {
        clearBarTimers();

        fromPercent = clampPercent(fromPercent);
        toPercent = clampPercent(toPercent);

        $fill.css({ transition: 'none', width: fromPercent + '%' });

        if (levelChanged) {
            var firstDelta = Math.max(0, 100 - fromPercent);

            $gain.css({
                transition: 'none',
                opacity: firstDelta > 0 ? 1 : 0,
                left: fromPercent + '%',
                width: firstDelta + '%'
            });

            if ($fill[0]) $fill[0].offsetHeight;

            barTimerA = setTimeout(function () {
                $fill.css({
                    transition: 'width 540ms cubic-bezier(0.22, 0.7, 0.18, 1)',
                    width: '100%'
                });
            }, 260);

            barTimerB = setTimeout(function () {
                $fill.css({ transition: 'none', width: '0%' });
                $gain.css({ transition: 'none', opacity: toPercent > 0 ? 1 : 0, left: '0%', width: toPercent + '%' });

                if ($fill[0]) $fill[0].offsetHeight;

                $fill.css({
                    transition: 'width 460ms cubic-bezier(0.22, 0.7, 0.18, 1)',
                    width: toPercent + '%'
                });
            }, 860);

            barTimerC = setTimeout(function () {
                $gain.css({ transition: 'opacity 180ms ease', opacity: 0 });
            }, 1380);

            return;
        }

        var delta = Math.max(0, toPercent - fromPercent);

        if (delta <= 0.15) {
            setBarInstant($fill, $gain, toPercent);
            return;
        }

        $gain.css({
            transition: 'none',
            opacity: 1,
            left: fromPercent + '%',
            width: delta + '%'
        });

        if ($fill[0]) $fill[0].offsetHeight;

        barTimerA = setTimeout(function () {
            $fill.css({
                transition: 'width 560ms cubic-bezier(0.22, 0.7, 0.18, 1)',
                width: toPercent + '%'
            });
        }, 260);

        barTimerB = setTimeout(function () {
            $gain.css({ transition: 'opacity 180ms ease', opacity: 0 });
        }, 940);
    }

    function updatePanel(summary, options) {
        if (!summary) return;

        options = options || {};

        var $panel = ensurePanel();
        if (!$panel.length) {
            pendingSummary = $.extend({}, summary);
            pendingOptions = $.extend({}, options);
            return;
        }

        var level = summary.level || 1;
        var totalXp = summary.totalXp || 0;
        var xpIntoLevel = summary.xpIntoLevel || 0;
        var xpForNext = summary.xpForNextLevel || 1;
        var percent = clampPercent(summary.progressPercent);
        var isMaxLevel = !!summary.isMaxLevel;
        var dailyXp = summary.dailyXp || 0;
        var discoveries = summary.discoveryCount || 0;
        var title = summary.equippedTitle || summary.title || '';

        $panel.removeClass('is-syncing').toggleClass('is-max-level', isMaxLevel).attr('data-progress-state', 'ready');
        $panel.find('.progress-level-label').text((isMaxLevel ? 'MAX ' : 'LVL ') + level);
        $panel.find('.progress-total-xp').text(totalXp + ' XP');
        $panel.find('.progress-xp-next').text(isMaxLevel ? 'MAX LEVEL' : (xpIntoLevel + ' / ' + xpForNext + ' TO NEXT'));
        $panel.find('.progress-daily-xp').text('TODAY ' + dailyXp + ' XP');
        $panel.find('.progress-discovery-row').text('DISCOVERED ' + discoveries);

        var $title = $panel.find('.progress-title-row');
        if (title) {
            $title.text(title).prop('hidden', false);
        } else {
            $title.text('').prop('hidden', true);
        }

        var $fill = $panel.find('.progress-xp-fill');
        var $gain = $panel.find('.progress-xp-gain');
        var animate = !!options.animateGain && currentSummary && totalXp > (currentSummary.totalXp || 0);

        if (animate) {
            animateGain(
                $fill,
                $gain,
                clampPercent(currentSummary.progressPercent),
                percent,
                level !== (currentSummary.level || 1)
            );
        } else {
            setBarInstant($fill, $gain, percent);
        }

        currentSummary = $.extend({}, summary);
        pendingSummary = null;
        pendingOptions = null;
        if (summaryRetryTimer) {
            clearTimeout(summaryRetryTimer);
            summaryRetryTimer = null;
        }
        summaryRetryAttempts = 0;
    }

    function clearSummaryRetry() {
        if (summaryRetryTimer) clearTimeout(summaryRetryTimer);
        summaryRetryTimer = null;
        summaryRetryAttempts = 0;
    }

    function scheduleSummaryRetry(delay) {
        if (!isLoggedIn()) return;
        if (summaryRetryTimer) return;
        if (summaryRetryAttempts >= 12) return;

        summaryRetryAttempts += 1;
        summaryRetryTimer = setTimeout(function () {
            summaryRetryTimer = null;
            requestSummary();
        }, delay || 1800);
    }

    function requestSummary() {
        if (!isLoggedIn()) return;
        if (summaryRequested) return;

        summaryRequested = true;

        withApi(function (api) {
            api.get({
                action: 'progress_summary',
                format: 'json',
                formatversion: 2
            }).then(function (data) {
                var payload = data && data.progress_summary;
                if (payload && payload.available && payload.summary) {
                    clearSummaryRetry();
                    updatePanel(payload.summary, { animateGain: false });
                } else {
                    scheduleSummaryRetry(2200);
                }
            }).catch(function () {
                scheduleSummaryRetry(2200);
            }).always(function () {
                summaryRequested = false;
            });
        }, function () {
            summaryRequested = false;
            scheduleSummaryRetry(2200);
        });
    }

    function queueNotifications(items) {
        if (!items || !items.length) return;

        items.forEach(function (item) {
            if (!item) return;
            notificationQueue.push(item);
        });

        showNextNotification();
    }

    function notificationText(item) {
        if (item.type === 'xp') {
            return '+' + (item.amount || 0) + ' XP · ' + (item.label || '문서 열람');
        }

        if (item.type === 'achievement') {
            var xp = item.amount ? ' · +' + item.amount + ' XP' : '';
            return '업적 달성 · ' + (item.label || '새 업적') + xp;
        }

        if (item.type === 'level') {
            return item.label || '레벨 상승';
        }

        return item.label || '보상 획득';
    }

    function showNextNotification() {
        if (notificationActive) return;
        if (!notificationQueue.length) return;

        notificationActive = true;
        var item = notificationQueue.shift();
        var $root = $('#progress-toast-root');

        if (!$root.length) {
            $('body').append('<div id="progress-toast-root"></div>');
            $root = $('#progress-toast-root');
        }

        var $toast = $('<div class="progress-toast"></div>');
        $toast.text(notificationText(item));
        $root.append($toast);

        requestAnimationFrame(function () {
            $toast.addClass('is-visible');
        });

        setTimeout(function () {
            $toast.removeClass('is-visible');
            setTimeout(function () {
                $toast.remove();
                notificationActive = false;
                showNextNotification();
            }, 220);
        }, 2600);
    }

    function applyPendingSummaryIfPossible() {
        if (!pendingSummary) return;
        updatePanel(pendingSummary, pendingOptions || { animateGain: false });
    }

    function handlePageView() {
        ensurePanel();
        applyPendingSummaryIfPossible();

        if (!isRewardableClientSide()) {
            requestSummary();
            return;
        }

        var pageId = getPageId();
        if (handledPageIds.has(pageId)) {
            requestSummary();
            return;
        }

        if (inFlightPageIds.has(pageId)) {
            requestSummary();
            return;
        }

        inFlightPageIds.add(pageId);

        withApi(function (api) {
            api.postWithToken('csrf', {
                action: 'progress_view',
                format: 'json',
                formatversion: 2,
                errorformat: 'plaintext',
                pageid: pageId
            }).then(function (data) {
                var payload = data && data.progress_view;
                if (!payload) return;

                handledPageIds.add(pageId);

                var animate = hasXpNotification(payload.notifications);

                if (payload.summary) {
                    updatePanel(payload.summary, { animateGain: animate });
                }

                if (payload.notifications && payload.notifications.length) {
                    queueNotifications(payload.notifications);
                }
            }).catch(function () {
                requestSummary();
            }).always(function () {
                inFlightPageIds.delete(pageId);
            });
        }, function () {
            inFlightPageIds.delete(pageId);
            requestSummary();
        });
    }

    function bindVisibilitySync() {
        if (visibilityBound) return;
        visibilityBound = true;

        document.addEventListener('visibilitychange', function () {
            if (document.visibilityState === 'visible') {
                requestSummary();
            }
        });
    }

    function bootProgressSystem(reason) {
        ensurePanel();
        applyPendingSummaryIfPossible();

        if (isRewardableClientSide()) {
            handlePageView();
        } else {
            requestSummary();
        }

        setTimeout(function () {
            ensurePanel();
            applyPendingSummaryIfPossible();
            requestSummary();
        }, 350);

        setTimeout(function () {
            ensurePanel();
            applyPendingSummaryIfPossible();
            requestSummary();
        }, 1500);
    }

    function handleSpaPageView() {
        ensurePanel();
        applyPendingSummaryIfPossible();

        requestAnimationFrame(function () {
            setTimeout(function () {
                handlePageView();
            }, 80);
        });
    }

    function applySummary(summary, options) {
        updatePanel(summary, options || { animateGain: false });
    }

    window.ProgressSystemWebUi = {
        boot: bootProgressSystem,
        requestSummary: requestSummary,
        applySummary: applySummary,
        handlePageView: handlePageView,
        handleSpaPageView: handleSpaPageView,
        ensurePanel: ensurePanel
    };

    $(function () {
        bindVisibilitySync();
        bootProgressSystem('documentReady');
    });

    mw.hook('wikipage.content').add(function () {
        ensurePanel();
        applyPendingSummaryIfPossible();
        setTimeout(function () {
            ensurePanel();
            applyPendingSummaryIfPossible();
            requestSummary();
        }, 120);
    });
})(mediaWiki, jQuery);


/* CLBI Nations / Historical Events year tabs
 * Mirrors the country information panel model:
 * active tab uses .is-active/aria-selected and inactive pages use hidden.
 */
(function (mw, $) {
    'use strict';

    function activateClbiNationsHistoryYear(panel, targetYear) {
        var tabs;
        var pages;

        if (!panel || !targetYear) return false;

        tabs = Array.prototype.slice.call(panel.querySelectorAll('.clbi-nations-history-year-button[data-year]'));
        pages = Array.prototype.slice.call(panel.querySelectorAll('.clbi-nations-history-page[data-year-panel]'));

        if (!tabs.length || !pages.length) return false;

        tabs.forEach(function (tab) {
            var active = tab.getAttribute('data-year') === targetYear;
            tab.classList.toggle('is-active', active);
            tab.setAttribute('aria-selected', active ? 'true' : 'false');
            tab.setAttribute('tabindex', active ? '0' : '-1');
        });

        pages.forEach(function (page) {
            var active = page.getAttribute('data-year-panel') === targetYear;
            page.classList.toggle('is-active', active);

            if (active) {
                page.removeAttribute('hidden');
            } else {
                page.setAttribute('hidden', 'hidden');
            }
        });

        return true;
    }

    function moveClbiNationsHistoryYear(panel, direction) {
        var tabs;
        var activeIndex;
        var nextIndex;
        var target;

        if (!panel) return false;

        tabs = Array.prototype.slice.call(panel.querySelectorAll('.clbi-nations-history-year-button[data-year]'));
        if (!tabs.length) return false;

        activeIndex = tabs.findIndex(function (tab) {
            return tab.classList.contains('is-active') || tab.getAttribute('aria-selected') === 'true';
        });

        if (activeIndex < 0) activeIndex = 0;

        nextIndex = (activeIndex + direction + tabs.length) % tabs.length;
        target = tabs[nextIndex].getAttribute('data-year');

        if (activateClbiNationsHistoryYear(panel, target)) {
            tabs[nextIndex].focus();
            return true;
        }

        return false;
    }

    function initClbiNationsHistoryYearTabs(root) {
        var scope = root && root.querySelectorAll ? root : document;
        var panels = scope.querySelectorAll('.clbi-nations-history-panel');

        Array.prototype.forEach.call(panels, function (panel) {
            if (panel.getAttribute('data-clbi-history-tabs-ready') === '1') return;

            panel.setAttribute('data-clbi-history-tabs-ready', '1');

            panel.addEventListener('click', function (event) {
                var tab = event.target.closest ? event.target.closest('.clbi-nations-history-year-button[data-year]') : null;

                if (!tab || !panel.contains(tab)) return;

                if (activateClbiNationsHistoryYear(panel, tab.getAttribute('data-year'))) {
                    event.preventDefault();
                }
            });

            panel.addEventListener('keydown', function (event) {
                var tab = event.target.closest ? event.target.closest('.clbi-nations-history-year-button[data-year]') : null;
                var handled = false;

                if (!tab || !panel.contains(tab)) return;

                if (event.key === 'ArrowLeft') handled = moveClbiNationsHistoryYear(panel, -1);
                else if (event.key === 'ArrowRight') handled = moveClbiNationsHistoryYear(panel, 1);
                else if (event.key === 'Home') handled = activateClbiNationsHistoryYear(panel, (panel.querySelector('.clbi-nations-history-year-button[data-year]') || {}).getAttribute && panel.querySelector('.clbi-nations-history-year-button[data-year]').getAttribute('data-year'));
                else if (event.key === 'End') {
                    var tabs = panel.querySelectorAll('.clbi-nations-history-year-button[data-year]');
                    var last = tabs[tabs.length - 1];
                    handled = last ? activateClbiNationsHistoryYear(panel, last.getAttribute('data-year')) : false;
                    if (handled) last.focus();
                }

                if (handled) {
                    event.preventDefault();
                    event.stopPropagation();
                }
            });
        });
    }

    window.initClbiNationsHistoryYearTabs = initClbiNationsHistoryYearTabs;

    $(function () {
        initClbiNationsHistoryYearTabs(document);
    });

    if (mw && mw.hook) {
        mw.hook('wikipage.content').add(function ($content) {
            initClbiNationsHistoryYearTabs($content && $content[0] ? $content[0] : document);
        });
    }
})(mediaWiki, jQuery);


/* =========================================
   Decoration runtime renderer
   ========================================= */
(function (mw) {
    'use strict';

    var REGISTRY_TITLE = 'MediaWiki:Decorations.json';
    var RENDERED_ATTR = 'data-wiki-decoration-rendered';
    var HOST_ATTR = 'data-wiki-decoration-host';
    var MAIN_PAGE_PLACEMENT = 'main-body-well';
    var MAIN_PAGE_TARGET = '.main-portal .main-body-well';
    var runtimeToken = 0;
    var lastRegistry = null;
    var lastRenderedPageKey = '';
    var scheduledRender = 0;
    var nationsPlacementObserver = null;
    var observedNationsStack = null;
    var mainPagePlacementObserver = null;
    var mainPagePlacementMutationObserver = null;
    var observedMainPagePortal = null;
    var scheduledMainPageRebase = 0;
    var pixelAssetCache = {};
    var pixelCanvasCache = {};

    function normalizePageName(value) {
        return String(value || '')
            .split('?')[0]
            .replace(/^\/index\.php\//, '')
            .replace(/_/g, ' ')
            .trim();
    }

    function currentPageKey() {
        var raw = mw && mw.config ? String(mw.config.get('wgPageName') || '') : '';
        return normalizePageName(raw) || raw || '대문';
    }

    function ensureMainPageBodyWell() {
        var portal;
        var topMount;
        var panel;
        var well;
        var manifesto;

        if (currentPageKey() !== '대문') return null;

        portal = document.querySelector('.main-portal');
        if (!portal) return null;

        topMount = portal.querySelector('[data-component="category-nav"]');
        panel = portal.querySelector('.main-body-panel');
        well = portal.querySelector('.main-body-well');
        manifesto = portal.querySelector('.main-manifesto');

        if (!panel) {
            panel = document.createElement('div');
            panel.className = 'main-body-panel';
            panel.setAttribute('data-main-body-panel-generated', '1');

            if (topMount && topMount.parentNode) {
                if (topMount.nextSibling) {
                    topMount.parentNode.insertBefore(panel, topMount.nextSibling);
                } else {
                    topMount.parentNode.appendChild(panel);
                }
            } else {
                portal.appendChild(panel);
            }
        }

        if (!well) {
            well = document.createElement('div');
            well.className = 'main-body-well';
            well.setAttribute('data-main-body-well-generated', '1');
            panel.appendChild(well);
        } else if (well.parentNode !== panel) {
            panel.appendChild(well);
        }

        if (manifesto && manifesto.parentNode !== well) {
            well.insertBefore(manifesto, well.firstChild);
        }

        return well;
    }


    function cssAttrEscape(value) {
        return String(value || '').replace(/\\/g, '\\\\').replace(/"/g, '\\"');
    }

    function getActiveNationsEra() {
        var content = document.querySelector('.clbi-nations-era-content.is-active[data-era-content]:not([hidden])');
        var title;
        var globe;

        if (content) return content.getAttribute('data-era-content') || '';

        title = document.querySelector('.clbi-nations-era-title-plate.is-active[data-era]');
        if (title) return title.getAttribute('data-era') || '';

        globe = document.querySelector('.clbi-nations-globe-window[data-nations-globe]');
        if (globe) {
            return globe.getAttribute('data-current-era') || globe.getAttribute('data-nations-current-era') || globe.getAttribute('data-era-year') || '';
        }

        return '';
    }

    function getActiveNationsEraPanel() {
        var era = getActiveNationsEra();
        var selector;
        if (!era) return document.querySelector('.clbi-nations-era-content.is-active[data-era-content]:not([hidden])');
        selector = '.clbi-nations-era-content[data-era-content="' + cssAttrEscape(era) + '"]';
        return document.querySelector(selector) || document.querySelector('.clbi-nations-era-content.is-active[data-era-content]:not([hidden])');
    }

    function getActiveNationsContinent() {
        var eraPanel = getActiveNationsEraPanel();
        var root = eraPanel || document;
        var tab = root.querySelector('.clbi-nations-tabpanel-tab.is-active[data-continent], .clbi-nations-tabpanel-tab[aria-selected="true"][data-continent]');
        var panel;

        if (tab) return tab.getAttribute('data-continent') || '';

        panel = root.querySelector('.clbi-nations-tabpanel-continent.is-active[data-continent-panel]');
        if (panel) return panel.getAttribute('data-continent-panel') || '';

        return '';
    }

    function getDecorationNationsBodySelector(era) {
        if (era) {
            return '.clbi-nations-era-content[data-era-content="' + cssAttrEscape(era) + '"] .clbi-nations-tabpanel-body';
        }
        return '.clbi-nations-era-content.is-active[data-era-content]:not([hidden]) .clbi-nations-tabpanel-body, .clbi-nations-tabpanel-body';
    }

    /*
    Decoration semantic placement resolver
    -----------------------------------------
    장식 저장 데이터의 placement 값은 "사용자가 고른 의미상 위치"를 나타낸다.
    resolver는 그 의미값을 실제 DOM 부착 위치와 표시 조건으로 번역한다.

    예: 시대 문서에서 사용자가 1950년 / 아메리카를 지정하면 의미상 scope는
    그 조합이지만, 이미지를 붙일 기준면은 대륙 패널 자체가 아니라
    .clbi-nations-tabpanel-body이다. 따라서 placement=nations-continent-body는
    .clbi-nations-tabpanel-body에 이미지를 붙이고, 현재 활성 연도와 대륙이 저장값과
    일치할 때만 렌더링한다.

    유지보수 규칙:
    - 새 조합형 문서가 생기면 entry.target을 매번 특수하게 저장하지 말고 placement를 추가한다.
    - DevTools.js 에디터 미리보기와 Common.js 런타임 렌더러의 resolver는 같은 의미를 가져야 한다.
    - target은 물리적 기준면, era/continent 같은 필드는 표시 조건으로 다룬다.
    */
    function shouldUseNationsBodyPlacement(entry) {
        var placement = String(entry && entry.placement || '').trim();
        var target = String(entry && entry.target || '').trim();
        var era = String(entry && entry.era || '').trim();
        var continent = String(entry && entry.continent || '').trim();

        if (!document.querySelector('.clbi-nations-panel-stack')) return false;
        if (placement === 'nations-continent-body') return true;
        if (era || continent) return true;
        if (target.indexOf('clbi-nations-tabpanel-continent') !== -1) return true;
        return false;
    }

    function resolveDecorationPlacement(entry) {
        var placement = String(entry && entry.placement || '').trim();
        var selector = String(entry && entry.target || '').trim() || '.liberty-content-main';
        var era = String(entry && entry.era || '').trim();
        var continent = String(entry && entry.continent || '').trim();
        var target;

        if (!placement && shouldUseNationsBodyPlacement(entry)) {
            placement = 'nations-continent-body';
        }

        if (placement === 'boot-gate' || placement === 'loading-screen') {
            selector = '#boot-gate-screen .boot-gate-decoration-layer, #boot-gate-screen';
            target = document.querySelector(selector);
            return {
                placement: placement,
                target: target,
                targetSelector: selector,
                visible: !!document.getElementById('boot-gate-screen')
            };
        }

        if (placement === 'nations-continent-body') {
            selector = getDecorationNationsBodySelector(era);
            target = document.querySelector(selector) || document.querySelector('.clbi-nations-tabpanel-body') || document.querySelector(String(entry && entry.target || '').trim());
            return {
                placement: placement,
                target: target,
                targetSelector: selector,
                visible: (!era || era === getActiveNationsEra()) && (!continent || continent === getActiveNationsContinent())
            };
        }

        /*
        대문의 일반 장식은 저장된 target과 관계없이 본문 우물 안에서 렌더링한다.
        우물이 overflow:hidden이므로 #1d1d1d 프레임 밖으로 나갈 수 없다.
        boot/loading 및 국가 패널 전용 placement는 위 분기에서 기존 동작을 유지한다.
        */
        var mainPageWell = ensureMainPageBodyWell();
        if (mainPageWell) {
            return {
                placement: MAIN_PAGE_PLACEMENT,
                target: mainPageWell,
                targetSelector: MAIN_PAGE_TARGET,
                visible: true
            };
        }

        return {
            placement: placement,
            target: document.querySelector(selector),
            targetSelector: selector,
            visible: true
        };
    }

    function normalizeNumber(value, fallback) {
        var n = parseFloat(value);
        return Number.isFinite(n) ? n : fallback;
    }

    function normalizeBool(value, fallback) {
        if (value === true || value === 'true' || value === '1' || value === 1) return true;
        if (value === false || value === 'false' || value === '0' || value === 0) return false;
        return fallback;
    }

    function normalizeSrc(src) {
        src = String(src || '').trim();
        if (!src) return '';
        if (/^(?:https?:)?\/\//i.test(src) || src.charAt(0) === '/' || src.indexOf('data:') === 0 || src.indexOf('blob:') === 0) return src;
        return '/index.php/Special:Redirect/file/' + encodeURIComponent(src);
    }


    function normalizeAssetType(entry) {
        var type = String(entry && entry.assetType || '').trim().toLowerCase();
        var ref = String(entry && (entry.asset || entry.src) || '').trim();

        if (type === 'clbi-pixel-json' || type === 'pixel-rle' || type === 'pixel-json') return 'pixel-json';
        if (!type && /\.json(?:[?#].*)?$/i.test(ref)) return 'pixel-json';
        return type || 'image';
    }

    function isPixelJsonDecoration(entry) {
        return normalizeAssetType(entry) === 'pixel-json';
    }

    function getPixelJsonRef(entry) {
        return String(entry && (entry.asset || entry.src) || '').trim();
    }

    function normalizePixelJsonUrl(ref) {
        ref = String(ref || '').trim();
        if (!ref) return '';
        if (/^(?:https?:)?\/\//i.test(ref) || ref.charAt(0) === '/' || ref.indexOf('data:') === 0 || ref.indexOf('blob:') === 0) return ref;
        if (/^(?:file|파일):/i.test(ref)) return '/index.php/Special:Redirect/file/' + encodeURIComponent(ref.replace(/^(?:file|파일):/i, ''));
        if (mw && mw.util && typeof mw.util.getUrl === 'function') {
            if (ref.indexOf(':') !== -1) {
                return mw.util.getUrl(ref, { action: 'raw', ctype: 'application/json' });
            }
            return mw.util.getUrl('MediaWiki:' + ref, { action: 'raw', ctype: 'application/json' });
        }
        return ref;
    }

    function parsePixelColor(value) {
        var text;
        var m;
        if (Array.isArray(value)) {
            return [
                Math.max(0, Math.min(255, Number(value[0]) || 0)),
                Math.max(0, Math.min(255, Number(value[1]) || 0)),
                Math.max(0, Math.min(255, Number(value[2]) || 0)),
                value.length > 3 ? Math.max(0, Math.min(255, Number(value[3]) || 0)) : 255
            ];
        }
        text = String(value || '').trim();
        m = text.match(/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);
        if (!m) return [0, 0, 0, 0];
        text = m[1];
        if (text.length === 3 || text.length === 4) {
            return [
                parseInt(text.charAt(0) + text.charAt(0), 16),
                parseInt(text.charAt(1) + text.charAt(1), 16),
                parseInt(text.charAt(2) + text.charAt(2), 16),
                text.length === 4 ? parseInt(text.charAt(3) + text.charAt(3), 16) : 255
            ];
        }
        return [
            parseInt(text.slice(0, 2), 16),
            parseInt(text.slice(2, 4), 16),
            parseInt(text.slice(4, 6), 16),
            text.length === 8 ? parseInt(text.slice(6, 8), 16) : 255
        ];
    }


    function decodePixelRle36(value) {
        var text = String(value || '').trim();
        var parts;
        var runs = [];
        var i;
        var x;
        var y;
        var len;
        var colorIndex;

        if (!text) return runs;
        parts = text.split(',');
        for (i = 0; i + 3 < parts.length; i += 4) {
            x = parseInt(parts[i], 36);
            y = parseInt(parts[i + 1], 36);
            len = parseInt(parts[i + 2], 36);
            colorIndex = parseInt(parts[i + 3], 36);
            if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(len) || !Number.isFinite(colorIndex)) continue;
            runs.push([x, y, len, colorIndex]);
        }
        return runs;
    }

    function normalizePixelAsset(doc) {
        var encoding = String(doc && (doc.encoding || doc.e) || '').trim().toLowerCase();
        var width = Math.round(Number(doc && (doc.width || doc.w)) || 0);
        var height = Math.round(Number(doc && (doc.height || doc.h)) || 0);
        var paletteSource = Array.isArray(doc && doc.palette) ? doc.palette : (Array.isArray(doc && doc.p) ? doc.p : []);
        var palette = paletteSource.map(parsePixelColor);
        var runs;

        /*
        CLBI Pixel Forge v0.2.3 compact format:
        - MediaWiki 단일 문서 크기 제한을 피하기 위해 사람이 읽기 쉬운 [[x,y,len,c], ...] 배열 대신
          base36 토큰 문자열을 쓴다.
        - 형식은 x,y,len,colorIndex를 4개 토큰 단위로 반복한 rle36이다.
        - 복원 후 좌표계는 기존 runs 배열과 완전히 같으며, 최종 CSS px에 1:1로 찍는다.
        */
        if ((encoding === 'rle36' || encoding === 'clbi-rle36') && typeof (doc && doc.r) === 'string') {
            runs = decodePixelRle36(doc.r);
        } else {
            runs = Array.isArray(doc && doc.runs) ? doc.runs : [];
        }

        if (!width || !height || width < 1 || height < 1) throw new Error('invalid pixel decoration size');
        if (width > 8192 || height > 8192) throw new Error('pixel decoration too large');
        return {
            type: String(doc && (doc.type || doc.t) || 'clbi-pixel-decoration'),
            version: Number(doc && (doc.version || doc.v)) || 1,
            encoding: encoding || 'runs',
            width: width,
            height: height,
            palette: palette,
            runs: runs
        };
    }

    function fetchPixelAsset(ref) {
        var url = normalizePixelJsonUrl(ref);
        var cached;
        if (!url) return Promise.reject(new Error('pixel json ref is empty'));
        cached = pixelAssetCache[url];
        if (cached) return cached.promise;
        cached = {
            promise: fetch(url, { credentials: 'same-origin', cache: 'force-cache' })
                .then(function (response) {
                    if (!response.ok) throw new Error('HTTP ' + response.status);
                    return response.json();
                })
                .then(normalizePixelAsset)
        };
        pixelAssetCache[url] = cached;
        return cached.promise;
    }

    function drawPixelAssetToCanvas(canvas, asset) {
        var ctx;
        var image;
        var data;
        var i;
        var run;
        var x;
        var y;
        var len;
        var color;
        var colorIndex;
        var p;
        var k;

        canvas.width = asset.width;
        canvas.height = asset.height;
        ctx = canvas.getContext('2d');
        ctx.imageSmoothingEnabled = false;
        image = ctx.createImageData(asset.width, asset.height);
        data = image.data;

        for (i = 0; i < asset.runs.length; i += 1) {
            run = asset.runs[i];
            if (!Array.isArray(run) || run.length < 4) continue;
            x = Math.round(Number(run[0]) || 0);
            y = Math.round(Number(run[1]) || 0);
            len = Math.round(Number(run[2]) || 0);
            colorIndex = Math.round(Number(run[3]) || 0);
            color = asset.palette[colorIndex];
            if (!color || len <= 0 || y < 0 || y >= asset.height || x >= asset.width) continue;
            if (x < 0) {
                len += x;
                x = 0;
            }
            len = Math.min(len, asset.width - x);
            for (k = 0; k < len; k += 1) {
                p = ((y * asset.width) + x + k) * 4;
                data[p] = color[0];
                data[p + 1] = color[1];
                data[p + 2] = color[2];
                data[p + 3] = color[3];
            }
        }

        ctx.putImageData(image, 0, 0);
    }

    function preparePixelCanvas(ref) {
        var url = normalizePixelJsonUrl(ref);
        var cached;
        if (!url) return Promise.reject(new Error('pixel json ref is empty'));
        cached = pixelCanvasCache[url];
        if (cached) return cached.promise;
        cached = {};
        cached.promise = fetchPixelAsset(ref).then(function (asset) {
            var canvas = document.createElement('canvas');
            drawPixelAssetToCanvas(canvas, asset);
            canvas.style.imageRendering = 'pixelated';
            canvas.setAttribute('data-decoration-asset-size', asset.width + 'x' + asset.height);
            cached.canvas = canvas;
            cached.width = asset.width;
            cached.height = asset.height;
            return canvas;
        });
        pixelCanvasCache[url] = cached;
        return cached.promise;
    }

    function getPreparedPixelCanvasSync(ref) {
        var url = normalizePixelJsonUrl(ref);
        var cached = url ? pixelCanvasCache[url] : null;
        return cached && cached.canvas ? cached.canvas : null;
    }

    function queryDecorationTarget(selector) {
        selector = String(selector || '').trim();
        if (!selector) return null;
        try {
            return document.querySelector(selector);
        } catch (err) {
            return null;
        }
    }

    function usesCanonicalMainPageCoordinates(entry, actualTarget) {
        var placement = String(entry && entry.placement || '').trim();
        var selector = String(entry && entry.target || '').trim();
        var declaredTarget;

        if (placement === MAIN_PAGE_PLACEMENT) return true;
        if (!actualTarget || !selector) return false;

        declaredTarget = queryDecorationTarget(selector);
        return declaredTarget === actualTarget;
    }

    function getDecorationLocalPosition(entry, actualTarget) {
        var x = normalizeNumber(entry && entry.x, 0);
        var y = normalizeNumber(entry && entry.y, 0);
        var sourceX = x;
        var sourceY = y;
        var sourceSelector;
        var sourceTarget;
        var sourceRect;
        var actualRect;
        var sourceOriginX;
        var sourceOriginY;
        var actualOriginX;
        var actualOriginY;

        /*
        대문 데코 좌표 보존
        -----------------------------------------
        저장된 x/y는 기존 entry.target 좌표계를 기준으로 만들어졌다.
        데코를 main-body-well 안으로 옮길 때 x/y를 그대로 적용하면
        더 아래에서 시작하는 새 좌표계 때문에 장식이 바닥으로 밀린다.

        실제 화면상의 위치는 유지하고 부모만 우물로 바꾼다.
        기존 기준면의 padding-box 원점과 새 우물의 padding-box 원점 차이를
        정수 px로 더해 새 로컬 좌표를 만든다.
        */
        if (
            currentPageKey() === '대문' &&
            actualTarget &&
            actualTarget.classList &&
            actualTarget.classList.contains('main-body-well') &&
            !usesCanonicalMainPageCoordinates(entry, actualTarget)
        ) {
            sourceSelector = String(entry && entry.target || '').trim() ||
                '.liberty-content-main';
            sourceTarget = queryDecorationTarget(sourceSelector) ||
                document.querySelector('.liberty-content-main') ||
                document.querySelector('.main-portal');

            if (sourceTarget && sourceTarget !== actualTarget) {
                sourceRect = sourceTarget.getBoundingClientRect();
                actualRect = actualTarget.getBoundingClientRect();

                sourceOriginX = sourceRect.left + normalizeNumber(sourceTarget.clientLeft, 0);
                sourceOriginY = sourceRect.top + normalizeNumber(sourceTarget.clientTop, 0);
                actualOriginX = actualRect.left + normalizeNumber(actualTarget.clientLeft, 0);
                actualOriginY = actualRect.top + normalizeNumber(actualTarget.clientTop, 0);

                x += Math.round(sourceOriginX - actualOriginX);
                y += Math.round(sourceOriginY - actualOriginY);
            }
        }

        return {
            x: Math.round(x),
            y: Math.round(y),
            sourceX: Math.round(sourceX),
            sourceY: Math.round(sourceY),
            sourceSelector: sourceSelector || ''
        };
    }

    function applyDecorationBaseStyle(node, entry, actualTarget) {
        var position = getDecorationLocalPosition(entry, actualTarget);

        node.style.left = position.x + 'px';
        node.style.top = position.y + 'px';
        node.style.opacity = String(normalizeNumber(entry.opacity, 1));
        node.style.zIndex = String(Math.round(normalizeNumber(entry.zIndex, 0)));
        node.style.pointerEvents = String(entry.pointerEvents || 'none');

        if (position.sourceSelector) {
            node.setAttribute('data-decoration-coordinate-source', position.sourceSelector);
            node.setAttribute('data-decoration-source-x', String(position.sourceX));
            node.setAttribute('data-decoration-source-y', String(position.sourceY));
            node.setAttribute('data-decoration-local-x', String(position.x));
            node.setAttribute('data-decoration-local-y', String(position.y));
        }

        if (entry.blendMode) node.style.mixBlendMode = String(entry.blendMode);
        if (entry.filter) node.style.filter = String(entry.filter);
        if (entry.transform) node.style.transform = String(entry.transform);
    }

    function isDecorationNodeActiveForNationsState(node) {
        var era = node ? String(node.getAttribute('data-decoration-era') || '').trim() : '';
        var continent = node ? String(node.getAttribute('data-decoration-continent') || '').trim() : '';
        if (era && era !== getActiveNationsEra()) return false;
        if (continent && continent !== getActiveNationsContinent()) return false;
        return true;
    }

    function setDecorationNodeVisibility(node, visible) {
        if (!node) return;
        visible = visible !== false;
        /* aria-hidden stays true because wiki decorations are purely visual. */
        if (node.hidden !== !visible) node.hidden = !visible;
        if (node.style.display !== (visible ? '' : 'none')) node.style.display = visible ? '' : 'none';
        node.setAttribute('data-decoration-visible', visible ? '1' : '0');
    }

    function updateDecorationVisibility(root) {
        var scope = root && root.querySelectorAll ? root : document;
        var count = 0;
        Array.prototype.forEach.call(scope.querySelectorAll('[' + RENDERED_ATTR + '="1"]'), function (node) {
            setDecorationNodeVisibility(node, isDecorationNodeActiveForNationsState(node));
            count += 1;
        });
        return count;
    }

    function hasRenderedDecorations(root) {
        var scope = root && root.querySelector ? root : document;
        return !!(scope && scope.querySelector && scope.querySelector('[' + RENDERED_ATTR + '="1"]'));
    }

    function applyPixelJsonDecoration(entry, target, visible) {
        var ref = getPixelJsonRef(entry);
        var template;
        var canvas;
        var ctx;
        if (!ref) return false;

        function makeCanvasFromTemplate(source) {
            var out = document.createElement('canvas');
            var outCtx;
            out.className = 'wiki-decoration wiki-decoration-pixel-json';
            out.setAttribute(RENDERED_ATTR, '1');
            out.setAttribute('aria-hidden', 'true');
            out.setAttribute('data-decoration-id', String(entry.id || ''));
            out.setAttribute('data-decoration-asset-type', 'pixel-json');
            if (entry.placement) out.setAttribute('data-decoration-placement', String(entry.placement));
            if (entry.era) out.setAttribute('data-decoration-era', String(entry.era));
            if (entry.continent) out.setAttribute('data-decoration-continent', String(entry.continent));
            out.width = source.width;
            out.height = source.height;
            out.style.imageRendering = 'pixelated';
            out.style.width = source.width + 'px';
            out.style.height = source.height + 'px';
            out.setAttribute('data-decoration-asset-size', source.width + 'x' + source.height);
            outCtx = out.getContext('2d');
            outCtx.imageSmoothingEnabled = false;
            outCtx.drawImage(source, 0, 0);
            applyDecorationBaseStyle(out, entry, target);
            setDecorationNodeVisibility(out, visible);
            return out;
        }

        template = getPreparedPixelCanvasSync(ref);
        if (template) {
            target.appendChild(makeCanvasFromTemplate(template));
            return true;
        }

        /* Fallback path only.  A full entry pack should prepare the template before the
           normal UI is released, so users should not see a blank decoration canvas. */
        preparePixelCanvas(ref).then(function (source) {
            if (!target || !target.parentNode || !source) return;
            target.appendChild(makeCanvasFromTemplate(source));
        }).catch(function () {});

        return true;
    }

    function preloadPixelAssetsForRegistry(registry) {
        var promises = [];
        decorationList(registry).forEach(function (entry) {
            var ref;
            if (!entry || !matchesPage(entry) || !isPixelJsonDecoration(entry)) return;
            ref = getPixelJsonRef(entry);
            if (!ref) return;
            promises.push(preparePixelCanvas(ref).catch(function () { return null; }));
        });
        return Promise.all(promises);
    }

    function decorationList(registry) {
        if (!registry || typeof registry !== 'object') return [];
        if (Array.isArray(registry)) return registry;
        if (Array.isArray(registry.decorations)) return registry.decorations;
        return [];
    }

    function matchesPage(entry) {
        var page = currentPageKey();
        var underscored = page.replace(/ /g, '_');
        var pages = entry && entry.pages;
        var target = entry && entry.page;
        var i;

        if (normalizeBool(entry && entry.global, false)) return true;
        if (String(entry && entry.placement || '').trim() === 'boot-gate' || String(entry && entry.placement || '').trim() === 'loading-screen') {
            return true;
        }
        if (normalizePageName(target).toLowerCase() === '__boot__' || normalizePageName(target).toLowerCase() === 'loading-screen') return true;
        if (!target && !pages) return true;

        if (Array.isArray(pages)) {
            for (i = 0; i < pages.length; i += 1) {
                if (normalizePageName(pages[i]) === page || String(pages[i] || '') === underscored) return true;
            }
        }

        target = normalizePageName(target);
        return target === page || target === underscored;
    }

    function clearRendered(root) {
        var scope = root && root.querySelectorAll ? root : document;
        Array.prototype.forEach.call(scope.querySelectorAll('[' + RENDERED_ATTR + '="1"]'), function (node) {
            if (node.parentNode) node.parentNode.removeChild(node);
        });
    }

    function ensureHost(target) {
        var style;
        if (!target) return;
        target.setAttribute(HOST_ATTR, '1');
        style = window.getComputedStyle ? window.getComputedStyle(target) : null;
        if (style && style.position === 'static') target.style.position = 'relative';
    }

    function applyDecoration(entry) {
        var resolved;
        var target;
        var src;
        var img;
        var width;
        var height;

        if (!entry || typeof entry !== 'object' || normalizeBool(entry.enabled, true) === false) return false;
        resolved = resolveDecorationPlacement(entry);
        if (!resolved) return false;
        target = resolved.target;
        if (!target) return false;

        ensureHost(target);

        if (isPixelJsonDecoration(entry)) {
            return applyPixelJsonDecoration(entry, target, resolved.visible !== false);
        }

        src = normalizeSrc(entry.src);
        if (!src) return false;

        img = document.createElement('img');
        img.className = 'wiki-decoration';
        img.setAttribute(RENDERED_ATTR, '1');
        img.setAttribute('aria-hidden', 'true');
        img.setAttribute('alt', '');
        img.setAttribute('decoding', 'async');
        img.setAttribute('loading', 'eager');
        img.setAttribute('data-decoration-id', String(entry.id || ''));
        if (entry.placement) img.setAttribute('data-decoration-placement', String(entry.placement));
        if (entry.era) img.setAttribute('data-decoration-era', String(entry.era));
        if (entry.continent) img.setAttribute('data-decoration-continent', String(entry.continent));
        img.src = src;

        applyDecorationBaseStyle(img, entry, target);
        width = normalizeNumber(entry.width, NaN);
        height = normalizeNumber(entry.height, NaN);
        if (Number.isFinite(width) && width > 0) img.style.width = width + 'px';
        if (Number.isFinite(height) && height > 0) img.style.height = height + 'px';
        if (entry.objectFit) img.style.objectFit = String(entry.objectFit);
        setDecorationNodeVisibility(img, resolved.visible !== false);

        target.appendChild(img);
        return true;
    }

    function mainPageLayoutSignature() {
        var source = document.querySelector('.liberty-content-main');
        var well = ensureMainPageBodyWell();
        var sourceRect;
        var wellRect;

        if (!source || !well) return '';
        sourceRect = source.getBoundingClientRect();
        wellRect = well.getBoundingClientRect();

        return [
            Math.round((wellRect.left + normalizeNumber(well.clientLeft, 0)) - (sourceRect.left + normalizeNumber(source.clientLeft, 0))),
            Math.round((wellRect.top + normalizeNumber(well.clientTop, 0)) - (sourceRect.top + normalizeNumber(source.clientTop, 0))),
            Math.round(wellRect.width),
            Math.round(wellRect.height)
        ].join('|');
    }

    function isMainPageDecorationLayoutReady() {
        var portal = document.querySelector('.main-portal');
        var panel = portal && portal.querySelector('.main-body-panel');
        var topMount = portal && portal.querySelector('[data-component="category-nav"]');

        if (!portal || !panel || !ensureMainPageBodyWell()) return false;
        if (!document.body || !document.body.classList.contains('clbi-main-page')) return false;
        if (topMount && !topMount.querySelector('.portal-category-nav')) return false;
        return true;
    }

    function waitForMainPageDecorationLayout() {
        var started;
        var previous = '';
        var stableFrames = 0;

        if (currentPageKey() !== '대문') return Promise.resolve(true);
        started = Date.now();

        return new Promise(function (resolve) {
            function check() {
                var signature = mainPageLayoutSignature();

                if (signature && signature === previous) stableFrames += 1;
                else stableFrames = 0;
                previous = signature;

                if ((isMainPageDecorationLayoutReady() && stableFrames >= 2) || Date.now() - started >= 1200) {
                    resolve(true);
                    return;
                }

                if (window.requestAnimationFrame) window.requestAnimationFrame(check);
                else window.setTimeout(check, 16);
            }

            check();
        });
    }

    function rebaseLegacyMainPageDecorations() {
        var well;

        if (currentPageKey() !== '대문') return;
        well = ensureMainPageBodyWell();
        if (!well) return;

        document.querySelectorAll('[' + RENDERED_ATTR + '="1"][data-decoration-coordinate-source]').forEach(function (node) {
            var position = getDecorationLocalPosition({
                target: node.getAttribute('data-decoration-coordinate-source') || '.liberty-content-main',
                x: normalizeNumber(node.getAttribute('data-decoration-source-x'), 0),
                y: normalizeNumber(node.getAttribute('data-decoration-source-y'), 0)
            }, well);

            node.style.left = position.x + 'px';
            node.style.top = position.y + 'px';
            node.setAttribute('data-decoration-local-x', String(position.x));
            node.setAttribute('data-decoration-local-y', String(position.y));
        });
    }

    function scheduleMainPageDecorationRebase() {
        if (scheduledMainPageRebase) return;
        scheduledMainPageRebase = window.requestAnimationFrame ? window.requestAnimationFrame(function () {
            scheduledMainPageRebase = 0;
            rebaseLegacyMainPageDecorations();
        }) : window.setTimeout(function () {
            scheduledMainPageRebase = 0;
            rebaseLegacyMainPageDecorations();
        }, 0);
    }

    function bindMainPagePlacementRefresh() {
        var portal = document.querySelector('.main-portal');
        var nodes;

        if (currentPageKey() !== '대문' || !portal) {
            if (mainPagePlacementObserver) mainPagePlacementObserver.disconnect();
            if (mainPagePlacementMutationObserver) mainPagePlacementMutationObserver.disconnect();
            observedMainPagePortal = null;
            return;
        }

        if (observedMainPagePortal !== portal) {
            if (mainPagePlacementObserver) mainPagePlacementObserver.disconnect();
            if (mainPagePlacementMutationObserver) mainPagePlacementMutationObserver.disconnect();
            observedMainPagePortal = portal;

            if (typeof ResizeObserver === 'function') {
                mainPagePlacementObserver = new ResizeObserver(scheduleMainPageDecorationRebase);
                nodes = [
                    document.querySelector('.liberty-content-main'),
                    portal,
                    portal.querySelector('[data-component="category-nav"]'),
                    portal.querySelector('.main-body-panel'),
                    portal.querySelector('.main-body-well')
                ];
                nodes.forEach(function (node) {
                    if (node) mainPagePlacementObserver.observe(node);
                });
            }

            /*
            장식 좌표는 크기 변화에만 의존한다. portal subtree DOM 변경을 감시하면
            프레임 SVG와 선언문 애니메이션이 장식 재배치를 반복 호출한다.
            ResizeObserver와 명시적 렌더 시점만 사용한다.
            */
            mainPagePlacementMutationObserver = null;
        }

        scheduleMainPageDecorationRebase();
    }

    function renderForCurrentLayout(registry, token) {
        if (currentPageKey() !== '대문') {
            if (token === runtimeToken) render(registry);
            return Promise.resolve(registry);
        }

        return waitForMainPageDecorationLayout().then(function () {
            if (token === runtimeToken) render(registry);
            return registry;
        });
    }

    function render(registry) {
        var token = runtimeToken;
        lastRegistry = registry || { decorations: [] };
        lastRenderedPageKey = currentPageKey();
        bindNationsPlacementRefresh();
        clearRendered(document);
        decorationList(lastRegistry).forEach(function (entry) {
            if (token === runtimeToken && matchesPage(entry)) applyDecoration(entry);
        });
        bindMainPagePlacementRefresh();
    }

    function renderPrepared() {
        var registry = getPreparedRegistrySync() || lastRegistry;
        var token = runtimeToken;
        if (!registry) return false;
        renderForCurrentLayout(registry, token);
        return true;
    }

    function syncDecorationState() {
        if (lastRenderedPageKey === currentPageKey() && hasRenderedDecorations(document)) {
            updateDecorationVisibility(document);
            return true;
        }
        if (lastRegistry) {
            renderForCurrentLayout(lastRegistry, runtimeToken);
            return true;
        }
        return renderPrepared();
    }

    function scheduleRenderFromCache() {
        if (scheduledRender) return;
        scheduledRender = window.requestAnimationFrame ? window.requestAnimationFrame(function () {
            scheduledRender = 0;
            if (!syncDecorationState()) reload();
        }) : window.setTimeout(function () {
            scheduledRender = 0;
            if (!syncDecorationState()) reload();
        }, 0);
    }

    function scheduleDecorationVisibilityUpdate() {
        if (scheduledRender) return;
        scheduledRender = window.requestAnimationFrame ? window.requestAnimationFrame(function () {
            scheduledRender = 0;
            if (lastRenderedPageKey !== currentPageKey() || !hasRenderedDecorations(document)) {
                if (!syncDecorationState()) reload();
                return;
            }
            updateDecorationVisibility(document);
        }) : window.setTimeout(function () {
            scheduledRender = 0;
            if (lastRenderedPageKey !== currentPageKey() || !hasRenderedDecorations(document)) {
                if (!syncDecorationState()) reload();
                return;
            }
            updateDecorationVisibility(document);
        }, 0);
    }

    function bindNationsPlacementRefresh() {
        var stack = document.querySelector('.clbi-nations-panel-stack');

        if (!stack || observedNationsStack === stack) return;
        observedNationsStack = stack;

        if (nationsPlacementObserver) {
            nationsPlacementObserver.disconnect();
        }

        if (typeof MutationObserver === 'function') {
            nationsPlacementObserver = new MutationObserver(scheduleDecorationVisibilityUpdate);
            nationsPlacementObserver.observe(stack, {
                subtree: true,
                attributes: true,
                attributeFilter: ['class', 'hidden', 'aria-selected', 'data-current-era', 'data-nations-current-era', 'data-era-year']
            });
        }
    }

    function getPreparedRegistrySync() {
        var registry = null;
        var url;
        try {
            if (window.EntryStore && typeof window.EntryStore.getJsonSync === 'function') {
                registry = window.EntryStore.getJsonSync(REGISTRY_TITLE);
                if (!registry && mw && mw.util && typeof mw.util.getUrl === 'function') {
                    url = mw.util.getUrl(REGISTRY_TITLE, { action: 'raw', ctype: 'application/json' });
                    registry = window.EntryStore.getJsonSync(url);
                }
            }
        } catch (err) {}
        return registry && typeof registry === 'object' ? registry : null;
    }

    function fetchRegistry() {
        var url;
        var prepared = getPreparedRegistrySync();
        if (prepared) return Promise.resolve(prepared);
        if (!mw || !mw.util || typeof fetch !== 'function') return Promise.resolve({ decorations: [] });
        url = mw.util.getUrl(REGISTRY_TITLE, {
            action: 'raw',
            ctype: 'application/json'
        });
        return fetch(url, { credentials: 'same-origin', cache: 'force-cache' })
            .then(function (response) {
                if (!response.ok) throw new Error('HTTP ' + response.status);
                return response.text();
            })
            .then(function (text) {
                if (!text || !text.trim()) return { decorations: [] };
                return JSON.parse(text);
            })
            .catch(function () {
                return { decorations: [] };
            });
    }

    function reload() {
        var token;
        runtimeToken += 1;
        token = runtimeToken;
        return fetchRegistry().then(function (registry) {
            return preloadPixelAssetsForRegistry(registry).then(function () {
                return renderForCurrentLayout(registry, token);
            });
        });
    }

    document.addEventListener('click', function (event) {
        var target = event.target && event.target.closest ? event.target.closest('.clbi-nations-tabpanel-tab[data-continent], [data-nations-era-move]') : null;
        if (target) window.setTimeout(scheduleDecorationVisibilityUpdate, 0);
    }, true);

    function decorationDiagnostics() {
        return {
            build: '20260713-main-body-well-coordinate-003',
            hasRegistry: !!lastRegistry,
            entries: decorationList(lastRegistry).length,
            rendered: document.querySelectorAll('[' + RENDERED_ATTR + '="1"]').length,
            preparedRegistry: !!getPreparedRegistrySync(),
            pixelAssets: Object.keys(pixelAssetCache || {}).length,
            pixelCanvases: Object.keys(pixelCanvasCache || {}).length,
            visibilityOnlySync: true,
            mainPageCoordinateSurface: MAIN_PAGE_TARGET,
            mainPagePlacementObserved: !!observedMainPagePortal,
            lastRenderedPage: lastRenderedPageKey,
            visibleRendered: document.querySelectorAll('[' + RENDERED_ATTR + '="1"][data-decoration-visible="1"]').length,
            scheduled: !!scheduledRender
        };
    }

    window.Decorations = window.Decorations || {};
    window.Decorations.reload = reload;
    window.Decorations.render = render;
    window.Decorations.renderPrepared = renderPrepared;
    window.Decorations.sync = syncDecorationState;
    window.Decorations.updateVisibility = updateDecorationVisibility;
    window.Decorations.diagnostics = decorationDiagnostics;
    window.Decorations.clear = clearRendered;
    window.Decorations.apply = applyDecoration;
    window.Decorations.pageKey = currentPageKey;
    window.Decorations.loadPixelAsset = fetchPixelAsset;
    window.Decorations.preparePixelCanvas = preparePixelCanvas;
    window.Decorations.getPreparedPixelCanvasSync = getPreparedPixelCanvasSync;
    window.Decorations.drawPixelAssetToCanvas = drawPixelAssetToCanvas;

    window.CLBI_DECORATIONS = window.CLBI_DECORATIONS || {};
    window.CLBI_DECORATIONS.reload = reload;
    window.CLBI_DECORATIONS.render = render;
    window.CLBI_DECORATIONS.renderPrepared = renderPrepared;
    window.CLBI_DECORATIONS.sync = syncDecorationState;
    window.CLBI_DECORATIONS.updateVisibility = updateDecorationVisibility;
    window.CLBI_DECORATIONS.diagnostics = decorationDiagnostics;
    window.CLBI_DECORATIONS.clear = clearRendered;
    window.CLBI_DECORATIONS.apply = applyDecoration;
    window.CLBI_DECORATIONS.pageKey = currentPageKey;
    window.CLBI_DECORATIONS.loadPixelAsset = fetchPixelAsset;
    window.CLBI_DECORATIONS.preparePixelCanvas = preparePixelCanvas;
    window.CLBI_DECORATIONS.getPreparedPixelCanvasSync = getPreparedPixelCanvasSync;
    window.CLBI_DECORATIONS.drawPixelAssetToCanvas = drawPixelAssetToCanvas;

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', reload);
    } else {
        reload();
    }

    if (mw && mw.hook) {
        mw.hook('wikipage.content').add(function () {
            reload();
        });
    }
})(mediaWiki);

/* =========================================
   Unified Shortcuts loader
   ========================================= */
(function () {
    'use strict';

    if (!window.mw || !mw.loader) return;
    loadClbiRawScript('MediaWiki:Nation_List_Manager.js');
    loadClbiRawScript('MediaWiki:History_Event_Manager.js');
    loadClbiRawScript('MediaWiki:Shortcuts.js');
})();

/* =========================================
   Main page manifesto bitmap renderer
   Integrated build: no extra raw-script page, no image/data-URL decoding.
   New shared systems do not use the legacy CLBI prefix.
   ========================================= */
(function (window, document, mw) {
    'use strict';

    /*
    Retired compatibility block
    -----------------------------------------
    선언문은 실제 HTML과 ManifestoIntro의 실선 요소만 사용한다.
    이 구식 렌더러는 제목·본문과 완성형 구분선을 canvas에 한 번에 그려
    새 애니메이션의 선 뒤에 트랙이 나타날 수 있었다.

    기존 Common.js를 장기 캐시한 뒤 새 파일로 넘어오는 경우를 위해
    남아 있는 canvas와 상태만 제거하고 즉시 종료한다. 새 공개 이름에는
    프로젝트 접두사를 사용하지 않는 규칙을 유지한다.
    */
    function removeRetiredBitmap() {
        Array.prototype.forEach.call(
            document.querySelectorAll('.main-portal .main-manifesto-bitmap'),
            function (canvas) {
                if (canvas.parentNode) canvas.parentNode.removeChild(canvas);
            }
        );

        Array.prototype.forEach.call(
            document.querySelectorAll('.main-portal .main-manifesto-inner'),
            function (inner) {
                inner.classList.remove('is-bitmap-ready');
                [
                    'data-bitmap-width',
                    'data-bitmap-optical-shift-x',
                    'data-bitmap-state',
                    'data-bitmap-error'
                ].forEach(function (name) {
                    inner.removeAttribute(name);
                });
            }
        );
    }

    removeRetiredBitmap();

    try {
        if (mw && mw.hook) {
            mw.hook('wikipage.content').add(removeRetiredBitmap);
        }
    } catch (ignoreRetiredBitmapHook) {}

    window.MainPageBitmap = {
        version:'retired-20260713-divider-no-track-001',
        recalculate:removeRetiredBitmap,
        status:function () {
            return {
                integrated:false,
                state:'retired',
                canvas:!!document.querySelector('.main-portal .main-manifesto-bitmap')
            };
        }
    };

    return;

    var VERSION = '20260712-bitmap18-inline-002';
    var SELECTOR = '.main-portal .main-manifesto-inner';
    var CELL_W = 24;
    var CELL_H = 24;
    var GLYPHS = {"진":[19,0,0,0,0,0,12288,24576,24576,25472,25584,25056,25072,25568,26160,26136,24576,9088,8960,768,256,32512,15872,0,0],"창":[19,0,0,0,0,0,6144,12512,12480,12800,13280,78328,258272,12768,14128,13848,4360,3840,7040,12672,4480,8064,3840,0,0],"바":[19,0,0,0,0,0,6144,12288,12288,12672,12672,14080,13056,13064,258456,127472,12784,12504,12408,12312,12288,12288,4096,0,0],"다":[19,0,0,0,0,0,6144,12288,12288,12288,13056,12792,12400,12320,258096,128528,14328,13048,12304,12288,12288,12288,4096,0,0],"는":[19,0,0,0,0,0,0,96,192,192,14528,16064,960,0,130048,118780,56,448,448,128,128,16256,7936,0,0],"왕":[19,0,0,0,0,0,12288,28768,25568,25456,25392,25392,254944,24960,16064,10236,12344,7680,14080,12672,12672,16128,7936,0,0],"과":[19,0,0,0,0,0,12288,28672,24576,26560,26352,26112,26112,26208,255680,254912,29248,32736,25084,8192,8192,8192,8192,0,0],"노":[19,0,0,0,0,0,0,0,0,96,192,192,4288,15552,16320,7040,7168,3072,50688,131064,124,0,0,0,0],"예":[19,0,0,0,0,0,24576,60416,22528,22528,22544,24048,24504,23320,23320,24504,23024,22528,22528,18432,16384,16384,24576,0,0],"를":[19,0,0,0,0,0,7168,16320,6144,8128,448,15552,1984,122880,262140,16636,8128,8128,3840,8064,1792,960,65408,4096,0],"같":[19,0,0,0,0,0,6144,12288,12288,13248,13304,110976,127168,12384,12344,4104,3584,0,8064,1920,256,14720,8064,0,0],"은":[19,0,0,0,0,0,384,3968,6528,6336,6272,3968,1792,32768,130944,115708,16,448,448,128,128,16256,7936,0,0],"깊":[19,0,0,0,0,0,12288,24576,24576,26496,25592,25472,25024,24800,24624,8216,12288,16256,4864,15872,7680,31232,32640,256,0],"이":[19,0,0,0,0,0,12288,24576,24576,24576,24592,25072,25584,25368,25368,25496,25072,24640,24576,24576,24576,8192,8192,0,0],"로":[19,0,0,0,0,0,0,0,15360,16320,6272,7168,8128,384,14528,16320,7040,3072,50688,131064,124,0,0,0,0],"삼":[19,0,0,0,0,0,6144,12288,12352,12736,12480,78064,258272,13296,14136,13324,4096,16256,16256,4224,4480,8064,8064,0,0],"켰":[19,0,0,0,0,0,12288,24576,26112,26600,29560,32656,25072,31992,26720,8224,8216,13056,15104,5056,15232,28544,58992,0,0],"고":[19,0,0,0,0,0,0,0,0,7680,16352,12416,12288,12288,12544,13056,6912,4864,49920,131064,124,0,0,0,0],",":[8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,12,12,8,0,0,0],"겨":[19,0,0,0,0,0,12288,24576,24576,24576,25344,26616,32560,31104,24768,31840,31792,24600,24584,24576,24576,24576,8192,0,0],"울":[19,0,0,0,0,0,1792,8064,6528,6272,7552,3840,114688,262140,18428,1536,16320,8128,3840,8064,1920,896,65280,0,0],"사":[19,0,0,0,0,0,6144,12288,12288,12352,12480,12480,12480,12400,258272,127920,14104,13828,13312,12288,12288,12288,4096,0,0],"람":[19,0,0,0,0,0,6144,12288,12288,13296,13240,78208,258552,12304,14224,13296,4096,15744,16256,4288,4480,8064,8064,0,0],"짐":[19,0,0,0,0,0,12288,24576,24576,25472,25584,24992,25072,26592,26160,9756,0,32512,32640,12672,12672,16128,16128,0,0],"승":[19,0,0,0,0,0,512,3584,1536,1792,8064,29056,24800,32768,130816,115708,272,3840,7040,4224,6272,8064,3840,0,0],"의":[19,0,0,0,0,0,28672,57344,24608,25536,26592,26160,26160,26464,25568,24576,24576,32704,25596,24576,24576,24576,8192,0,0],"살":[19,0,0,0,0,0,6144,12288,12352,12736,12480,110832,127456,13232,13848,5132,8064,8064,3840,8064,1792,896,65024,0,0],"을":[19,0,0,0,0,0,1792,8064,6528,6272,7552,3840,32768,130944,115708,0,16320,8128,3840,8064,1920,896,65280,0,0],"빛":[19,0,0,0,0,0,12288,24576,25344,25344,26376,25496,25592,25584,25552,25088,7168,12288,32640,6400,7680,32256,25472,0,0],"으":[19,0,0,0,0,0,0,0,128,3968,8064,4544,4288,6336,7616,3968,0,0,57344,131068,56,0,0,0,0],"얼":[19,0,0,0,0,0,12288,24576,24592,24816,25008,32536,31512,25016,25072,8192,16256,16256,7680,16128,3584,1792,130560,0,0],"렸":[19,0,0,0,0,0,12288,24576,24576,25584,32568,27008,31224,31792,26544,9200,8192,13056,15104,4928,15232,28544,58976,0,0],".":[8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,12,12,0,0,0,0],"그":[19,0,0,0,0,0,0,0,0,7168,16352,12672,12288,12288,12288,12288,6144,4096,57344,131068,56,0,0,0,0],"들":[19,0,0,0,0,0,6144,16320,896,384,14528,16320,960,130048,118780,120,16320,8128,3840,8064,1920,896,65280,0,0],"돌":[19,0,0,0,0,0,6144,16320,896,384,14528,16320,8128,130048,253948,16504,16320,8128,3840,8064,1920,896,65280,0,0],"벽":[19,0,0,0,0,0,12288,24576,24832,25344,32520,31512,25560,32632,25584,9104,8192,31744,32640,8192,8192,8192,8192,0,0],"세":[19,0,0,0,0,0,24576,60416,22528,22528,22720,22720,22752,24432,22752,22960,23320,23300,22528,18432,16384,16384,24576,0,0],"우":[19,0,0,0,0,0,0,384,7936,6528,12480,6336,7552,3968,0,131008,116732,1552,1536,1536,1536,1536,512,0,0],"땅":[19,0,0,0,0,0,12288,28672,24576,28560,9200,74160,254128,30936,16376,12280,12544,7936,13184,12672,12672,8064,3840,0,0],"찢":[19,0,0,0,0,0,12288,24576,24704,26616,28656,26560,25456,28656,28056,26848,8192,32512,16128,7680,15872,25344,16768,0,0],"어":[19,0,0,0,0,0,12288,24576,24576,24576,24592,24816,25520,32536,27416,25496,25072,24640,24576,24576,24576,8192,8192,0,0],"길":[19,0,0,0,0,0,12288,24576,24576,26496,25592,25472,24768,24672,24624,8216,16256,16128,7680,16128,3584,1792,130560,0,0],"냈":[19,0,0,0,0,0,8192,58368,19456,27672,27704,31792,31792,32560,28656,27120,8704,13824,14080,13248,15232,28544,50272,0,0],"며":[19,0,0,0,0,0,12288,24576,24576,24576,25472,26600,32536,25368,25400,32560,25584,25056,24576,24576,24576,24576,8192,0,0],"쇠":[19,0,0,0,0,0,28672,57344,24704,24960,24960,25056,25536,26208,27888,24960,24960,32704,25596,24576,24576,24576,8192,0,0],"에":[19,0,0,0,0,0,24576,60416,22528,22528,22544,23024,23480,24344,24344,22968,23024,22528,22528,18432,16384,16384,24576,0,0],"제":[19,0,0,0,0,0,24576,60416,22528,22528,23488,23032,22976,24512,24184,23024,23344,23320,23052,18432,16384,16384,24576,0,0],"름":[19,0,0,0,0,0,6144,16320,6272,8128,960,14528,16320,384,130560,116732,56,15872,16320,4288,4544,7552,8064,0,0],"새":[19,0,0,0,0,0,24576,60416,23552,19456,27840,27840,31968,31856,23776,23984,20248,20228,16384,16384,16384,16384,24576,0,0],"겼":[19,0,0,0,0,0,12288,24576,24576,26496,30712,32640,25024,31968,26672,8216,8200,15104,15104,6976,15232,28608,58992,0,0],"감":[19,0,0,0,0,0,6144,12288,12288,13184,13304,78208,258240,12384,12336,4120,4096,16256,16320,4224,4480,8064,8064,0,0],"옥":[19,0,0,0,0,0,1792,7936,6528,6272,6528,8064,3584,1536,130816,116732,56,16128,15296,4096,4096,4096,4096,0,0],"되":[19,0,0,0,0,0,28672,57344,25088,26608,25072,24672,25632,26416,26608,25456,24960,32704,25596,24576,24576,24576,8192,0,0],"군":[19,0,0,0,0,0,0,7680,16352,12288,12288,12288,6144,126976,262140,18172,1536,1728,1472,192,192,16256,8064,0,0],"대":[19,0,0,0,0,0,24576,60416,23552,19456,28032,28144,31856,31776,23600,24344,20440,19960,16400,16384,16384,16384,24576,0,0],"나":[19,0,0,0,0,0,6144,12288,12288,12288,12296,12312,12336,12304,259600,128784,14256,12528,12320,12288,12288,12288,4096,0,0],"르":[19,0,0,0,0,0,0,0,6144,16320,6336,7168,8128,448,12480,16320,3968,0,57344,131068,56,0,0,0,0],"오":[19,0,0,0,0,0,0,0,256,7936,15232,12672,12416,12672,8064,7936,3072,1024,49664,131064,124,0,0,0,0],"래":[19,0,0,0,0,0,24576,60416,23552,19456,28144,27064,32128,32248,23664,23568,20240,20464,16880,16384,16384,16384,24576,0,0],"된":[19,0,0,0,0,0,28672,57344,26368,25584,24800,25696,28656,26608,29440,32736,25080,24832,25344,768,768,65280,15872,0,0],"원":[19,0,0,0,0,0,28672,57440,25536,26464,26160,26160,29664,32640,26592,26620,25360,25024,25536,768,768,65280,15872,0,0],"한":[19,0,0,0,0,0,6144,28704,12512,12800,14328,12784,258528,13088,12592,12784,12512,12416,4544,384,128,16256,7936,0,0],"함":[19,0,0,0,0,0,6144,12512,12480,12800,14328,78032,258528,13104,12720,12784,4192,15744,16256,4288,4480,8064,8064,0,0],"께":[19,0,0,0,0,0,24576,55296,55296,55296,55488,57336,57280,57184,57184,55600,55704,55500,55392,49152,49152,16384,16384,0,0],"음":[19,0,0,0,0,0,1920,8064,6528,6336,6336,3968,1792,32768,131040,16892,0,16128,16320,4288,4544,7552,8064,0,0],"손":[19,0,0,0,0,0,512,1536,1536,1920,7936,14720,26304,1584,130560,249852,120,448,448,128,128,16256,7936,0,0],"넘":[19,0,0,0,0,0,12288,24576,24576,24600,31792,31792,24624,28208,26608,8416,0,32512,32640,12672,12672,16256,15616,0,0],"갔":[19,0,0,0,0,0,6144,12288,12288,13184,13304,78208,258240,12384,12336,12312,4352,15104,6912,6528,7616,30656,25136,0,0],"\n":[8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"줄":[19,0,0,0,0,0,6144,16320,3520,3840,15296,12480,41056,130976,116732,1536,16320,8128,3840,8064,1920,896,65280,0,0],"처":[19,0,0,0,0,0,12288,24576,24800,25024,25344,26592,25072,32448,27616,25392,25360,24840,24832,24960,24960,8320,8192,0,0],"부":[19,0,0,0,0,0,6144,12288,28768,14400,15552,13248,8128,7872,0,131008,116732,1552,1536,1536,1536,1536,512,0,0],"터":[19,0,0,0,0,0,12288,24576,24576,25056,24768,25344,25584,31984,31840,25648,28568,26360,24624,24576,24576,8192,8192,0,0],"목":[19,0,0,0,0,0,14336,32512,15328,6336,3264,16064,7296,3072,130816,116732,56,16128,15296,4096,4096,4096,4096,0,0],"둘":[19,0,0,0,0,0,6144,16320,896,384,14528,16320,960,130944,116732,1592,16320,8128,3840,8064,1920,896,65280,0,0],"레":[19,0,0,0,0,0,24576,60416,22528,22528,23024,22968,22912,24568,22640,22544,23312,23536,23024,18432,16384,16384,24576,0,0],"있":[19,0,0,0,0,0,12288,24576,24576,24816,25072,25400,25368,25368,25072,8416,8192,15104,15104,7104,14720,28608,26224,0,0],"었":[19,0,0,0,0,0,12288,24576,24576,24816,25072,32568,32536,25496,25072,8416,8192,15104,15104,7104,14720,28608,26224,0,0],"끝":[19,0,0,0,0,0,0,14720,16368,13152,12672,12672,4480,130560,116732,56,3840,3584,8128,1920,384,16320,4032,0,0],"속":[19,0,0,0,0,0,512,3584,1536,1792,7936,12672,26336,1568,130560,116732,56,16128,15296,4096,4096,4096,4096,0,0],"뿌":[19,0,0,0,0,0,4096,30720,14080,15904,16352,13280,16320,14208,4608,130944,126972,1552,1536,1536,1536,1536,512,0,0],"리":[19,0,0,0,0,0,12288,24576,24576,24576,25568,25528,24960,25040,24688,25648,26160,26608,25056,24576,24576,8192,8192,0,0],"와":[19,0,0,0,0,0,12288,28672,24608,25568,25456,26160,26416,25584,254432,254336,28864,32736,25084,8192,8192,8192,8192,0,0],"빨":[19,0,0,0,0,0,12288,28672,26112,26176,26304,255944,255992,10200,10224,1728,16256,16256,7936,7936,1792,896,65024,0,0],"굶":[19,0,0,0,0,0,0,16128,13248,12288,12288,6144,118784,262140,18428,1536,14080,16368,13792,14272,14272,16352,16352,0,0],"주":[19,0,0,0,0,0,0,14336,16320,3264,1792,7936,12736,24672,32,131008,116732,1552,1536,1536,1536,1536,512,0,0],"림":[19,0,0,0,0,0,12288,24576,24576,25584,25400,25472,25072,24624,26544,9200,8192,15616,32640,12672,12672,16256,16128,0,0],"매":[19,0,0,0,0,0,24576,60416,23552,19456,28544,28644,32156,32024,23832,23992,19952,19504,16384,16384,16384,16384,24576,0,0],"였":[19,0,0,0,0,0,12288,24576,24576,24816,32752,32568,25368,32664,25072,8416,8192,15104,15104,7104,14720,28608,26224,0,0],"른":[19,0,0,0,0,0,4096,16320,6336,7744,4032,14528,16320,896,126976,253948,120,64,448,128,128,16256,7936,0,0],"아":[19,0,0,0,0,0,6144,12288,12288,12288,12304,12528,12720,13080,258840,127896,12784,12352,12288,12288,12288,12288,4096,0,0],"직":[19,0,0,0,0,0,12288,24576,24576,25472,25584,24992,25072,25568,26160,9752,0,31744,32640,8192,8192,12288,12288,0,0],"태":[19,0,0,0,0,0,24576,60416,23552,19680,27840,28032,32240,31856,23600,24336,20440,20472,16432,16384,16384,16384,24576,0,0],"지":[19,0,0,0,0,0,12288,24576,24576,24576,26496,25584,24992,24768,24816,25568,26160,27672,25612,24576,24576,24576,8192,0,0],"않":[19,0,0,0,0,0,6144,12288,12304,12528,12784,111384,258840,13208,12784,4160,7168,6240,32352,15456,13408,14176,8160,0,0],"자":[19,0,0,0,0,0,6144,12288,12288,12288,13184,13304,12720,12480,258296,127984,14128,13848,13324,12288,12288,12288,4096,0,0],"졌":[19,0,0,0,0,0,12288,24576,24576,25472,32752,31136,32240,32736,26160,9756,8704,13056,15104,4928,15232,28544,50784,0,0],"앞":[19,0,0,0,0,0,6144,12288,12304,12528,12784,111384,258840,13208,12784,4160,6144,8128,2432,7936,2816,15616,16320,128,0],"갈":[19,0,0,0,0,0,6144,12288,12288,13248,13304,127360,127168,12384,12344,4104,16256,8064,3840,8064,1792,896,65280,0,0],"때":[19,0,0,0,0,0,24576,52224,55296,55296,57096,56312,63920,63632,63704,56536,57336,57336,49216,49152,49152,16384,16384,0,0],"마":[19,0,0,0,0,0,6144,12288,12288,12288,13184,13284,13084,13080,258840,127792,12784,12464,12288,12288,12288,12288,4096,0,0],"듭":[19,0,0,0,0,0,6144,16320,1984,384,12480,16064,3008,32768,131008,115708,14336,12352,12480,14720,16256,8064,7808,0,0],"파":[19,0,0,0,0,0,6144,12288,12288,12288,13248,12792,12688,13296,258528,127392,16352,12412,12288,12288,12288,12288,4096,0,0],"각":[19,0,0,0,0,0,6144,12288,12288,13184,13304,12672,258240,12384,12336,4120,4096,16128,13248,12288,4096,4096,4096,0,0],"쥔":[19,0,0,0,0,0,28672,57856,26608,25584,25024,26592,28208,27664,28544,28668,25360,24960,25536,768,768,65280,15872,0,0],"당":[19,0,0,0,0,0,6144,12288,12288,13248,12536,77920,258096,15888,14328,12920,4352,7936,7040,12672,4480,8064,3840,0,0],"기":[19,0,0,0,0,0,12288,24576,24576,24576,25344,26616,25392,24960,24768,24672,24624,24600,24584,24576,24576,24576,8192,0,0],"면":[19,0,0,0,0,0,12288,24576,24576,26496,26604,32536,25368,32560,31728,25072,24576,25344,8960,768,768,32512,15872,0,0],"풀":[19,0,0,0,0,0,12288,16352,7296,8064,3328,32704,41440,131008,116732,1536,16320,8128,3840,8064,1920,896,65280,0,0],"려":[19,0,0,0,0,0,12288,24576,24576,24576,25568,32696,31104,25040,31856,27696,26160,26608,25056,24576,24576,8192,8192,0,0],"날":[19,0,0,0,0,0,6144,12288,12288,12312,12344,110640,128560,14256,13296,4192,8064,8064,3840,8064,1792,896,65024,0,0],"것":[19,0,0,0,0,0,12288,24576,24576,26496,25592,24960,32704,26848,24624,24600,11272,3072,1792,3584,15104,29056,24800,0,0],"라":[19,0,0,0,0,0,6144,12288,12288,12288,13280,12728,12672,12792,258168,127504,13840,14320,12784,12288,12288,12288,4096,0,0],"여":[19,0,0,0,0,0,12288,24576,24576,24576,24592,24816,32688,25368,25368,32664,25072,24640,24576,24576,24576,8192,8192,0,0],"므":[19,0,0,0,0,0,0,0,4096,31744,32736,6624,3264,1728,16064,7360,0,0,57344,131068,56,0,0,0,0],"번":[19,0,0,0,0,0,12288,24576,24576,25344,26376,26392,32728,25464,25584,25552,24576,25344,8960,768,768,32512,15872,0,0],"도":[19,0,0,0,0,0,0,0,0,15360,4064,960,384,14528,16064,7136,7360,3072,50688,131064,124,0,0,0,0],"느":[19,0,0,0,0,0,0,0,0,32,192,192,192,14528,16064,7104,0,0,57344,131068,56,0,0,0,0],"슨":[19,0,0,0,0,0,512,1536,1536,1920,7936,14720,24768,48,130048,118780,56,448,448,128,128,16256,7936,0,0],"해":[19,0,0,0,0,0,24576,60416,23552,19680,27968,28664,32240,32224,23984,23984,19952,19568,16384,16384,16384,16384,24576,0,0],"았":[19,0,0,0,0,0,6144,12288,12288,12528,12784,78616,258840,13208,12784,12512,4352,15104,6912,6528,7616,30656,25136,0,0],"침":[19,0,0,0,0,0,12288,24768,25024,25088,26592,25584,24800,25568,26416,9232,8,15616,32640,12672,12672,16256,16128,0,0],"내":[19,0,0,0,0,0,24576,58368,19456,19456,27656,27672,31792,31792,31760,24368,20464,19952,16384,16384,24576,24576,8192,0,0],"멎":[19,0,0,0,0,0,12288,24576,24576,26496,25576,32536,31512,25392,25072,8224,8192,32640,6912,3584,15872,25344,16768,0,0],"서":[19,0,0,0,0,0,12288,24576,24576,24640,24768,25024,24768,32496,24800,25520,26392,26124,25600,24576,24576,8192,8192,0,0],"긴":[19,0,0,0,0,0,12288,24576,24576,26368,25592,25520,25024,24768,24688,24632,24584,25472,8960,768,768,32512,15872,0,0],"붙":[19,0,0,0,0,0,6144,12288,14432,16064,13248,7872,38912,130816,116732,1552,3840,3584,8064,1920,384,15808,4032,0,0],"잡":[19,0,0,0,0,0,6144,12288,12288,13184,13304,111040,258288,13280,13872,5660,4096,12352,12416,14720,16256,8064,7296,0,0],"피":[19,0,0,0,0,0,12288,24576,24576,24576,26496,25592,25392,25568,25440,24992,28640,26744,24576,24576,24576,24576,8192,0,0],"가":[19,0,0,0,0,0,6144,12288,12288,12288,13056,13304,12728,12736,127168,258144,12336,12312,12300,12288,12288,12288,4096,0,0],"굴":[19,0,0,0,0,0,0,16128,13248,12288,12288,6144,126976,262140,18172,1536,16320,8128,3840,8064,1920,896,65280,0,0],"보":[19,0,0,0,0,0,0,0,6144,12288,28768,14528,16064,13248,16320,7360,3072,1024,50688,131064,124,0,0,0,0],"하":[19,0,0,0,0,0,6144,12288,12320,12512,12800,14332,12792,12512,259040,127792,12720,12528,12288,12288,12288,12288,4096,0,0],"입":[19,0,0,0,0,0,12288,24576,24576,24816,25584,25368,25368,25496,25072,8256,4096,28800,24960,14720,16128,16128,15616,0,0],"말":[19,0,0,0,0,0,6144,12288,12288,13184,13308,111384,127768,13240,12784,4096,8064,8064,3840,8064,1792,896,65024,0,0],"했":[19,0,0,0,0,0,24576,58368,23776,19776,28664,27888,32224,23984,19888,18672,96,13824,15872,13184,15232,28544,50272,0,0],"조":[19,0,0,0,0,0,0,0,0,15360,8128,3072,1792,16128,28864,25184,1568,1536,50688,131064,124,0,0,0,0],"올":[19,0,0,0,0,0,1792,8064,6528,6528,8064,3840,1536,128768,253948,16504,16320,8128,3840,8064,1920,896,65280,0,0],"수":[19,0,0,0,0,0,0,1536,3072,1792,1792,6912,29056,24800,32,131008,116732,1552,1536,1536,1536,1536,512,0,0],"록":[19,0,0,0,0,0,6144,16320,6272,8128,960,14528,16320,3968,128512,253948,120,15872,16320,4096,4096,4096,6144,0,0],"열":[19,0,0,0,0,0,12288,24576,24592,24816,32688,31512,25368,32696,25072,8192,16256,16256,7680,16128,3584,1792,130560,0,0],"단":[19,0,0,0,0,0,6144,28672,12288,13184,12792,12400,258096,13872,14232,14328,12336,12672,4480,384,384,16256,7936,0,0],"질":[19,0,0,0,0,0,12288,24576,24576,26496,25584,24992,25072,26464,26160,9240,16128,16128,7680,16128,3584,1792,130560,0,0],"히":[19,0,0,0,0,0,12288,24576,24576,25024,26112,26616,25584,25024,25440,25392,25392,25056,24576,24576,24576,8192,8192,0,0],"운":[19,0,0,0,0,0,384,3968,6528,6336,6272,3968,1792,32768,131040,17916,3072,1984,1472,128,192,16256,7936,0,0],"데":[19,0,0,0,0,0,24576,60416,22528,22528,22912,23024,22640,24352,22576,23320,23512,23032,22544,18432,16384,16384,24576,0,0],"끌":[19,0,0,0,0,0,0,14720,16368,13152,12672,12672,4480,130560,116732,56,16320,8128,3840,8064,1920,896,65280,0,0],"린":[19,0,0,0,0,0,12288,24576,24576,25568,25464,24960,25592,24624,26416,26608,24672,8320,9088,256,256,32512,15872,0,0],"게":[19,0,0,0,0,0,24576,60416,22528,22528,23424,23544,22960,24000,24512,22624,22576,22552,22536,18432,16384,16384,24576,0,0],"누":[19,0,0,0,0,0,0,96,192,192,192,15552,16320,960,0,131008,116732,1552,1536,1536,1536,1536,512,0,0],"인":[19,0,0,0,0,0,12288,24576,24576,24624,25072,25400,25368,25368,25072,24800,24576,9088,8960,256,256,32512,15872,0,0],"쳐":[19,0,0,0,0,0,12288,24576,24800,25024,25344,26592,32752,31936,25568,32560,25360,24840,24832,24960,24960,8320,8192,0,0],"문":[19,0,0,0,0,0,12288,15872,15328,6336,3264,7872,7360,32768,131040,17916,3072,1984,1472,128,192,16256,7936,0,0],"몸":[19,0,0,0,0,0,14336,32512,15328,6336,3264,16064,7296,3072,130816,116732,56,16128,16320,4288,4544,7552,8064,0,0],"식":[19,0,0,0,0,0,12288,24576,24768,24960,25024,24816,24800,25568,26160,9244,0,31744,32640,8192,8192,12288,12288,0,0],"억":[19,0,0,0,0,0,12288,24576,24576,24816,25072,32536,32536,25368,25072,8416,0,31744,32640,12288,12288,12288,12288,0,0],"전":[19,0,0,0,0,0,12288,24576,24576,25472,25592,24992,31984,25568,26160,26136,24576,9088,8960,768,256,32512,15872,0,0],"품":[19,0,0,0,0,0,12288,16352,7360,8064,7040,16128,26592,127040,253948,18040,1536,16128,16320,4288,4544,7552,8064,0,0],"발":[19,0,0,0,0,0,6144,12288,12672,13056,14092,111512,127992,13176,13272,4096,8064,8064,3840,8064,1792,896,65024,0,0],"머":[19,0,0,0,0,0,12288,24576,24576,24576,25472,25576,25368,32536,27448,25392,25584,25056,24576,24576,24576,24576,8192,0,0],"두":[19,0,0,0,0,0,0,14336,8128,960,384,12480,16064,5056,192,131008,116732,1552,1536,1536,1536,1536,512,0,0],"닐":[19,0,0,0,0,0,12288,24576,24576,24600,24624,24624,27696,28464,26608,8288,16256,16256,7680,16128,3584,1792,130560,0,0],"격":[19,0,0,0,0,0,12288,24576,24576,26496,26616,32640,25024,31968,26672,8216,8200,32256,26496,8192,8192,8192,8192,0,0],"없":[19,0,0,0,0,0,12288,24576,24592,24816,25072,32536,31512,25496,25072,8256,8192,13824,15936,4928,15296,28608,51008,0,0],"니":[19,0,0,0,0,0,12288,24576,24576,24576,24584,24624,24624,24624,25648,28208,26544,25328,24576,24576,24576,8192,8192,0,0],"산":[19,0,0,0,0,0,6144,28672,12352,12480,12480,12496,258272,13280,14128,13852,12288,12672,4480,384,384,16256,7936,0,0],"복":[19,0,0,0,0,0,14336,12288,28736,15552,14272,16320,7808,3072,130560,249852,120,15872,16320,4096,4096,4096,6144,0,0],"종":[19,0,0,0,0,0,6144,16320,3520,1792,7936,12736,26208,1568,130816,116732,280,3840,7040,4224,6272,8064,3840,0,0],"죽":[19,0,0,0,0,0,6144,16320,3520,1792,7936,12736,24672,122912,262140,18172,1536,16128,15296,4096,4096,4096,4096,0,0],"망":[19,0,0,0,0,0,6144,12288,12288,13248,13308,78620,258840,13112,12784,12336,4352,7936,7040,12672,4480,8064,3840,0,0],"베":[19,0,0,0,0,0,24576,60416,22528,22912,22912,24448,24448,24456,24536,23024,23024,22776,22648,18456,16384,16384,24576,0,0],"막":[19,0,0,0,0,0,6144,12288,12288,13248,13308,13084,258840,13080,12784,12464,4096,15872,16320,12288,4096,4096,4096,0,0],"무":[19,0,0,0,0,0,0,30720,32608,15296,6336,3520,16320,15488,0,131008,116732,1552,1536,1536,1536,1536,512,0,0],"릎":[19,0,0,0,0,0,6144,16320,6272,8128,960,14528,8128,0,130560,116732,56,16320,3456,8064,3840,16128,14272,0,0],"꿇":[19,0,0,0,0,0,0,14720,16368,12640,12672,12672,118912,262140,18428,1536,7936,7152,32736,14784,11712,16352,7648,0,0],"까":[19,0,0,0,0,0,12288,28672,24576,24576,24768,10232,10176,9824,254752,254768,8600,8388,8288,8192,8192,8192,12288,0,0],"놓":[19,0,0,0,0,0,0,224,192,12480,15552,8128,7552,130048,253948,16760,1792,15872,16320,3584,6912,3328,1792,0,0],"러":[19,0,0,0,0,0,12288,24576,24576,24576,25568,25528,29056,32720,24688,25648,26160,26608,25056,24576,24576,8192,8192,0,0],"재":[19,0,0,0,0,0,24576,60416,23552,19456,28608,28152,32192,31936,23672,24048,20272,20248,16908,16384,16384,16384,24576,0,0],"받":[19,0,0,0,0,0,6144,12288,12672,13056,14092,78744,259064,13176,13304,12672,0,7936,3584,768,24960,32640,1920,0,0],"묵":[19,0,0,0,0,0,14336,32512,15328,6336,3264,16064,3200,130048,118780,1592,1536,16128,15296,4096,4096,4096,4096,0,0],"스":[19,0,0,0,0,0,0,0,512,1536,3584,1920,1792,7936,12672,24800,0,0,57344,131068,56,0,0,0,0],"릴":[19,0,0,0,0,0,12288,24576,24832,25592,25360,25536,25072,25136,26608,8432,14464,16256,7936,16128,3840,1792,130560,0,0],"계":[19,0,0,0,0,0,24576,60416,22528,22528,23424,23544,24496,24256,22720,24416,22576,22552,22536,18432,16384,16384,24576,0,0],"구":[19,0,0,0,0,0,0,6144,16352,12736,12288,12288,12288,6144,4096,131056,67324,1536,1536,1536,1536,1536,512,0,0],"물":[19,0,0,0,0,0,14336,32544,15328,3264,7872,16064,32768,131040,18428,1536,16320,8128,3840,8064,1920,896,65280,0,0],"못":[19,0,0,0,0,0,14336,32512,15328,7360,3776,16064,7296,3072,130816,116732,1048,3584,1536,1792,7936,12480,8304,0,0],"시":[19,0,0,0,0,0,12288,24576,24576,24640,24768,25024,24768,24816,24800,25520,26424,26124,25600,24576,24576,8192,8192,0,0],"육":[19,0,0,0,0,0,1792,8064,6528,6336,6528,3968,1536,130048,118780,6584,6528,16256,15296,4096,4096,4096,4096,0,0],"신":[19,0,0,0,0,0,12288,24576,24640,25024,25024,24768,24800,25568,26416,25628,24576,9088,8960,768,256,32512,15872,0,0],"일":[19,0,0,0,0,0,12288,24576,24592,24816,25584,25368,25368,25528,25072,8192,16256,16256,7680,16128,3584,1792,130560,0,0],"모":[19,0,0,0,0,0,0,0,14336,32256,16352,6368,3264,7872,16064,6144,2048,1024,50688,131064,124,0,0,0,0],"행":[19,0,0,0,0,0,24576,58368,23776,19776,20472,27888,32224,32176,23984,19696,25184,15872,30208,25344,25344,16128,7680,0,0],"절":[19,0,0,0,0,0,12288,24576,24576,25472,25584,32160,32752,26464,26160,9752,16128,16128,7680,16128,3584,1792,130560,0,0],"멸":[19,0,0,0,0,0,12288,24576,24576,26496,32760,31512,25400,32688,25072,8224,16128,16128,7680,16128,3584,1792,130560,0,0],"끊":[19,0,0,0,0,0,0,14592,16368,13280,12672,12672,12672,114688,262140,16636,7168,6240,32352,15456,13408,16224,7648,0,0],"순":[19,0,0,0,0,0,512,3584,1536,1792,8064,29056,24800,32768,131008,116732,3072,1984,1472,128,192,16256,7936,0,0],"간":[19,0,0,0,0,0,6144,28672,12288,13184,13304,12688,258240,12384,12336,12312,12296,12672,4480,384,384,16256,7936,0,0]};
    var BODY_SCALE = 1;
    var TITLE_SCALE = 2;
    var BODY_TRACKING = -2;
    var TITLE_TRACKING = 0;
    var SPACE_ADVANCE = Math.round(CELL_H * 0.5);
    var BODY_LINE_HEIGHT = CELL_H + 8;
    var PARAGRAPH_GAP = 20;
    var DIVIDER_Y = 52;
    var BODY_TOP = 68;
    var BODY_COLOR = '#d8d8d8';
    var TITLE_COLOR = '#ffffff';
    var DIVIDER_COLOR = '#555555';
    var resizeTimer = 0;
    var observed = typeof WeakSet === 'function' ? new WeakSet() : null;
    var resizeObserver = typeof ResizeObserver === 'function' ? new ResizeObserver(function (entries) {
        entries.forEach(function (entry) { schedule(entry.target, false); });
    }) : null;

    function glyphFor(character) {
        return Object.prototype.hasOwnProperty.call(GLYPHS, character) ? GLYPHS[character] : null;
    }

    function measureText(text, scale, tracking) {
        var width = 0;
        var glyphCount = 0;
        Array.from(String(text || '')).forEach(function (character) {
            var glyph;
            if (character === ' ') {
                width += SPACE_ADVANCE * scale;
                return;
            }
            glyph = glyphFor(character);
            if (!glyph) return;
            width += glyph[0] * scale;
            width += tracking * scale;
            glyphCount += 1;
        });
        if (glyphCount && tracking) width -= tracking * scale;
        return Math.max(0, Math.round(width));
    }

    function breakLongToken(token, maxWidth) {
        var pieces = [];
        var current = '';
        Array.from(token).forEach(function (character) {
            var candidate = current + character;
            if (current && measureText(candidate, BODY_SCALE, BODY_TRACKING) > maxWidth) {
                pieces.push(current);
                current = character;
            } else {
                current = candidate;
            }
        });
        if (current) pieces.push(current);
        return pieces;
    }

    function wrapParagraph(text, maxWidth) {
        var words = String(text || '').trim().split(/\s+/).filter(Boolean);
        var lines = [];
        var current = '';

        words.forEach(function (word) {
            var candidate = current ? current + ' ' + word : word;
            var pieces;
            if (measureText(candidate, BODY_SCALE, BODY_TRACKING) <= maxWidth) {
                current = candidate;
                return;
            }
            if (current) {
                lines.push(current);
                current = '';
            }
            if (measureText(word, BODY_SCALE, BODY_TRACKING) <= maxWidth) {
                current = word;
                return;
            }
            pieces = breakLongToken(word, maxWidth);
            pieces.forEach(function (piece, index) {
                if (index === pieces.length - 1) current = piece;
                else lines.push(piece);
            });
        });
        if (current) lines.push(current);
        return lines.length ? lines : [''];
    }

    function calculateOpticalShift(lines, width) {
        var weightedCenter = 0;
        var totalWeight = 0;
        var maxLineWidth = 0;
        var shift;
        lines.forEach(function (line) {
            var lineWidth = line.width;
            var weight = Math.max(1, lineWidth) * BODY_LINE_HEIGHT;
            weightedCenter += (lineWidth / 2) * weight;
            totalWeight += weight;
            maxLineWidth = Math.max(maxLineWidth, lineWidth);
        });
        if (!totalWeight) return 0;
        shift = Math.round((width / 2) - (weightedCenter / totalWeight));
        return Math.max(0, Math.min(Math.max(0, width - maxLineWidth), shift));
    }

    function drawGlyph(context, glyph, x, y, scale) {
        var py;
        var px;
        var row;
        for (py = 0; py < CELL_H; py += 1) {
            row = glyph[py + 1] || 0;
            if (!row) continue;
            for (px = 0; px < CELL_W; px += 1) {
                if (row & (1 << px)) {
                    context.fillRect(
                        Math.round(x + px * scale),
                        Math.round(y + py * scale),
                        scale,
                        scale
                    );
                }
            }
        }
    }

    function drawText(context, text, x, y, scale, tracking, color) {
        context.fillStyle = color;
        Array.from(String(text || '')).forEach(function (character) {
            var glyph;
            if (character === ' ') {
                x += SPACE_ADVANCE * scale;
                return;
            }
            glyph = glyphFor(character);
            if (!glyph) return;
            drawGlyph(context, glyph, x, y, scale);
            x += (glyph[0] + tracking) * scale;
        });
    }

    function sourceContent(inner) {
        var titleNode = inner.querySelector('.main-manifesto-title');
        var paragraphs = [];
        Array.prototype.forEach.call(inner.children || [], function (child) {
            if (child && child.tagName === 'P') {
                var value = String(child.textContent || '').trim();
                if (value) paragraphs.push(value);
            }
        });
        return {
            title: titleNode ? String(titleNode.textContent || '').trim() : '',
            paragraphs: paragraphs
        };
    }

    function ensureCanvas(inner) {
        var canvas = inner.querySelector('.main-manifesto-bitmap');
        if (!canvas) {
            canvas = document.createElement('canvas');
            canvas.className = 'main-manifesto-bitmap';
            canvas.setAttribute('aria-hidden', 'true');
            canvas.setAttribute('data-bitmap-version', VERSION);
            inner.insertBefore(canvas, inner.firstChild);
        }
        return canvas;
    }

    function render(inner, force) {
        var width;
        var source;
        var paragraphs;
        var flatLines = [];
        var titleWidth;
        var height;
        var canvas;
        var context;
        var y;
        var opticalShift;

        if (!inner || !inner.isConnected) return;
        width = Math.max(1, Math.floor(inner.clientWidth || inner.getBoundingClientRect().width || 0));
        if (width <= 1) {
            window.setTimeout(function () { schedule(inner, true); }, 60);
            return;
        }
        if (!force && Number(inner.getAttribute('data-bitmap-width')) === width && inner.classList.contains('is-bitmap-ready')) return;

        source = sourceContent(inner);
        if (!source.title || !source.paragraphs.length) {
            fail(inner, new Error('Manifesto source nodes were not found.'));
            return;
        }

        paragraphs = source.paragraphs.map(function (paragraph) {
            return wrapParagraph(paragraph, width).map(function (line) {
                var item = { text:line, width:measureText(line, BODY_SCALE, BODY_TRACKING) };
                flatLines.push(item);
                return item;
            });
        });

        titleWidth = measureText(source.title, TITLE_SCALE, TITLE_TRACKING);
        height = BODY_TOP;
        paragraphs.forEach(function (lines, index) {
            height += lines.length * BODY_LINE_HEIGHT;
            if (index < paragraphs.length - 1) height += PARAGRAPH_GAP;
        });
        height = Math.max(height, DIVIDER_Y + 2);

        canvas = ensureCanvas(inner);
        canvas.width = width;
        canvas.height = Math.ceil(height);
        canvas.style.width = width + 'px';
        canvas.style.height = Math.ceil(height) + 'px';
        context = canvas.getContext('2d', { alpha:true });
        if (!context) {
            fail(inner, new Error('Canvas 2D context is unavailable.'));
            return;
        }
        context.imageSmoothingEnabled = false;
        context.clearRect(0, 0, canvas.width, canvas.height);

        drawText(
            context,
            source.title,
            Math.round((width - titleWidth) / 2),
            0,
            TITLE_SCALE,
            TITLE_TRACKING,
            TITLE_COLOR
        );

        /* 완성형 구분선은 폐기했다. 실선 애니메이션은 ManifestoIntro만 담당한다. */

        opticalShift = calculateOpticalShift(flatLines, width);
        y = BODY_TOP;
        paragraphs.forEach(function (lines, paragraphIndex) {
            lines.forEach(function (line) {
                drawText(context, line.text, opticalShift, y, BODY_SCALE, BODY_TRACKING, BODY_COLOR);
                y += BODY_LINE_HEIGHT;
            });
            if (paragraphIndex < paragraphs.length - 1) y += PARAGRAPH_GAP;
        });

        inner.setAttribute('data-bitmap-width', String(width));
        inner.setAttribute('data-bitmap-optical-shift-x', String(opticalShift));
        inner.setAttribute('data-bitmap-state', 'ready');
        inner.classList.add('is-bitmap-ready');
    }

    function fail(inner, error) {
        if (!inner) return;
        inner.classList.remove('is-bitmap-ready');
        inner.setAttribute('data-bitmap-state', 'failed');
        inner.setAttribute('data-bitmap-error', String(error && error.message ? error.message : error));
        try { console.error('[MainPageBitmap]', error); } catch (ignore) {}
    }

    function schedule(inner, force) {
        if (!inner) return;
        window.requestAnimationFrame(function () {
            try { render(inner, force); }
            catch (error) { fail(inner, error); }
        });
    }

    function mount(root) {
        var scope = root && root.querySelectorAll ? root : document;
        var nodes = [];
        if (scope.matches && scope.matches(SELECTOR)) nodes.push(scope);
        nodes = nodes.concat(Array.prototype.slice.call(scope.querySelectorAll(SELECTOR)));
        nodes.forEach(function (inner) {
            if (resizeObserver && (!observed || !observed.has(inner))) {
                resizeObserver.observe(inner);
                if (observed) observed.add(inner);
            }
            schedule(inner, true);
        });
    }

    function recalculate() {
        Array.prototype.forEach.call(document.querySelectorAll(SELECTOR), function (inner) {
            schedule(inner, true);
        });
    }

    function boot() {
        mount(document);
        window.setTimeout(function () { mount(document); }, 120);
        window.setTimeout(function () { mount(document); }, 500);
    }

    if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot, { once:true });
    else boot();

    window.addEventListener('resize', function () {
        window.clearTimeout(resizeTimer);
        resizeTimer = window.setTimeout(recalculate, 100);
    }, { passive:true });

    try {
        if (mw && mw.hook) {
            mw.hook('wikipage.content').add(function (content) {
                mount(content && content[0] ? content[0] : document);
            });
        }
    } catch (ignoreHook) {}

    window.MainPageBitmap = {
        version:VERSION,
        recalculate:recalculate,
        status:function () {
            var inner = document.querySelector(SELECTOR);
            return inner ? {
                integrated:true,
                state:inner.getAttribute('data-bitmap-state') || 'pending',
                error:inner.getAttribute('data-bitmap-error') || '',
                width:inner.getAttribute('data-bitmap-width') || '',
                opticalShiftX:inner.getAttribute('data-bitmap-optical-shift-x') || '',
                canvas:!!inner.querySelector('.main-manifesto-bitmap')
            } : { integrated:true, state:'not-mounted' };
        }
    };

    window.MainPageManifesto = window.MainPageManifesto || {};
    window.MainPageManifesto.recalculate = recalculate;
})(window, document, window.mw);